Merge #9643: [refactor] Remove using namespace <xxx> from wallet/ & util*

a57845c Refactor: Remove using namespace <xxx> from util* (Karl-Johan Alm)
8a52281 Refactor: Remove using namespace <xxx> from wallet/ (Karl-Johan Alm)

Tree-SHA512: cd06b569fee0ce25db753ade5ee694b582733a8883bfd62a27613020266d2a902af079ef23b58a5412f7af4afd7681e689af3c7780e5ea00c77b16d144d72db5
This commit is contained in:
Wladimir J. van der Laan 2017-03-09 08:10:09 +01:00
commit c047b1663d
No known key found for this signature in database
GPG key ID: 74810B012346C9A6
10 changed files with 349 additions and 368 deletions

View file

@ -97,15 +97,15 @@ namespace boost {
} // namespace boost } // namespace boost
using namespace std;
const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf"; const char * const BITCOIN_CONF_FILENAME = "bitcoin.conf";
const char * const BITCOIN_PID_FILENAME = "bitcoind.pid"; const char * const BITCOIN_PID_FILENAME = "bitcoind.pid";
CCriticalSection cs_args; CCriticalSection cs_args;
map<string, string> mapArgs; std::map<std::string, std::string> mapArgs;
static map<string, vector<string> > _mapMultiArgs; static std::map<std::string, std::vector<std::string> > _mapMultiArgs;
const map<string, vector<string> >& mapMultiArgs = _mapMultiArgs; const std::map<std::string, std::vector<std::string> >& mapMultiArgs = _mapMultiArgs;
bool fDebug = false; bool fDebug = false;
bool fPrintToConsole = false; bool fPrintToConsole = false;
bool fPrintToDebugLog = true; bool fPrintToDebugLog = true;
@ -191,7 +191,7 @@ static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT;
*/ */
static FILE* fileout = NULL; static FILE* fileout = NULL;
static boost::mutex* mutexDebugLog = NULL; static boost::mutex* mutexDebugLog = NULL;
static list<string> *vMsgsBeforeOpenLog; static std::list<std::string>* vMsgsBeforeOpenLog;
static int FileWriteStr(const std::string &str, FILE *fp) static int FileWriteStr(const std::string &str, FILE *fp)
{ {
@ -202,7 +202,7 @@ static void DebugPrintInit()
{ {
assert(mutexDebugLog == NULL); assert(mutexDebugLog == NULL);
mutexDebugLog = new boost::mutex(); mutexDebugLog = new boost::mutex();
vMsgsBeforeOpenLog = new list<string>; vMsgsBeforeOpenLog = new std::list<std::string>;
} }
void OpenDebugLog() void OpenDebugLog()
@ -238,22 +238,22 @@ bool LogAcceptCategory(const char* category)
// This helps prevent issues debugging global destructors, // This helps prevent issues debugging global destructors,
// where mapMultiArgs might be deleted before another // where mapMultiArgs might be deleted before another
// global destructor calls LogPrint() // global destructor calls LogPrint()
static boost::thread_specific_ptr<set<string> > ptrCategory; static boost::thread_specific_ptr<std::set<std::string> > ptrCategory;
if (ptrCategory.get() == NULL) if (ptrCategory.get() == NULL)
{ {
if (mapMultiArgs.count("-debug")) { if (mapMultiArgs.count("-debug")) {
const vector<string>& categories = mapMultiArgs.at("-debug"); const std::vector<std::string>& categories = mapMultiArgs.at("-debug");
ptrCategory.reset(new set<string>(categories.begin(), categories.end())); ptrCategory.reset(new std::set<std::string>(categories.begin(), categories.end()));
// thread_specific_ptr automatically deletes the set when the thread ends. // thread_specific_ptr automatically deletes the set when the thread ends.
} else } else
ptrCategory.reset(new set<string>()); ptrCategory.reset(new std::set<std::string>());
} }
const set<string>& setCategories = *ptrCategory.get(); const std::set<std::string>& setCategories = *ptrCategory.get();
// if not debugging everything and not debugging specific category, LogPrint does nothing. // if not debugging everything and not debugging specific category, LogPrint does nothing.
if (setCategories.count(string("")) == 0 && if (setCategories.count(std::string("")) == 0 &&
setCategories.count(string("1")) == 0 && setCategories.count(std::string("1")) == 0 &&
setCategories.count(string(category)) == 0) setCategories.count(std::string(category)) == 0)
return false; return false;
} }
return true; return true;
@ -266,7 +266,7 @@ bool LogAcceptCategory(const char* category)
*/ */
static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine) static std::string LogTimestampStr(const std::string &str, std::atomic_bool *fStartedNewLine)
{ {
string strStamped; std::string strStamped;
if (!fLogTimestamps) if (!fLogTimestamps)
return str; return str;
@ -293,7 +293,7 @@ int LogPrintStr(const std::string &str)
int ret = 0; // Returns total number of characters written int ret = 0; // Returns total number of characters written
static std::atomic_bool fStartedNewLine(true); static std::atomic_bool fStartedNewLine(true);
string strTimestamped = LogTimestampStr(str, &fStartedNewLine); std::string strTimestamped = LogTimestampStr(str, &fStartedNewLine);
if (fPrintToConsole) if (fPrintToConsole)
{ {
@ -561,14 +561,14 @@ void ReadConfigFile(const std::string& confPath)
{ {
LOCK(cs_args); LOCK(cs_args);
set<string> setOptions; std::set<std::string> setOptions;
setOptions.insert("*"); setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) 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 bitcoin.conf // Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key; std::string strKey = std::string("-") + it->string_key;
string strValue = it->value[0]; std::string strValue = it->value[0];
InterpretNegativeSetting(strKey, strValue); InterpretNegativeSetting(strKey, strValue);
if (mapArgs.count(strKey) == 0) if (mapArgs.count(strKey) == 0)
mapArgs[strKey] = strValue; mapArgs[strKey] = strValue;

View file

@ -9,8 +9,6 @@
#include "tinyformat.h" #include "tinyformat.h"
#include "utilstrencodings.h" #include "utilstrencodings.h"
using namespace std;
std::string FormatMoney(const CAmount& n) std::string FormatMoney(const CAmount& n)
{ {
// Note: not using straight sprintf here because we do NOT want // Note: not using straight sprintf here because we do NOT want
@ -18,7 +16,7 @@ std::string FormatMoney(const CAmount& n)
int64_t n_abs = (n > 0 ? n : -n); int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN; int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN; int64_t remainder = n_abs%COIN;
string str = strprintf("%d.%08d", quotient, remainder); std::string str = strprintf("%d.%08d", quotient, remainder);
// Right-trim excess zeros before the decimal point: // Right-trim excess zeros before the decimal point:
int nTrim = 0; int nTrim = 0;
@ -33,14 +31,14 @@ std::string FormatMoney(const CAmount& n)
} }
bool ParseMoney(const string& str, CAmount& nRet) bool ParseMoney(const std::string& str, CAmount& nRet)
{ {
return ParseMoney(str.c_str(), nRet); return ParseMoney(str.c_str(), nRet);
} }
bool ParseMoney(const char* pszIn, CAmount& nRet) bool ParseMoney(const char* pszIn, CAmount& nRet)
{ {
string strWhole; std::string strWhole;
int64_t nUnits = 0; int64_t nUnits = 0;
const char* p = pszIn; const char* p = pszIn;
while (isspace(*p)) while (isspace(*p))

View file

@ -12,20 +12,18 @@
#include <errno.h> #include <errno.h>
#include <limits> #include <limits>
using namespace std; static const std::string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
static const string CHARS_ALPHA_NUM = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; static const std::string SAFE_CHARS[] =
static const string SAFE_CHARS[] =
{ {
CHARS_ALPHA_NUM + " .,;-_/:?@()", // SAFE_CHARS_DEFAULT CHARS_ALPHA_NUM + " .,;-_/:?@()", // SAFE_CHARS_DEFAULT
CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT
CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME
}; };
string SanitizeString(const string& str, int rule) std::string SanitizeString(const std::string& str, int rule)
{ {
string strResult; std::string strResult;
for (std::string::size_type i = 0; i < str.size(); i++) for (std::string::size_type i = 0; i < str.size(); i++)
{ {
if (SAFE_CHARS[rule].find(str[i]) != std::string::npos) if (SAFE_CHARS[rule].find(str[i]) != std::string::npos)
@ -57,7 +55,7 @@ signed char HexDigit(char c)
return p_util_hexdigit[(unsigned char)c]; return p_util_hexdigit[(unsigned char)c];
} }
bool IsHex(const string& str) bool IsHex(const std::string& str)
{ {
for(std::string::const_iterator it(str.begin()); it != str.end(); ++it) for(std::string::const_iterator it(str.begin()); it != str.end(); ++it)
{ {
@ -67,10 +65,10 @@ bool IsHex(const string& str)
return (str.size() > 0) && (str.size()%2 == 0); 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 // convert hex dump to vector
vector<unsigned char> vch; std::vector<unsigned char> vch;
while (true) while (true)
{ {
while (isspace(*psz)) while (isspace(*psz))
@ -88,16 +86,16 @@ vector<unsigned char> ParseHex(const char* psz)
return vch; return vch;
} }
vector<unsigned char> ParseHex(const string& str) std::vector<unsigned char> ParseHex(const std::string& str)
{ {
return ParseHex(str.c_str()); return ParseHex(str.c_str());
} }
string EncodeBase64(const unsigned char* pch, size_t len) std::string EncodeBase64(const unsigned char* pch, size_t len)
{ {
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet=""; std::string strRet = "";
strRet.reserve((len+2)/3*4); strRet.reserve((len+2)/3*4);
int mode=0, left=0; int mode=0, left=0;
@ -139,12 +137,12 @@ string EncodeBase64(const unsigned char* pch, size_t len)
return strRet; return strRet;
} }
string EncodeBase64(const string& str) std::string EncodeBase64(const std::string& str)
{ {
return EncodeBase64((const unsigned char*)str.c_str(), str.size()); 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] = static const int decode64_table[256] =
{ {
@ -166,7 +164,7 @@ vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
if (pfInvalid) if (pfInvalid)
*pfInvalid = false; *pfInvalid = false;
vector<unsigned char> vchRet; std::vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4); vchRet.reserve(strlen(p)*3/4);
int mode = 0; int mode = 0;
@ -227,17 +225,17 @@ vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
return vchRet; return vchRet;
} }
string DecodeBase64(const string& str) std::string DecodeBase64(const std::string& str)
{ {
vector<unsigned char> vchRet = DecodeBase64(str.c_str()); std::vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); return (vchRet.size() == 0) ? std::string() : 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"; static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet=""; std::string strRet="";
strRet.reserve((len+4)/5*8); strRet.reserve((len+4)/5*8);
int mode=0, left=0; int mode=0, left=0;
@ -292,12 +290,12 @@ string EncodeBase32(const unsigned char* pch, size_t len)
return strRet; return strRet;
} }
string EncodeBase32(const string& str) std::string EncodeBase32(const std::string& str)
{ {
return EncodeBase32((const unsigned char*)str.c_str(), str.size()); 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] = static const int decode32_table[256] =
{ {
@ -319,7 +317,7 @@ vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
if (pfInvalid) if (pfInvalid)
*pfInvalid = false; *pfInvalid = false;
vector<unsigned char> vchRet; std::vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8); vchRet.reserve((strlen(p))*5/8);
int mode = 0; int mode = 0;
@ -414,10 +412,10 @@ vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
return vchRet; return vchRet;
} }
string DecodeBase32(const string& str) std::string DecodeBase32(const std::string& str)
{ {
vector<unsigned char> vchRet = DecodeBase32(str.c_str()); std::vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); return (vchRet.size() == 0) ? std::string() : std::string((const char*)&vchRet[0], vchRet.size());
} }
static bool ParsePrechecks(const std::string& str) static bool ParsePrechecks(const std::string& str)

View file

@ -12,8 +12,6 @@
#include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp> #include <boost/thread.hpp>
using namespace std;
static int64_t nMockTime = 0; //!< For unit testing static int64_t nMockTime = 0; //!< For unit testing
int64_t GetTime() int64_t GetTime()

View file

@ -22,9 +22,6 @@
#include <boost/thread.hpp> #include <boost/thread.hpp>
#include <boost/version.hpp> #include <boost/version.hpp>
using namespace std;
// //
// CDB // CDB
// //
@ -117,7 +114,7 @@ bool CDBEnv::Open(const boost::filesystem::path& pathIn)
void CDBEnv::MakeMock() void CDBEnv::MakeMock()
{ {
if (fDbEnvInit) if (fDbEnvInit)
throw runtime_error("CDBEnv::MakeMock: Already initialized"); throw std::runtime_error("CDBEnv::MakeMock: Already initialized");
boost::this_thread::interruption_point(); boost::this_thread::interruption_point();
@ -140,7 +137,7 @@ void CDBEnv::MakeMock()
DB_PRIVATE, DB_PRIVATE,
S_IRUSR | S_IWUSR); S_IRUSR | S_IWUSR);
if (ret > 0) 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; fDbEnvInit = true;
fMockDb = true; fMockDb = true;
@ -214,7 +211,7 @@ bool CDB::Recover(const std::string& filename, void *callbackDataIn, bool (*reco
{ {
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
string strType, strErr; std::string strType, strErr;
if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue)) if (!(*recoverKVcallback)(callbackDataIn, ssKey, ssValue))
continue; continue;
} }
@ -301,7 +298,7 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
if (fAggressive) if (fAggressive)
flags |= DB_AGGRESSIVE; flags |= DB_AGGRESSIVE;
stringstream strDump; std::stringstream strDump;
Db db(dbenv, 0); Db db(dbenv, 0);
int result = db.verify(strFile.c_str(), NULL, &strDump, flags); int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
@ -325,7 +322,7 @@ bool CDBEnv::Salvage(const std::string& strFile, bool fAggressive, std::vector<C
// ... repeated // ... repeated
// DATA=END // DATA=END
string strLine; std::string strLine;
while (!strDump.eof() && strLine != HEADER_END) while (!strDump.eof() && strLine != HEADER_END)
getline(strDump, strLine); // Skip past header getline(strDump, strLine); // Skip past header
@ -378,7 +375,7 @@ CDB::CDB(const std::string& strFilename, const char* pszMode, bool fFlushOnClose
{ {
LOCK(bitdb.cs_db); LOCK(bitdb.cs_db);
if (!bitdb.Open(GetDataDir())) if (!bitdb.Open(GetDataDir()))
throw runtime_error("CDB: Failed to open database environment."); throw std::runtime_error("CDB: Failed to open database environment.");
strFile = strFilename; strFile = strFilename;
++bitdb.mapFileUseCount[strFile]; ++bitdb.mapFileUseCount[strFile];
@ -391,7 +388,7 @@ CDB::CDB(const std::string& strFilename, const char* pszMode, bool fFlushOnClose
DbMpoolFile* mpf = pdb->get_mpf(); DbMpoolFile* mpf = pdb->get_mpf();
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1); ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
if (ret != 0) if (ret != 0)
throw runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFile)); throw std::runtime_error(strprintf("CDB: Failed to configure for no temp file backing for database %s", strFile));
} }
ret = pdb->open(NULL, // Txn pointer ret = pdb->open(NULL, // Txn pointer
@ -406,10 +403,10 @@ CDB::CDB(const std::string& strFilename, const char* pszMode, bool fFlushOnClose
pdb = NULL; pdb = NULL;
--bitdb.mapFileUseCount[strFile]; --bitdb.mapFileUseCount[strFile];
strFile = ""; strFile = "";
throw runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename)); throw std::runtime_error(strprintf("CDB: Error %d, can't open database %s", ret, strFilename));
} }
if (fCreate && !Exists(string("version"))) { if (fCreate && !Exists(std::string("version"))) {
bool fTmp = fReadOnly; bool fTmp = fReadOnly;
fReadOnly = false; fReadOnly = false;
WriteVersion(CLIENT_VERSION); WriteVersion(CLIENT_VERSION);
@ -452,7 +449,7 @@ void CDB::Close()
} }
} }
void CDBEnv::CloseDb(const string& strFile) void CDBEnv::CloseDb(const std::string& strFile)
{ {
{ {
LOCK(cs_db); LOCK(cs_db);
@ -466,7 +463,7 @@ void CDBEnv::CloseDb(const string& strFile)
} }
} }
bool CDBEnv::RemoveDb(const string& strFile) bool CDBEnv::RemoveDb(const std::string& strFile)
{ {
this->CloseDb(strFile); this->CloseDb(strFile);
@ -475,7 +472,7 @@ bool CDBEnv::RemoveDb(const string& strFile)
return (rc == 0); return (rc == 0);
} }
bool CDB::Rewrite(const string& strFile, const char* pszSkip) bool CDB::Rewrite(const std::string& strFile, const char* pszSkip)
{ {
while (true) { while (true) {
{ {
@ -488,7 +485,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
bool fSuccess = true; bool fSuccess = true;
LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile); LogPrintf("CDB::Rewrite: Rewriting %s...\n", strFile);
string strFileRes = strFile + ".rewrite"; std::string strFileRes = strFile + ".rewrite";
{ // surround usage of db with extra {} { // surround usage of db with extra {}
CDB db(strFile.c_str(), "r"); CDB db(strFile.c_str(), "r");
Db* pdbCopy = new Db(bitdb.dbenv, 0); Db* pdbCopy = new Db(bitdb.dbenv, 0);
@ -568,9 +565,9 @@ void CDBEnv::Flush(bool fShutdown)
return; return;
{ {
LOCK(cs_db); LOCK(cs_db);
map<string, int>::iterator mi = mapFileUseCount.begin(); std::map<std::string, int>::iterator mi = mapFileUseCount.begin();
while (mi != mapFileUseCount.end()) { while (mi != mapFileUseCount.end()) {
string strFile = (*mi).first; std::string strFile = (*mi).first;
int nRefCount = (*mi).second; int nRefCount = (*mi).second;
LogPrint("db", "CDBEnv::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount); LogPrint("db", "CDBEnv::Flush: Flushing %s (refcount = %d)...\n", strFile, nRefCount);
if (nRefCount == 0) { if (nRefCount == 0) {
@ -607,7 +604,7 @@ bool CDB::PeriodicFlush(std::string strFile)
{ {
// Don't do this if any databases are in use // Don't do this if any databases are in use
int nRefCount = 0; 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()) while (mi != bitdb.mapFileUseCount.end())
{ {
nRefCount += (*mi).second; nRefCount += (*mi).second;
@ -617,7 +614,7 @@ bool CDB::PeriodicFlush(std::string strFile)
if (nRefCount == 0) if (nRefCount == 0)
{ {
boost::this_thread::interruption_point(); boost::this_thread::interruption_point();
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()) if (mi != bitdb.mapFileUseCount.end())
{ {
LogPrint("db", "Flushing %s\n", strFile); LogPrint("db", "Flushing %s\n", strFile);

View file

@ -29,8 +29,6 @@
#include <boost/assign/list_of.hpp> #include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
using namespace std;
std::string static EncodeDumpTime(int64_t nTime) { std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
} }
@ -82,7 +80,7 @@ UniValue importprivkey(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3) if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw runtime_error( throw std::runtime_error(
"importprivkey \"bitcoinprivkey\" ( \"label\" ) ( rescan )\n" "importprivkey \"bitcoinprivkey\" ( \"label\" ) ( rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n" "\nArguments:\n"
@ -106,8 +104,8 @@ UniValue importprivkey(const JSONRPCRequest& request)
EnsureWalletIsUnlocked(pwallet); EnsureWalletIsUnlocked(pwallet);
string strSecret = request.params[0].get_str(); std::string strSecret = request.params[0].get_str();
string strLabel = ""; std::string strLabel = "";
if (request.params.size() > 1) if (request.params.size() > 1)
strLabel = request.params[1].get_str(); strLabel = request.params[1].get_str();
@ -156,8 +154,8 @@ UniValue importprivkey(const JSONRPCRequest& request)
return NullUniValue; return NullUniValue;
} }
void ImportAddress(CWallet*, const CBitcoinAddress& address, const string& strLabel); void ImportAddress(CWallet*, const CBitcoinAddress& address, const std::string& strLabel);
void ImportScript(CWallet * const pwallet, const CScript& script, const string& strLabel, bool isRedeemScript) void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript)
{ {
if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) { if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
@ -182,7 +180,7 @@ void ImportScript(CWallet * const pwallet, const CScript& script, const string&
} }
} }
void ImportAddress(CWallet * const pwallet, const CBitcoinAddress& address, const string& strLabel) void ImportAddress(CWallet* const pwallet, const CBitcoinAddress& address, const std::string& strLabel)
{ {
CScript script = GetScriptForDestination(address.Get()); CScript script = GetScriptForDestination(address.Get());
ImportScript(pwallet, script, strLabel, false); ImportScript(pwallet, script, strLabel, false);
@ -199,7 +197,7 @@ UniValue importaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw runtime_error( throw std::runtime_error(
"importaddress \"address\" ( \"label\" rescan p2sh )\n" "importaddress \"address\" ( \"label\" rescan p2sh )\n"
"\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n" "\nArguments:\n"
@ -221,7 +219,7 @@ UniValue importaddress(const JSONRPCRequest& request)
); );
string strLabel = ""; std::string strLabel = "";
if (request.params.size() > 1) if (request.params.size() > 1)
strLabel = request.params[1].get_str(); strLabel = request.params[1].get_str();
@ -269,7 +267,7 @@ UniValue importprunedfunds(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 2) if (request.fHelp || request.params.size() != 2)
throw runtime_error( throw std::runtime_error(
"importprunedfunds\n" "importprunedfunds\n"
"\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n" "\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n"
"\nArguments:\n" "\nArguments:\n"
@ -288,8 +286,8 @@ UniValue importprunedfunds(const JSONRPCRequest& request)
ssMB >> merkleBlock; ssMB >> merkleBlock;
//Search partial merkle tree in proof for our transaction and index in valid block //Search partial merkle tree in proof for our transaction and index in valid block
vector<uint256> vMatch; std::vector<uint256> vMatch;
vector<unsigned int> vIndex; std::vector<unsigned int> vIndex;
unsigned int txnIndex = 0; unsigned int txnIndex = 0;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) { if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
@ -298,7 +296,7 @@ UniValue importprunedfunds(const JSONRPCRequest& request)
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()])) if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
vector<uint256>::const_iterator it; std::vector<uint256>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) { if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
} }
@ -330,7 +328,7 @@ UniValue removeprunedfunds(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"removeprunedfunds \"txid\"\n" "removeprunedfunds \"txid\"\n"
"\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will effect wallet balances.\n" "\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will effect wallet balances.\n"
"\nArguments:\n" "\nArguments:\n"
@ -345,9 +343,9 @@ UniValue removeprunedfunds(const JSONRPCRequest& request)
uint256 hash; uint256 hash;
hash.SetHex(request.params[0].get_str()); hash.SetHex(request.params[0].get_str());
vector<uint256> vHash; std::vector<uint256> vHash;
vHash.push_back(hash); vHash.push_back(hash);
vector<uint256> vHashOut; std::vector<uint256> vHashOut;
if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) { if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not properly delete the transaction."); throw JSONRPCError(RPC_INTERNAL_ERROR, "Could not properly delete the transaction.");
@ -368,7 +366,7 @@ UniValue importpubkey(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4) if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw runtime_error( throw std::runtime_error(
"importpubkey \"pubkey\" ( \"label\" rescan )\n" "importpubkey \"pubkey\" ( \"label\" rescan )\n"
"\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n" "\nArguments:\n"
@ -386,7 +384,7 @@ UniValue importpubkey(const JSONRPCRequest& request)
); );
string strLabel = ""; std::string strLabel = "";
if (request.params.size() > 1) if (request.params.size() > 1)
strLabel = request.params[1].get_str(); strLabel = request.params[1].get_str();
@ -428,7 +426,7 @@ UniValue importwallet(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"importwallet \"filename\"\n" "importwallet \"filename\"\n"
"\nImports keys from a wallet dump file (see dumpwallet).\n" "\nImports keys from a wallet dump file (see dumpwallet).\n"
"\nArguments:\n" "\nArguments:\n"
@ -449,7 +447,7 @@ UniValue importwallet(const JSONRPCRequest& request)
EnsureWalletIsUnlocked(pwallet); EnsureWalletIsUnlocked(pwallet);
ifstream file; std::ifstream file;
file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate); file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
if (!file.is_open()) if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
@ -536,7 +534,7 @@ UniValue dumpprivkey(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"dumpprivkey \"address\"\n" "dumpprivkey \"address\"\n"
"\nReveals the private key corresponding to 'address'.\n" "\nReveals the private key corresponding to 'address'.\n"
"Then the importprivkey can be used with this output\n" "Then the importprivkey can be used with this output\n"
@ -554,7 +552,7 @@ UniValue dumpprivkey(const JSONRPCRequest& request)
EnsureWalletIsUnlocked(pwallet); EnsureWalletIsUnlocked(pwallet);
string strAddress = request.params[0].get_str(); std::string strAddress = request.params[0].get_str();
CBitcoinAddress address; CBitcoinAddress address;
if (!address.SetString(strAddress)) if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
@ -577,7 +575,7 @@ UniValue dumpwallet(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"dumpwallet \"filename\"\n" "dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format.\n" "\nDumps all wallet keys in a human-readable format.\n"
"\nArguments:\n" "\nArguments:\n"
@ -591,7 +589,7 @@ UniValue dumpwallet(const JSONRPCRequest& request)
EnsureWalletIsUnlocked(pwallet); EnsureWalletIsUnlocked(pwallet);
ofstream file; std::ofstream file;
file.open(request.params[0].get_str().c_str()); file.open(request.params[0].get_str().c_str());
if (!file.is_open()) if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
@ -675,16 +673,16 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
} }
// Optional fields. // Optional fields.
const string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : ""; const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue(); const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue(); const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
const bool& internal = data.exists("internal") ? data["internal"].get_bool() : false; const bool& internal = data.exists("internal") ? data["internal"].get_bool() : false;
const bool& watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false; const bool& watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
const string& label = data.exists("label") && !internal ? data["label"].get_str() : ""; const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
bool isScript = scriptPubKey.getType() == UniValue::VSTR; bool isScript = scriptPubKey.getType() == UniValue::VSTR;
bool isP2SH = strRedeemScript.length() > 0; bool isP2SH = strRedeemScript.length() > 0;
const string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str(); const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
// Parse the output. // Parse the output.
CScript script; CScript script;
@ -774,7 +772,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
// Import private keys. // Import private keys.
if (keys.size()) { if (keys.size()) {
for (size_t i = 0; i < keys.size(); i++) { for (size_t i = 0; i < keys.size(); i++) {
const string& privkey = keys[i].get_str(); const std::string& privkey = keys[i].get_str();
CBitcoinSecret vchSecret; CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(privkey); bool fGood = vchSecret.SetString(privkey);
@ -814,7 +812,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
} else { } else {
// Import public keys. // Import public keys.
if (pubKeys.size() && keys.size() == 0) { if (pubKeys.size() && keys.size() == 0) {
const string& strPubKey = pubKeys[0].get_str(); const std::string& strPubKey = pubKeys[0].get_str();
if (!IsHex(strPubKey)) { if (!IsHex(strPubKey)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
@ -882,7 +880,7 @@ UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int6
// Import private keys. // Import private keys.
if (keys.size()) { if (keys.size()) {
const string& strPrivkey = keys[0].get_str(); const std::string& strPrivkey = keys[0].get_str();
// Checks. // Checks.
CBitcoinSecret vchSecret; CBitcoinSecret vchSecret;
@ -1001,7 +999,7 @@ UniValue importmulti(const JSONRPCRequest& mainRequest)
// clang-format off // clang-format off
if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2) if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"importmulti \"requests\" \"options\"\n\n" "importmulti \"requests\" \"options\"\n\n"
"Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options).\n\n" "Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options).\n\n"
"Arguments:\n" "Arguments:\n"

View file

@ -27,8 +27,6 @@
#include <univalue.h> #include <univalue.h>
using namespace std;
CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request) CWallet *GetWalletForJSONRPCRequest(const JSONRPCRequest& request)
{ {
return pwalletMain; return pwalletMain;
@ -94,13 +92,13 @@ void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
} }
entry.push_back(Pair("bip125-replaceable", rbfStatus)); entry.push_back(Pair("bip125-replaceable", rbfStatus));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second)); entry.push_back(Pair(item.first, item.second));
} }
string AccountFromValue(const UniValue& value) std::string AccountFromValue(const UniValue& value)
{ {
string strAccount = value.get_str(); std::string strAccount = value.get_str();
if (strAccount == "*") if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount; return strAccount;
@ -114,7 +112,7 @@ UniValue getnewaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 1) if (request.fHelp || request.params.size() > 1)
throw runtime_error( throw std::runtime_error(
"getnewaddress ( \"account\" )\n" "getnewaddress ( \"account\" )\n"
"\nReturns a new Bitcoin address for receiving payments.\n" "\nReturns a new Bitcoin address for receiving payments.\n"
"If 'account' is specified (DEPRECATED), it is added to the address book \n" "If 'account' is specified (DEPRECATED), it is added to the address book \n"
@ -131,7 +129,7 @@ UniValue getnewaddress(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
// Parse the account first so we don't generate a key if there's an error // Parse the account first so we don't generate a key if there's an error
string strAccount; std::string strAccount;
if (request.params.size() > 0) if (request.params.size() > 0)
strAccount = AccountFromValue(request.params[0]); strAccount = AccountFromValue(request.params[0]);
@ -152,7 +150,7 @@ UniValue getnewaddress(const JSONRPCRequest& request)
} }
CBitcoinAddress GetAccountAddress(CWallet * const pwallet, string strAccount, bool bForceNew=false) CBitcoinAddress GetAccountAddress(CWallet* const pwallet, std::string strAccount, bool bForceNew=false)
{ {
CPubKey pubKey; CPubKey pubKey;
if (!pwallet->GetAccountPubkey(pubKey, strAccount, bForceNew)) { if (!pwallet->GetAccountPubkey(pubKey, strAccount, bForceNew)) {
@ -170,7 +168,7 @@ UniValue getaccountaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"getaccountaddress \"account\"\n" "getaccountaddress \"account\"\n"
"\nDEPRECATED. Returns the current Bitcoin address for receiving payments to this account.\n" "\nDEPRECATED. Returns the current Bitcoin address for receiving payments to this account.\n"
"\nArguments:\n" "\nArguments:\n"
@ -187,7 +185,7 @@ UniValue getaccountaddress(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
// Parse the account first so we don't generate a key if there's an error // Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(request.params[0]); std::string strAccount = AccountFromValue(request.params[0]);
UniValue ret(UniValue::VSTR); UniValue ret(UniValue::VSTR);
@ -204,7 +202,7 @@ UniValue getrawchangeaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 1) if (request.fHelp || request.params.size() > 1)
throw runtime_error( throw std::runtime_error(
"getrawchangeaddress\n" "getrawchangeaddress\n"
"\nReturns a new Bitcoin address, for receiving change.\n" "\nReturns a new Bitcoin address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n" "This is for use with raw transactions, NOT normal use.\n"
@ -242,7 +240,7 @@ UniValue setaccount(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"setaccount \"address\" \"account\"\n" "setaccount \"address\" \"account\"\n"
"\nDEPRECATED. Sets the account associated with the given address.\n" "\nDEPRECATED. Sets the account associated with the given address.\n"
"\nArguments:\n" "\nArguments:\n"
@ -259,7 +257,7 @@ UniValue setaccount(const JSONRPCRequest& request)
if (!address.IsValid()) if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
string strAccount; std::string strAccount;
if (request.params.size() > 1) if (request.params.size() > 1)
strAccount = AccountFromValue(request.params[1]); strAccount = AccountFromValue(request.params[1]);
@ -267,7 +265,7 @@ UniValue setaccount(const JSONRPCRequest& request)
if (IsMine(*pwallet, address.Get())) { if (IsMine(*pwallet, address.Get())) {
// Detect when changing the account of an address that is the 'unused current key' of another account: // Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwallet->mapAddressBook.count(address.Get())) { if (pwallet->mapAddressBook.count(address.Get())) {
string strOldAccount = pwallet->mapAddressBook[address.Get()].name; std::string strOldAccount = pwallet->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(pwallet, strOldAccount)) { if (address == GetAccountAddress(pwallet, strOldAccount)) {
GetAccountAddress(pwallet, strOldAccount, true); GetAccountAddress(pwallet, strOldAccount, true);
} }
@ -289,7 +287,7 @@ UniValue getaccount(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"getaccount \"address\"\n" "getaccount \"address\"\n"
"\nDEPRECATED. Returns the account associated with the given address.\n" "\nDEPRECATED. Returns the account associated with the given address.\n"
"\nArguments:\n" "\nArguments:\n"
@ -307,8 +305,8 @@ UniValue getaccount(const JSONRPCRequest& request)
if (!address.IsValid()) if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
string strAccount; std::string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwallet->mapAddressBook.find(address.Get()); std::map<CTxDestination, CAddressBookData>::iterator mi = pwallet->mapAddressBook.find(address.Get());
if (mi != pwallet->mapAddressBook.end() && !(*mi).second.name.empty()) { if (mi != pwallet->mapAddressBook.end() && !(*mi).second.name.empty()) {
strAccount = (*mi).second.name; strAccount = (*mi).second.name;
} }
@ -324,7 +322,7 @@ UniValue getaddressesbyaccount(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"getaddressesbyaccount \"account\"\n" "getaddressesbyaccount \"account\"\n"
"\nDEPRECATED. Returns the list of addresses for the given account.\n" "\nDEPRECATED. Returns the list of addresses for the given account.\n"
"\nArguments:\n" "\nArguments:\n"
@ -341,13 +339,13 @@ UniValue getaddressesbyaccount(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
string strAccount = AccountFromValue(request.params[0]); std::string strAccount = AccountFromValue(request.params[0]);
// Find all addresses that have the given account // Find all addresses that have the given account
UniValue ret(UniValue::VARR); UniValue ret(UniValue::VARR);
for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwallet->mapAddressBook) { for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwallet->mapAddressBook) {
const CBitcoinAddress& address = item.first; const CBitcoinAddress& address = item.first;
const string& strName = item.second.name; const std::string& strName = item.second.name;
if (strName == strAccount) if (strName == strAccount)
ret.push_back(address.ToString()); ret.push_back(address.ToString());
} }
@ -376,7 +374,7 @@ static void SendMoney(CWallet * const pwallet, const CTxDestination &address, CA
CReserveKey reservekey(pwallet); CReserveKey reservekey(pwallet);
CAmount nFeeRequired; CAmount nFeeRequired;
std::string strError; std::string strError;
vector<CRecipient> vecSend; std::vector<CRecipient> vecSend;
int nChangePosRet = -1; int nChangePosRet = -1;
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount}; CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
vecSend.push_back(recipient); vecSend.push_back(recipient);
@ -400,7 +398,7 @@ UniValue sendtoaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 2 || request.params.size() > 5) if (request.fHelp || request.params.size() < 2 || request.params.size() > 5)
throw runtime_error( throw std::runtime_error(
"sendtoaddress \"address\" amount ( \"comment\" \"comment_to\" subtractfeefromamount )\n" "sendtoaddress \"address\" amount ( \"comment\" \"comment_to\" subtractfeefromamount )\n"
"\nSend an amount to a given address.\n" "\nSend an amount to a given address.\n"
+ HelpRequiringPassphrase(pwallet) + + HelpRequiringPassphrase(pwallet) +
@ -460,7 +458,7 @@ UniValue listaddressgroupings(const JSONRPCRequest& request)
} }
if (request.fHelp) if (request.fHelp)
throw runtime_error( throw std::runtime_error(
"listaddressgroupings\n" "listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n" "\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n" "made public by common use as inputs or as the resulting change\n"
@ -485,8 +483,8 @@ UniValue listaddressgroupings(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
UniValue jsonGroupings(UniValue::VARR); UniValue jsonGroupings(UniValue::VARR);
map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances(); std::map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances();
for (set<CTxDestination> grouping : pwallet->GetAddressGroupings()) { for (std::set<CTxDestination> grouping : pwallet->GetAddressGroupings()) {
UniValue jsonGrouping(UniValue::VARR); UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH(CTxDestination address, grouping) BOOST_FOREACH(CTxDestination address, grouping)
{ {
@ -513,7 +511,7 @@ UniValue signmessage(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 2) if (request.fHelp || request.params.size() != 2)
throw runtime_error( throw std::runtime_error(
"signmessage \"address\" \"message\"\n" "signmessage \"address\" \"message\"\n"
"\nSign a message with the private key of an address" "\nSign a message with the private key of an address"
+ HelpRequiringPassphrase(pwallet) + "\n" + HelpRequiringPassphrase(pwallet) + "\n"
@ -537,8 +535,8 @@ UniValue signmessage(const JSONRPCRequest& request)
EnsureWalletIsUnlocked(pwallet); EnsureWalletIsUnlocked(pwallet);
string strAddress = request.params[0].get_str(); std::string strAddress = request.params[0].get_str();
string strMessage = request.params[1].get_str(); std::string strMessage = request.params[1].get_str();
CBitcoinAddress addr(strAddress); CBitcoinAddress addr(strAddress);
if (!addr.IsValid()) if (!addr.IsValid())
@ -557,7 +555,7 @@ UniValue signmessage(const JSONRPCRequest& request)
ss << strMessageMagic; ss << strMessageMagic;
ss << strMessage; ss << strMessage;
vector<unsigned char> vchSig; std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig)) if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
@ -572,7 +570,7 @@ UniValue getreceivedbyaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"getreceivedbyaddress \"address\" ( minconf )\n" "getreceivedbyaddress \"address\" ( minconf )\n"
"\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n" "\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n"
"\nArguments:\n" "\nArguments:\n"
@ -632,7 +630,7 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n" "getreceivedbyaccount \"account\" ( minconf )\n"
"\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n" "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n" "\nArguments:\n"
@ -659,8 +657,8 @@ UniValue getreceivedbyaccount(const JSONRPCRequest& request)
nMinDepth = request.params[1].get_int(); nMinDepth = request.params[1].get_int();
// Get the set of pub keys assigned to account // Get the set of pub keys assigned to account
string strAccount = AccountFromValue(request.params[0]); std::string strAccount = AccountFromValue(request.params[0]);
set<CTxDestination> setAddress = pwallet->GetAccountAddresses(strAccount); std::set<CTxDestination> setAddress = pwallet->GetAccountAddresses(strAccount);
// Tally // Tally
CAmount nAmount = 0; CAmount nAmount = 0;
@ -691,7 +689,7 @@ UniValue getbalance(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 3) if (request.fHelp || request.params.size() > 3)
throw runtime_error( throw std::runtime_error(
"getbalance ( \"account\" minconf include_watchonly )\n" "getbalance ( \"account\" minconf include_watchonly )\n"
"\nIf account is not specified, returns the server's total available balance.\n" "\nIf account is not specified, returns the server's total available balance.\n"
"If account is specified (DEPRECATED), returns the balance in the account.\n" "If account is specified (DEPRECATED), returns the balance in the account.\n"
@ -750,9 +748,9 @@ UniValue getbalance(const JSONRPCRequest& request)
continue; continue;
CAmount allFee; CAmount allFee;
string strSentAccount; std::string strSentAccount;
list<COutputEntry> listReceived; std::list<COutputEntry> listReceived;
list<COutputEntry> listSent; std::list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth) if (wtx.GetDepthInMainChain() >= nMinDepth)
{ {
@ -766,7 +764,7 @@ UniValue getbalance(const JSONRPCRequest& request)
return ValueFromAmount(nBalance); return ValueFromAmount(nBalance);
} }
string strAccount = AccountFromValue(request.params[0]); std::string strAccount = AccountFromValue(request.params[0]);
CAmount nBalance = pwallet->GetAccountBalance(strAccount, nMinDepth, filter); CAmount nBalance = pwallet->GetAccountBalance(strAccount, nMinDepth, filter);
@ -781,7 +779,7 @@ UniValue getunconfirmedbalance(const JSONRPCRequest &request)
} }
if (request.fHelp || request.params.size() > 0) if (request.fHelp || request.params.size() > 0)
throw runtime_error( throw std::runtime_error(
"getunconfirmedbalance\n" "getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n"); "Returns the server's total unconfirmed balance\n");
@ -799,7 +797,7 @@ UniValue movecmd(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 3 || request.params.size() > 5) if (request.fHelp || request.params.size() < 3 || request.params.size() > 5)
throw runtime_error( throw std::runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n" "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n" "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n"
"\nArguments:\n" "\nArguments:\n"
@ -821,15 +819,15 @@ UniValue movecmd(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
string strFrom = AccountFromValue(request.params[0]); std::string strFrom = AccountFromValue(request.params[0]);
string strTo = AccountFromValue(request.params[1]); std::string strTo = AccountFromValue(request.params[1]);
CAmount nAmount = AmountFromValue(request.params[2]); CAmount nAmount = AmountFromValue(request.params[2]);
if (nAmount <= 0) if (nAmount <= 0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
if (request.params.size() > 3) if (request.params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though // unused parameter, used to be nMinDepth, keep type-checking it though
(void)request.params[3].get_int(); (void)request.params[3].get_int();
string strComment; std::string strComment;
if (request.params.size() > 4) if (request.params.size() > 4)
strComment = request.params[4].get_str(); strComment = request.params[4].get_str();
@ -849,7 +847,7 @@ UniValue sendfrom(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 3 || request.params.size() > 6) if (request.fHelp || request.params.size() < 3 || request.params.size() > 6)
throw runtime_error( throw std::runtime_error(
"sendfrom \"fromaccount\" \"toaddress\" amount ( minconf \"comment\" \"comment_to\" )\n" "sendfrom \"fromaccount\" \"toaddress\" amount ( minconf \"comment\" \"comment_to\" )\n"
"\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address." "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a bitcoin address."
+ HelpRequiringPassphrase(pwallet) + "\n" + HelpRequiringPassphrase(pwallet) + "\n"
@ -879,7 +877,7 @@ UniValue sendfrom(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
string strAccount = AccountFromValue(request.params[0]); std::string strAccount = AccountFromValue(request.params[0]);
CBitcoinAddress address(request.params[1].get_str()); CBitcoinAddress address(request.params[1].get_str());
if (!address.IsValid()) if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
@ -918,7 +916,7 @@ UniValue sendmany(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 2 || request.params.size() > 5) if (request.fHelp || request.params.size() < 2 || request.params.size() > 5)
throw runtime_error( throw std::runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] )\n" "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers." "\nSend multiple times. Amounts are double-precision floating point numbers."
+ HelpRequiringPassphrase(pwallet) + "\n" + HelpRequiringPassphrase(pwallet) + "\n"
@ -959,7 +957,7 @@ UniValue sendmany(const JSONRPCRequest& request)
throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
} }
string strAccount = AccountFromValue(request.params[0]); std::string strAccount = AccountFromValue(request.params[0]);
UniValue sendTo = request.params[1].get_obj(); UniValue sendTo = request.params[1].get_obj();
int nMinDepth = 1; int nMinDepth = 1;
if (request.params.size() > 2) if (request.params.size() > 2)
@ -974,19 +972,19 @@ UniValue sendmany(const JSONRPCRequest& request)
if (request.params.size() > 4) if (request.params.size() > 4)
subtractFeeFromAmount = request.params[4].get_array(); subtractFeeFromAmount = request.params[4].get_array();
set<CBitcoinAddress> setAddress; std::set<CBitcoinAddress> setAddress;
vector<CRecipient> vecSend; std::vector<CRecipient> vecSend;
CAmount totalAmount = 0; CAmount totalAmount = 0;
vector<string> keys = sendTo.getKeys(); std::vector<std::string> keys = sendTo.getKeys();
BOOST_FOREACH(const string& name_, keys) BOOST_FOREACH(const std::string& name_, keys)
{ {
CBitcoinAddress address(name_); CBitcoinAddress address(name_);
if (!address.IsValid()) if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+name_); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ")+name_);
if (setAddress.count(address)) if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address); setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get()); CScript scriptPubKey = GetScriptForDestination(address.Get());
@ -1017,7 +1015,7 @@ UniValue sendmany(const JSONRPCRequest& request)
CReserveKey keyChange(pwallet); CReserveKey keyChange(pwallet);
CAmount nFeeRequired = 0; CAmount nFeeRequired = 0;
int nChangePosRet = -1; int nChangePosRet = -1;
string strFailReason; std::string strFailReason;
bool fCreated = pwallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason); bool fCreated = pwallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason);
if (!fCreated) if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
@ -1042,7 +1040,7 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() < 2 || request.params.size() > 3) if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
{ {
string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n" std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n" "\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a Bitcoin address or hex-encoded public key.\n" "Each key is a Bitcoin address or hex-encoded public key.\n"
"If 'account' is specified (DEPRECATED), assign address to that account.\n" "If 'account' is specified (DEPRECATED), assign address to that account.\n"
@ -1065,12 +1063,12 @@ UniValue addmultisigaddress(const JSONRPCRequest& request)
"\nAs json rpc call\n" "\nAs json rpc call\n"
+ HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
; ;
throw runtime_error(msg); throw std::runtime_error(msg);
} }
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
string strAccount; std::string strAccount;
if (request.params.size() > 2) if (request.params.size() > 2)
strAccount = AccountFromValue(request.params[2]); strAccount = AccountFromValue(request.params[2]);
@ -1140,7 +1138,7 @@ UniValue addwitnessaddress(const JSONRPCRequest& request)
if (request.fHelp || request.params.size() < 1 || request.params.size() > 1) if (request.fHelp || request.params.size() < 1 || request.params.size() > 1)
{ {
string msg = "addwitnessaddress \"address\"\n" std::string msg = "addwitnessaddress \"address\"\n"
"\nAdd a witness address for a script (with pubkey or redeemscript known).\n" "\nAdd a witness address for a script (with pubkey or redeemscript known).\n"
"It returns the witness script.\n" "It returns the witness script.\n"
@ -1151,7 +1149,7 @@ UniValue addwitnessaddress(const JSONRPCRequest& request)
"\"witnessaddress\", (string) The value of the new address (P2SH of witness script).\n" "\"witnessaddress\", (string) The value of the new address (P2SH of witness script).\n"
"}\n" "}\n"
; ;
throw runtime_error(msg); throw std::runtime_error(msg);
} }
{ {
@ -1181,7 +1179,7 @@ struct tallyitem
{ {
CAmount nAmount; CAmount nAmount;
int nConf; int nConf;
vector<uint256> txids; std::vector<uint256> txids;
bool fIsWatchonly; bool fIsWatchonly;
tallyitem() tallyitem()
{ {
@ -1209,7 +1207,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
filter = filter | ISMINE_WATCH_ONLY; filter = filter | ISMINE_WATCH_ONLY;
// Tally // Tally
map<CBitcoinAddress, tallyitem> mapTally; std::map<CBitcoinAddress, tallyitem> mapTally;
for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) { for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
const CWalletTx& wtx = pairWtx.second; const CWalletTx& wtx = pairWtx.second;
@ -1232,7 +1230,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
tallyitem& item = mapTally[address]; tallyitem& item = mapTally[address];
item.nAmount += txout.nValue; item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth); item.nConf = std::min(item.nConf, nDepth);
item.txids.push_back(wtx.GetHash()); item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY) if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true; item.fIsWatchonly = true;
@ -1241,11 +1239,11 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
// Reply // Reply
UniValue ret(UniValue::VARR); UniValue ret(UniValue::VARR);
map<string, tallyitem> mapAccountTally; std::map<std::string, tallyitem> mapAccountTally;
for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwallet->mapAddressBook) { for (const std::pair<CBitcoinAddress, CAddressBookData>& item : pwallet->mapAddressBook) {
const CBitcoinAddress& address = item.first; const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name; const std::string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); std::map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty) if (it == mapTally.end() && !fIncludeEmpty)
continue; continue;
@ -1263,7 +1261,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
{ {
tallyitem& _item = mapAccountTally[strAccount]; tallyitem& _item = mapAccountTally[strAccount];
_item.nAmount += nAmount; _item.nAmount += nAmount;
_item.nConf = min(_item.nConf, nConf); _item.nConf = std::min(_item.nConf, nConf);
_item.fIsWatchonly = fIsWatchonly; _item.fIsWatchonly = fIsWatchonly;
} }
else else
@ -1292,7 +1290,7 @@ UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool fByA
if (fByAccounts) if (fByAccounts)
{ {
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) for (std::map<std::string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{ {
CAmount nAmount = (*it).second.nAmount; CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf; int nConf = (*it).second.nConf;
@ -1317,7 +1315,7 @@ UniValue listreceivedbyaddress(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 3) if (request.fHelp || request.params.size() > 3)
throw runtime_error( throw std::runtime_error(
"listreceivedbyaddress ( minconf include_empty include_watchonly)\n" "listreceivedbyaddress ( minconf include_empty include_watchonly)\n"
"\nList balances by receiving address.\n" "\nList balances by receiving address.\n"
"\nArguments:\n" "\nArguments:\n"
@ -1361,7 +1359,7 @@ UniValue listreceivedbyaccount(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 3) if (request.fHelp || request.params.size() > 3)
throw runtime_error( throw std::runtime_error(
"listreceivedbyaccount ( minconf include_empty include_watchonly)\n" "listreceivedbyaccount ( minconf include_empty include_watchonly)\n"
"\nDEPRECATED. List balances by account.\n" "\nDEPRECATED. List balances by account.\n"
"\nArguments:\n" "\nArguments:\n"
@ -1399,16 +1397,16 @@ static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
entry.push_back(Pair("address", addr.ToString())); entry.push_back(Pair("address", addr.ToString()));
} }
void ListTransactions(CWallet * const pwallet, const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) void ListTransactions(CWallet* const pwallet, const CWalletTx& wtx, const std::string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{ {
CAmount nFee; CAmount nFee;
string strSentAccount; std::string strSentAccount;
list<COutputEntry> listReceived; std::list<COutputEntry> listReceived;
list<COutputEntry> listSent; std::list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter); wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*")); bool fAllAccounts = (strAccount == std::string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY); bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent // Sent
@ -1441,7 +1439,7 @@ void ListTransactions(CWallet * const pwallet, const CWalletTx& wtx, const strin
{ {
BOOST_FOREACH(const COutputEntry& r, listReceived) BOOST_FOREACH(const COutputEntry& r, listReceived)
{ {
string account; std::string account;
if (pwallet->mapAddressBook.count(r.destination)) { if (pwallet->mapAddressBook.count(r.destination)) {
account = pwallet->mapAddressBook[r.destination].name; account = pwallet->mapAddressBook[r.destination].name;
} }
@ -1479,9 +1477,9 @@ void ListTransactions(CWallet * const pwallet, const CWalletTx& wtx, const strin
} }
} }
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret) void AcentryToJSON(const CAccountingEntry& acentry, const std::string& strAccount, UniValue& ret)
{ {
bool fAllAccounts = (strAccount == string("*")); bool fAllAccounts = (strAccount == std::string("*"));
if (fAllAccounts || acentry.strAccount == strAccount) if (fAllAccounts || acentry.strAccount == strAccount)
{ {
@ -1504,7 +1502,7 @@ UniValue listtransactions(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 4) if (request.fHelp || request.params.size() > 4)
throw runtime_error( throw std::runtime_error(
"listtransactions ( \"account\" count skip include_watchonly)\n" "listtransactions ( \"account\" count skip include_watchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n" "\nArguments:\n"
@ -1565,7 +1563,7 @@ UniValue listtransactions(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
string strAccount = "*"; std::string strAccount = "*";
if (request.params.size() > 0) if (request.params.size() > 0)
strAccount = request.params[0].get_str(); strAccount = request.params[0].get_str();
int nCount = 10; int nCount = 10;
@ -1607,11 +1605,11 @@ UniValue listtransactions(const JSONRPCRequest& request)
if ((nFrom + nCount) > (int)ret.size()) if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom; nCount = ret.size() - nFrom;
vector<UniValue> arrTmp = ret.getValues(); std::vector<UniValue> arrTmp = ret.getValues();
vector<UniValue>::iterator first = arrTmp.begin(); std::vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom); std::advance(first, nFrom);
vector<UniValue>::iterator last = arrTmp.begin(); std::vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount); std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end()); if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
@ -1634,7 +1632,7 @@ UniValue listaccounts(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 2) if (request.fHelp || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"listaccounts ( minconf include_watchonly)\n" "listaccounts ( minconf include_watchonly)\n"
"\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n" "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n" "\nArguments:\n"
@ -1666,7 +1664,7 @@ UniValue listaccounts(const JSONRPCRequest& request)
if(request.params[1].get_bool()) if(request.params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances; std::map<std::string, CAmount> mapAccountBalances;
for (const std::pair<CTxDestination, CAddressBookData>& entry : pwallet->mapAddressBook) { for (const std::pair<CTxDestination, CAddressBookData>& entry : pwallet->mapAddressBook) {
if (IsMine(*pwallet, entry.first) & includeWatchonly) { // This address belongs to me if (IsMine(*pwallet, entry.first) & includeWatchonly) { // This address belongs to me
mapAccountBalances[entry.second.name] = 0; mapAccountBalances[entry.second.name] = 0;
@ -1676,9 +1674,9 @@ UniValue listaccounts(const JSONRPCRequest& request)
for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) { for (const std::pair<uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
const CWalletTx& wtx = pairWtx.second; const CWalletTx& wtx = pairWtx.second;
CAmount nFee; CAmount nFee;
string strSentAccount; std::string strSentAccount;
list<COutputEntry> listReceived; std::list<COutputEntry> listReceived;
list<COutputEntry> listSent; std::list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain(); int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue; continue;
@ -1697,12 +1695,12 @@ UniValue listaccounts(const JSONRPCRequest& request)
} }
} }
const list<CAccountingEntry> & acentries = pwallet->laccentries; const std::list<CAccountingEntry>& acentries = pwallet->laccentries;
BOOST_FOREACH(const CAccountingEntry& entry, acentries) BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit; mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ); UniValue ret(UniValue::VOBJ);
BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) { BOOST_FOREACH(const PAIRTYPE(std::string, CAmount)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
} }
return ret; return ret;
@ -1716,7 +1714,7 @@ UniValue listsinceblock(const JSONRPCRequest& request)
} }
if (request.fHelp) if (request.fHelp)
throw runtime_error( throw std::runtime_error(
"listsinceblock ( \"blockhash\" target_confirmations include_watchonly)\n" "listsinceblock ( \"blockhash\" target_confirmations include_watchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n" "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n" "\nArguments:\n"
@ -1823,7 +1821,7 @@ UniValue gettransaction(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"gettransaction \"txid\" ( include_watchonly )\n" "gettransaction \"txid\" ( include_watchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n" "\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n" "\nArguments:\n"
@ -1898,7 +1896,7 @@ UniValue gettransaction(const JSONRPCRequest& request)
ListTransactions(pwallet, wtx, "*", 0, false, details, filter); ListTransactions(pwallet, wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details)); entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx), RPCSerializationFlags()); std::string strHex = EncodeHexTx(static_cast<CTransaction>(wtx), RPCSerializationFlags());
entry.push_back(Pair("hex", strHex)); entry.push_back(Pair("hex", strHex));
return entry; return entry;
@ -1912,7 +1910,7 @@ UniValue abandontransaction(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"abandontransaction \"txid\"\n" "abandontransaction \"txid\"\n"
"\nMark in-wallet transaction <txid> as abandoned\n" "\nMark in-wallet transaction <txid> as abandoned\n"
"This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n" "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
@ -1951,7 +1949,7 @@ UniValue backupwallet(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 1) if (request.fHelp || request.params.size() != 1)
throw runtime_error( throw std::runtime_error(
"backupwallet \"destination\"\n" "backupwallet \"destination\"\n"
"\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n" "\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n" "\nArguments:\n"
@ -1963,7 +1961,7 @@ UniValue backupwallet(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
string strDest = request.params[0].get_str(); std::string strDest = request.params[0].get_str();
if (!pwallet->BackupWallet(strDest)) { if (!pwallet->BackupWallet(strDest)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
} }
@ -1980,7 +1978,7 @@ UniValue keypoolrefill(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 1) if (request.fHelp || request.params.size() > 1)
throw runtime_error( throw std::runtime_error(
"keypoolrefill ( newsize )\n" "keypoolrefill ( newsize )\n"
"\nFills the keypool." "\nFills the keypool."
+ HelpRequiringPassphrase(pwallet) + "\n" + HelpRequiringPassphrase(pwallet) + "\n"
@ -2027,7 +2025,7 @@ UniValue walletpassphrase(const JSONRPCRequest& request)
} }
if (pwallet->IsCrypted() && (request.fHelp || request.params.size() != 2)) { if (pwallet->IsCrypted() && (request.fHelp || request.params.size() != 2)) {
throw runtime_error( throw std::runtime_error(
"walletpassphrase \"passphrase\" timeout\n" "walletpassphrase \"passphrase\" timeout\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending bitcoins\n" "This is needed prior to performing transactions related to private keys such as sending bitcoins\n"
@ -2069,7 +2067,7 @@ UniValue walletpassphrase(const JSONRPCRequest& request)
} }
} }
else else
throw runtime_error( throw std::runtime_error(
"walletpassphrase <passphrase> <timeout>\n" "walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds."); "Stores the wallet decryption key in memory for <timeout> seconds.");
@ -2091,7 +2089,7 @@ UniValue walletpassphrasechange(const JSONRPCRequest& request)
} }
if (pwallet->IsCrypted() && (request.fHelp || request.params.size() != 2)) { if (pwallet->IsCrypted() && (request.fHelp || request.params.size() != 2)) {
throw runtime_error( throw std::runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n" "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n" "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n" "\nArguments:\n"
@ -2122,7 +2120,7 @@ UniValue walletpassphrasechange(const JSONRPCRequest& request)
strNewWalletPass = request.params[1].get_str().c_str(); strNewWalletPass = request.params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error( throw std::runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
@ -2142,7 +2140,7 @@ UniValue walletlock(const JSONRPCRequest& request)
} }
if (pwallet->IsCrypted() && (request.fHelp || request.params.size() != 0)) { if (pwallet->IsCrypted() && (request.fHelp || request.params.size() != 0)) {
throw runtime_error( throw std::runtime_error(
"walletlock\n" "walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n" "\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n" "After calling this method, you will need to call walletpassphrase again\n"
@ -2182,7 +2180,7 @@ UniValue encryptwallet(const JSONRPCRequest& request)
} }
if (!pwallet->IsCrypted() && (request.fHelp || request.params.size() != 1)) { if (!pwallet->IsCrypted() && (request.fHelp || request.params.size() != 1)) {
throw runtime_error( throw std::runtime_error(
"encryptwallet \"passphrase\"\n" "encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n" "After this, any calls that interact with private keys such as sending or signing \n"
@ -2221,7 +2219,7 @@ UniValue encryptwallet(const JSONRPCRequest& request)
strWalletPass = request.params[0].get_str().c_str(); strWalletPass = request.params[0].get_str().c_str();
if (strWalletPass.length() < 1) if (strWalletPass.length() < 1)
throw runtime_error( throw std::runtime_error(
"encryptwallet <passphrase>\n" "encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>."); "Encrypts the wallet with <passphrase>.");
@ -2244,7 +2242,7 @@ UniValue lockunspent(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"lockunspent unlock ([{\"txid\":\"txid\",\"vout\":n},...])\n" "lockunspent unlock ([{\"txid\":\"txid\",\"vout\":n},...])\n"
"\nUpdates list of temporarily unspendable outputs.\n" "\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
@ -2308,7 +2306,7 @@ UniValue lockunspent(const JSONRPCRequest& request)
{"vout", UniValueType(UniValue::VNUM)}, {"vout", UniValueType(UniValue::VNUM)},
}); });
string txid = find_value(o, "txid").get_str(); std::string txid = find_value(o, "txid").get_str();
if (!IsHex(txid)) if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
@ -2335,7 +2333,7 @@ UniValue listlockunspent(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 0) if (request.fHelp || request.params.size() > 0)
throw runtime_error( throw std::runtime_error(
"listlockunspent\n" "listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n" "\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n" "See the lockunspent call to lock and unlock transactions for spending.\n"
@ -2362,7 +2360,7 @@ UniValue listlockunspent(const JSONRPCRequest& request)
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
vector<COutPoint> vOutpts; std::vector<COutPoint> vOutpts;
pwallet->ListLockedCoins(vOutpts); pwallet->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR); UniValue ret(UniValue::VARR);
@ -2386,7 +2384,7 @@ UniValue settxfee(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 1) if (request.fHelp || request.params.size() < 1 || request.params.size() > 1)
throw runtime_error( throw std::runtime_error(
"settxfee amount\n" "settxfee amount\n"
"\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n" "\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n"
"\nArguments:\n" "\nArguments:\n"
@ -2415,7 +2413,7 @@ UniValue getwalletinfo(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 0) if (request.fHelp || request.params.size() != 0)
throw runtime_error( throw std::runtime_error(
"getwalletinfo\n" "getwalletinfo\n"
"Returns an object containing various wallet state info.\n" "Returns an object containing various wallet state info.\n"
"\nResult:\n" "\nResult:\n"
@ -2464,7 +2462,7 @@ UniValue resendwallettransactions(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() != 0) if (request.fHelp || request.params.size() != 0)
throw runtime_error( throw std::runtime_error(
"resendwallettransactions\n" "resendwallettransactions\n"
"Immediately re-broadcast unconfirmed wallet transactions to all peers.\n" "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
"Intended only for testing; the wallet code periodically re-broadcasts\n" "Intended only for testing; the wallet code periodically re-broadcasts\n"
@ -2494,7 +2492,7 @@ UniValue listunspent(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() > 4) if (request.fHelp || request.params.size() > 4)
throw runtime_error( throw std::runtime_error(
"listunspent ( minconf maxconf [\"addresses\",...] [include_unsafe] )\n" "listunspent ( minconf maxconf [\"addresses\",...] [include_unsafe] )\n"
"\nReturns array of unspent transaction outputs\n" "\nReturns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n" "with between minconf and maxconf (inclusive) confirmations.\n"
@ -2546,7 +2544,7 @@ UniValue listunspent(const JSONRPCRequest& request)
nMaxDepth = request.params[1].get_int(); nMaxDepth = request.params[1].get_int();
} }
set<CBitcoinAddress> setAddress; std::set<CBitcoinAddress> setAddress;
if (request.params.size() > 2 && !request.params[2].isNull()) { if (request.params.size() > 2 && !request.params[2].isNull()) {
RPCTypeCheckArgument(request.params[2], UniValue::VARR); RPCTypeCheckArgument(request.params[2], UniValue::VARR);
UniValue inputs = request.params[2].get_array(); UniValue inputs = request.params[2].get_array();
@ -2554,9 +2552,9 @@ UniValue listunspent(const JSONRPCRequest& request)
const UniValue& input = inputs[idx]; const UniValue& input = inputs[idx];
CBitcoinAddress address(input.get_str()); CBitcoinAddress address(input.get_str());
if (!address.IsValid()) if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+input.get_str()); throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ")+input.get_str());
if (setAddress.count(address)) 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); setAddress.insert(address);
} }
} }
@ -2568,7 +2566,7 @@ UniValue listunspent(const JSONRPCRequest& request)
} }
UniValue results(UniValue::VARR); UniValue results(UniValue::VARR);
vector<COutput> vecOutputs; std::vector<COutput> vecOutputs;
assert(pwallet != NULL); assert(pwallet != NULL);
LOCK2(cs_main, pwallet->cs_wallet); LOCK2(cs_main, pwallet->cs_wallet);
pwallet->AvailableCoins(vecOutputs, !include_unsafe, NULL, true); pwallet->AvailableCoins(vecOutputs, !include_unsafe, NULL, true);
@ -2622,7 +2620,7 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
} }
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
throw runtime_error( throw std::runtime_error(
"fundrawtransaction \"hexstring\" ( options )\n" "fundrawtransaction \"hexstring\" ( options )\n"
"\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
"This will not modify existing inputs, and will add at most one change output to the outputs.\n" "This will not modify existing inputs, and will add at most one change output to the outputs.\n"
@ -2679,7 +2677,7 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
CFeeRate feeRate = CFeeRate(0); CFeeRate feeRate = CFeeRate(0);
bool overrideEstimatedFeerate = false; bool overrideEstimatedFeerate = false;
UniValue subtractFeeFromOutputs; UniValue subtractFeeFromOutputs;
set<int> setSubtractFeeFromOutputs; std::set<int> setSubtractFeeFromOutputs;
if (request.params.size() > 1) { if (request.params.size() > 1) {
if (request.params[1].type() == UniValue::VBOOL) { if (request.params[1].type() == UniValue::VBOOL) {
@ -2758,7 +2756,7 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
} }
CAmount nFeeOut; CAmount nFeeOut;
string strFailReason; std::string strFailReason;
if (!pwallet->FundTransaction(tx, nFeeOut, overrideEstimatedFeerate, feeRate, changePosition, strFailReason, includeWatching, lockUnspents, setSubtractFeeFromOutputs, reserveChangeKey, changeAddress)) { if (!pwallet->FundTransaction(tx, nFeeOut, overrideEstimatedFeerate, feeRate, changePosition, strFailReason, includeWatching, lockUnspents, setSubtractFeeFromOutputs, reserveChangeKey, changeAddress)) {
throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason); throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason);
@ -2782,14 +2780,14 @@ UniValue fundrawtransaction(const JSONRPCRequest& request)
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, CWallet &wallet) int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, CWallet &wallet)
{ {
CMutableTransaction txNew(tx); CMutableTransaction txNew(tx);
std::vector<pair<CWalletTx *, unsigned int>> vCoins; std::vector<std::pair<CWalletTx*, unsigned int>> vCoins;
// Look up the inputs. We should have already checked that this transaction // Look up the inputs. We should have already checked that this transaction
// IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our // IsAllFromMe(ISMINE_SPENDABLE), so every input should already be in our
// wallet, with a valid index into the vout array. // wallet, with a valid index into the vout array.
for (auto& input : tx.vin) { for (auto& input : tx.vin) {
const auto mi = wallet.mapWallet.find(input.prevout.hash); const auto mi = wallet.mapWallet.find(input.prevout.hash);
assert(mi != wallet.mapWallet.end() && input.prevout.n < mi->second.tx->vout.size()); assert(mi != wallet.mapWallet.end() && input.prevout.n < mi->second.tx->vout.size());
vCoins.emplace_back(make_pair(&(mi->second), input.prevout.n)); vCoins.emplace_back(std::make_pair(&(mi->second), input.prevout.n));
} }
if (!wallet.DummySignTx(txNew, vCoins)) { if (!wallet.DummySignTx(txNew, vCoins)) {
// This should never happen, because IsAllFromMe(ISMINE_SPENDABLE) // This should never happen, because IsAllFromMe(ISMINE_SPENDABLE)
@ -2807,7 +2805,7 @@ UniValue bumpfee(const JSONRPCRequest& request)
return NullUniValue; return NullUniValue;
if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) { if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
throw runtime_error( throw std::runtime_error(
"bumpfee \"txid\" ( options ) \n" "bumpfee \"txid\" ( options ) \n"
"\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n" "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n"
"An opt-in RBF transaction with the given txid must be in the wallet.\n" "An opt-in RBF transaction with the given txid must be in the wallet.\n"

View file

@ -27,16 +27,14 @@ extern UniValue importmulti(const JSONRPCRequest& request);
// we repeat those tests this many times and only complain if all iterations of the test fail // we repeat those tests this many times and only complain if all iterations of the test fail
#define RANDOM_REPEATS 5 #define RANDOM_REPEATS 5
using namespace std;
std::vector<std::unique_ptr<CWalletTx>> wtxn; std::vector<std::unique_ptr<CWalletTx>> wtxn;
typedef set<pair<const CWalletTx*,unsigned int> > CoinSet; typedef std::set<std::pair<const CWalletTx*,unsigned int> > CoinSet;
BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup) BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup)
static const CWallet testWallet; static const CWallet testWallet;
static vector<COutput> vCoins; static std::vector<COutput> vCoins;
static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0)
{ {
@ -69,7 +67,7 @@ static void empty_wallet(void)
static bool equal_sets(CoinSet a, CoinSet b) static bool equal_sets(CoinSet a, CoinSet b)
{ {
pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin()); std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin());
return ret.first == a.end() && ret.second == b.end(); return ret.first == a.end() && ret.second == b.end();
} }

View file

@ -33,8 +33,6 @@
#include <boost/filesystem.hpp> #include <boost/filesystem.hpp>
#include <boost/thread.hpp> #include <boost/thread.hpp>
using namespace std;
CWallet* pwalletMain = NULL; CWallet* pwalletMain = NULL;
/** Transaction fee set by the user */ /** Transaction fee set by the user */
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
@ -66,8 +64,8 @@ const uint256 CMerkleTx::ABANDON_HASH(uint256S("00000000000000000000000000000000
struct CompareValueOnly struct CompareValueOnly
{ {
bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, bool operator()(const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t1,
const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t2) const
{ {
return t1.first < t2.first; return t1.first < t2.first;
} }
@ -186,7 +184,7 @@ bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
} }
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const vector<unsigned char> &vchCryptedSecret) const std::vector<unsigned char> &vchCryptedSecret)
{ {
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false; return false;
@ -404,9 +402,9 @@ bool CWallet::SetMaxVersion(int nVersion)
return true; return true;
} }
set<uint256> CWallet::GetConflicts(const uint256& txid) const std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
{ {
set<uint256> result; std::set<uint256> result;
AssertLockHeld(cs_wallet); AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
@ -471,7 +469,7 @@ bool CWallet::Verify()
return true; return true;
} }
void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
{ {
// We want all the wallet transactions in range to have the same metadata as // We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos). // the oldest (smallest nOrderPos).
@ -515,7 +513,7 @@ void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{ {
const COutPoint outpoint(hash, n); const COutPoint outpoint(hash, n);
pair<TxSpends::const_iterator, TxSpends::const_iterator> range; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint); range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it) for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
@ -533,9 +531,9 @@ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{ {
mapTxSpends.insert(make_pair(outpoint, wtxid)); mapTxSpends.insert(std::make_pair(outpoint, wtxid));
pair<TxSpends::iterator, TxSpends::iterator> range; std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint); range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range); SyncMetaData(range);
} }
@ -661,20 +659,20 @@ DBErrors CWallet::ReorderTransactions()
// Probably a bad idea to change the output of this // Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef multimap<int64_t, TxPair > TxItems; typedef std::multimap<int64_t, TxPair > TxItems;
TxItems txByTime; TxItems txByTime;
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); 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;
walletdb.ListAccountCreditDebit("", acentries); walletdb.ListAccountCreditDebit("", acentries);
BOOST_FOREACH(CAccountingEntry& entry, 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)));
} }
nOrderPosNext = 0; nOrderPosNext = 0;
@ -788,7 +786,7 @@ bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bFo
else { else {
// Check if the current key has been used // Check if the current key has been used
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID()); CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && account.vchPubKey.IsValid(); it != mapWallet.end() && account.vchPubKey.IsValid();
++it) ++it)
BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout) BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
@ -860,7 +858,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
uint256 hash = wtxIn.GetHash(); uint256 hash = wtxIn.GetHash();
// Inserts only if not already there, returns tx inserted or tx found // 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; CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this); wtx.BindWallet(this);
bool fInsertedNew = ret.second; bool fInsertedNew = ret.second;
@ -868,7 +866,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{ {
wtx.nTimeReceived = GetAdjustedTime(); wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&walletdb); wtx.nOrderPos = IncOrderPosNext(&walletdb);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
wtx.nTimeSmart = ComputeTimeSmart(wtx); wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash); AddToSpends(hash);
} }
@ -933,7 +931,7 @@ bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
mapWallet[hash] = wtxIn; mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash]; CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this); wtx.BindWallet(this);
wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0))); wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
AddToSpends(hash); AddToSpends(hash);
BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) { BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
if (mapWallet.count(txin.prevout.hash)) { if (mapWallet.count(txin.prevout.hash)) {
@ -1132,7 +1130,7 @@ isminetype CWallet::IsMine(const CTxIn &txin) const
{ {
{ {
LOCK(cs_wallet); 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()) if (mi != mapWallet.end())
{ {
const CWalletTx& prev = (*mi).second; const CWalletTx& prev = (*mi).second;
@ -1149,7 +1147,7 @@ CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
{ {
{ {
LOCK(cs_wallet); 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()) if (mi != mapWallet.end())
{ {
const CWalletTx& prev = (*mi).second; const CWalletTx& prev = (*mi).second;
@ -1323,7 +1321,7 @@ bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain)) if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
throw runtime_error(std::string(__func__) + ": writing chain failed"); throw std::runtime_error(std::string(__func__) + ": writing chain failed");
hdChain = chain; hdChain = chain;
return true; return true;
@ -1351,7 +1349,7 @@ int CWalletTx::GetRequestCount() const
// Generated block // Generated block
if (!hashUnset()) if (!hashUnset())
{ {
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()) if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second; nRequests = (*mi).second;
} }
@ -1359,7 +1357,7 @@ int CWalletTx::GetRequestCount() const
else else
{ {
// Did anyone request this transaction? // 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()) if (mi != pwallet->mapRequestCount.end())
{ {
nRequests = (*mi).second; nRequests = (*mi).second;
@ -1367,7 +1365,7 @@ int CWalletTx::GetRequestCount() const
// How about the block it's in? // How about the block it's in?
if (nRequests == 0 && !hashUnset()) if (nRequests == 0 && !hashUnset())
{ {
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()) if (_mi != pwallet->mapRequestCount.end())
nRequests = (*_mi).second; nRequests = (*_mi).second;
else else
@ -1379,8 +1377,8 @@ int CWalletTx::GetRequestCount() const
return nRequests; return nRequests;
} }
void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
{ {
nFee = 0; nFee = 0;
listReceived.clear(); listReceived.clear();
@ -1435,15 +1433,15 @@ void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
} }
void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, void CWalletTx::GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
CAmount& nSent, CAmount& nFee, const isminefilter& filter) const CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
{ {
nReceived = nSent = nFee = 0; nReceived = nSent = nFee = 0;
CAmount allFee; CAmount allFee;
string strSentAccount; std::string strSentAccount;
list<COutputEntry> listReceived; std::list<COutputEntry> listReceived;
list<COutputEntry> listSent; std::list<COutputEntry> listSent;
GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (strAccount == strSentAccount) if (strAccount == strSentAccount)
@ -1458,7 +1456,7 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
{ {
if (pwallet->mapAddressBook.count(r.destination)) if (pwallet->mapAddressBook.count(r.destination))
{ {
map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); std::map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
nReceived += r.amount; nReceived += r.amount;
} }
@ -1579,9 +1577,9 @@ bool CWalletTx::RelayWalletTransaction(CConnman* connman)
return false; return false;
} }
set<uint256> CWalletTx::GetConflicts() const std::set<uint256> CWalletTx::GetConflicts() const
{ {
set<uint256> result; std::set<uint256> result;
if (pwallet != NULL) if (pwallet != NULL)
{ {
uint256 myHash = GetHash(); uint256 myHash = GetHash();
@ -1806,14 +1804,14 @@ std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CCon
LOCK(cs_wallet); LOCK(cs_wallet);
// Sort them in chronological order // Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted; std::multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
{ {
CWalletTx& wtx = item.second; CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime: // Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime) if (wtx.nTimeReceived > nTime)
continue; continue;
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
} }
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
{ {
@ -1863,7 +1861,7 @@ CAmount CWallet::GetBalance() const
CAmount nTotal = 0; CAmount nTotal = 0;
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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; const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted()) if (pcoin->IsTrusted())
@ -1879,7 +1877,7 @@ CAmount CWallet::GetUnconfirmedBalance() const
CAmount nTotal = 0; CAmount nTotal = 0;
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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; const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool()) if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
@ -1894,7 +1892,7 @@ CAmount CWallet::GetImmatureBalance() const
CAmount nTotal = 0; CAmount nTotal = 0;
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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; const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit(); nTotal += pcoin->GetImmatureCredit();
@ -1908,7 +1906,7 @@ CAmount CWallet::GetWatchOnlyBalance() const
CAmount nTotal = 0; CAmount nTotal = 0;
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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; const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted()) if (pcoin->IsTrusted())
@ -1924,7 +1922,7 @@ CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
CAmount nTotal = 0; CAmount nTotal = 0;
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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; const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool()) if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
@ -1939,7 +1937,7 @@ CAmount CWallet::GetImmatureWatchOnlyBalance() const
CAmount nTotal = 0; CAmount nTotal = 0;
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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; const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureWatchOnlyCredit(); nTotal += pcoin->GetImmatureWatchOnlyCredit();
@ -1948,13 +1946,13 @@ CAmount CWallet::GetImmatureWatchOnlyBalance() const
return nTotal; return nTotal;
} }
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const void CWallet::AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
{ {
vCoins.clear(); vCoins.clear();
{ {
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, 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 uint256& wtxid = it->first; const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second; const CWalletTx* pcoin = &(*it).second;
@ -2022,10 +2020,10 @@ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const
} }
} }
static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, static void ApproximateBestSubset(std::vector<std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
vector<char>& vfBest, CAmount& nBest, int iterations = 1000) std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{ {
vector<char> vfIncluded; std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true); vfBest.assign(vValue.size(), true);
nBest = nTotalLower; nBest = nTotalLower;
@ -2068,17 +2066,17 @@ static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,uns
} }
} }
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, vector<COutput> vCoins, bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
{ {
setCoinsRet.clear(); setCoinsRet.clear();
nValueRet = 0; nValueRet = 0;
// List of values less than target // List of values less than target
pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger; std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<CAmount>::max(); coinLowestLarger.first = std::numeric_limits<CAmount>::max();
coinLowestLarger.second.first = NULL; coinLowestLarger.second.first = NULL;
vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue; std::vector<std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > > vValue;
CAmount nTotalLower = 0; CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
@ -2099,7 +2097,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMin
int i = output.i; int i = output.i;
CAmount n = pcoin->tx->vout[i].nValue; CAmount n = pcoin->tx->vout[i].nValue;
pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i)); std::pair<CAmount,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
if (n == nTargetValue) if (n == nTargetValue)
{ {
@ -2140,7 +2138,7 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMin
// Solve subset sum by stochastic approximation // Solve subset sum by stochastic approximation
std::sort(vValue.begin(), vValue.end(), CompareValueOnly()); std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
std::reverse(vValue.begin(), vValue.end()); std::reverse(vValue.begin(), vValue.end());
vector<char> vfBest; std::vector<char> vfBest;
CAmount nBest; CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest); ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
@ -2173,9 +2171,9 @@ bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMin
return true; return true;
} }
bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
{ {
vector<COutput> vCoins(vAvailableCoins); std::vector<COutput> vCoins(vAvailableCoins);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure) // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs) if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
@ -2185,13 +2183,13 @@ bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount&
if (!out.fSpendable) if (!out.fSpendable)
continue; continue;
nValueRet += out.tx->tx->vout[out.i].nValue; nValueRet += out.tx->tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i)); setCoinsRet.insert(std::make_pair(out.tx, out.i));
} }
return (nValueRet >= nTargetValue); return (nValueRet >= nTargetValue);
} }
// calculate value from preset inputs and store them // calculate value from preset inputs and store them
set<pair<const CWalletTx*, uint32_t> > setPresetCoins; std::set<std::pair<const CWalletTx*, uint32_t> > setPresetCoins;
CAmount nValueFromPresetInputs = 0; CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs; std::vector<COutPoint> vPresetInputs;
@ -2199,7 +2197,7 @@ bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount&
coinControl->ListSelected(vPresetInputs); coinControl->ListSelected(vPresetInputs);
BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs) BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
{ {
map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end()) if (it != mapWallet.end())
{ {
const CWalletTx* pcoin = &it->second; const CWalletTx* pcoin = &it->second;
@ -2207,15 +2205,15 @@ bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount&
if (pcoin->tx->vout.size() <= outpoint.n) if (pcoin->tx->vout.size() <= outpoint.n)
return false; return false;
nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue; nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
setPresetCoins.insert(make_pair(pcoin, outpoint.n)); setPresetCoins.insert(std::make_pair(pcoin, outpoint.n));
} else } else
return false; // TODO: Allow non-wallet inputs return false; // TODO: Allow non-wallet inputs
} }
// remove preset inputs from vCoins // remove preset inputs from vCoins
for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();) for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
{ {
if (setPresetCoins.count(make_pair(it->tx, it->i))) if (setPresetCoins.count(std::make_pair(it->tx, it->i)))
it = vCoins.erase(it); it = vCoins.erase(it);
else else
++it; ++it;
@ -2244,7 +2242,7 @@ bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount&
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, bool keepReserveKey, const CTxDestination& destChange) bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, bool keepReserveKey, const CTxDestination& destChange)
{ {
vector<CRecipient> vecSend; std::vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector // Turn the txout set into a CRecipient vector
for (size_t idx = 0; idx < tx.vout.size(); idx++) for (size_t idx = 0; idx < tx.vout.size(); idx++)
@ -2298,7 +2296,7 @@ bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool ov
return true; return true;
} }
bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign) int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
{ {
CAmount nValue = 0; CAmount nValue = 0;
@ -2359,7 +2357,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
assert(txNew.nLockTime < LOCKTIME_THRESHOLD); assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
{ {
set<pair<const CWalletTx*,unsigned int> > setCoins; std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
LOCK2(cs_main, cs_wallet); LOCK2(cs_main, cs_wallet);
{ {
std::vector<COutput> vAvailableCoins; std::vector<COutput> vAvailableCoins;
@ -2499,7 +2497,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
return false; return false;
} }
vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut; std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
txNew.vout.insert(position, newTxOut); txNew.vout.insert(position, newTxOut);
} }
} }
@ -2569,7 +2567,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
// to be addressed so we avoid creating too small an output. // to be addressed so we avoid creating too small an output.
if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) { if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount extraFeePaid = nFeeRet - nFeeNeeded; CAmount extraFeePaid = nFeeRet - nFeeNeeded;
vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut; std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
change_position->nValue += extraFeePaid; change_position->nValue += extraFeePaid;
nFeeRet -= extraFeePaid; nFeeRet -= extraFeePaid;
} }
@ -2579,7 +2577,7 @@ bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wt
// Try to reduce change to include necessary fee // Try to reduce change to include necessary fee
if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) { if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet; CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut; std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
// Only reduce change if remaining amount is still a large enough output. // Only reduce change if remaining amount is still a large enough output.
if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) { if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
change_position->nValue -= additionalFeeNeeded; change_position->nValue -= additionalFeeNeeded;
@ -2705,7 +2703,7 @@ bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwa
laccentries.push_back(acentry); laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back(); CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
return true; return true;
} }
@ -2770,7 +2768,7 @@ DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
return DB_LOAD_OK; return DB_LOAD_OK;
} }
DBErrors CWallet::ZapSelectTx(vector<uint256>& vHashIn, vector<uint256>& vHashOut) DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{ {
if (!fFileBacked) if (!fFileBacked)
return DB_LOAD_OK; return DB_LOAD_OK;
@ -2825,7 +2823,7 @@ DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
} }
bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{ {
bool fUpdated = false; bool fUpdated = false;
{ {
@ -2854,7 +2852,7 @@ bool CWallet::DelAddressBook(const CTxDestination& address)
{ {
// Delete destdata tuples associated with address // Delete destdata tuples associated with address
std::string strAddress = CBitcoinAddress(address).ToString(); std::string strAddress = CBitcoinAddress(address).ToString();
BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata) BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
{ {
CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
} }
@ -2897,7 +2895,7 @@ bool CWallet::NewKeyPool()
if (IsLocked()) if (IsLocked())
return false; return false;
int64_t nKeys = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)0); int64_t nKeys = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)0);
for (int i = 0; i < nKeys; i++) for (int i = 0; i < nKeys; i++)
{ {
int64_t nIndex = i+1; int64_t nIndex = i+1;
@ -2924,7 +2922,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
if (kpSize > 0) if (kpSize > 0)
nTargetSize = kpSize; nTargetSize = kpSize;
else else
nTargetSize = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0); nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
while (setKeyPool.size() < (nTargetSize + 1)) while (setKeyPool.size() < (nTargetSize + 1))
{ {
@ -2932,7 +2930,7 @@ bool CWallet::TopUpKeyPool(unsigned int kpSize)
if (!setKeyPool.empty()) if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1; nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error(std::string(__func__) + ": writing generated key failed"); throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
setKeyPool.insert(nEnd); setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
} }
@ -2959,9 +2957,9 @@ void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
nIndex = *(setKeyPool.begin()); nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error(std::string(__func__) + ": read failed"); throw std::runtime_error(std::string(__func__) + ": read failed");
if (!HaveKey(keypool.vchPubKey.GetID())) if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error(std::string(__func__) + ": unknown key in key pool"); throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
assert(keypool.vchPubKey.IsValid()); assert(keypool.vchPubKey.IsValid());
LogPrintf("keypool reserve %d\n", nIndex); LogPrintf("keypool reserve %d\n", nIndex);
} }
@ -3020,14 +3018,14 @@ int64_t CWallet::GetOldestKeyPoolTime()
CWalletDB walletdb(strWalletFile); CWalletDB walletdb(strWalletFile);
int64_t nIndex = *(setKeyPool.begin()); int64_t nIndex = *(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error(std::string(__func__) + ": read oldest key in keypool failed"); throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
assert(keypool.vchPubKey.IsValid()); assert(keypool.vchPubKey.IsValid());
return keypool.nTime; return keypool.nTime;
} }
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{ {
map<CTxDestination, CAmount> balances; std::map<CTxDestination, CAmount> balances;
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
@ -3065,11 +3063,11 @@ std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
return balances; return balances;
} }
set< set<CTxDestination> > CWallet::GetAddressGroupings() std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
{ {
AssertLockHeld(cs_wallet); // mapWallet AssertLockHeld(cs_wallet); // mapWallet
set< set<CTxDestination> > groupings; std::set< std::set<CTxDestination> > groupings;
set<CTxDestination> grouping; std::set<CTxDestination> grouping;
BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
{ {
@ -3122,20 +3120,20 @@ set< set<CTxDestination> > CWallet::GetAddressGroupings()
} }
} }
set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
BOOST_FOREACH(set<CTxDestination> _grouping, groupings) BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
{ {
// make a set of all the groups hit by this new group // make a set of all the groups hit by this new group
set< set<CTxDestination>* > hits; std::set< std::set<CTxDestination>* > hits;
map< CTxDestination, set<CTxDestination>* >::iterator it; std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
BOOST_FOREACH(CTxDestination address, _grouping) BOOST_FOREACH(CTxDestination address, _grouping)
if ((it = setmap.find(address)) != setmap.end()) if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second); hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups // merge all hit groups into a new single group and delete old groups
set<CTxDestination>* merged = new set<CTxDestination>(_grouping); std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
BOOST_FOREACH(set<CTxDestination>* hit, hits) BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
{ {
merged->insert(hit->begin(), hit->end()); merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit); uniqueGroupings.erase(hit);
@ -3148,8 +3146,8 @@ set< set<CTxDestination> > CWallet::GetAddressGroupings()
setmap[element] = merged; setmap[element] = merged;
} }
set< set<CTxDestination> > ret; std::set< std::set<CTxDestination> > ret;
BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings) BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
{ {
ret.insert(*uniqueGrouping); ret.insert(*uniqueGrouping);
delete uniqueGrouping; delete uniqueGrouping;
@ -3169,7 +3167,7 @@ CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAc
CAmount nBalance = 0; CAmount nBalance = 0;
// Tally wallet transactions // Tally wallet transactions
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)
{ {
const CWalletTx& wtx = (*it).second; const CWalletTx& wtx = (*it).second;
if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
@ -3192,11 +3190,11 @@ CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAc
std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
set<CTxDestination> result; std::set<CTxDestination> result;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook) BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
{ {
const CTxDestination& address = item.first; const CTxDestination& address = item.first;
const string& strName = item.second.name; const std::string& strName = item.second.name;
if (strName == strAccount) if (strName == strAccount)
result.insert(address); result.insert(address);
} }
@ -3236,7 +3234,7 @@ void CReserveKey::ReturnKey()
vchPubKey = CPubKey(); vchPubKey = CPubKey();
} }
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
{ {
setAddress.clear(); setAddress.clear();
@ -3247,11 +3245,11 @@ void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{ {
CKeyPool keypool; CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool)) if (!walletdb.ReadPool(id, keypool))
throw runtime_error(std::string(__func__) + ": read failed"); throw std::runtime_error(std::string(__func__) + ": read failed");
assert(keypool.vchPubKey.IsValid()); assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID(); CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID)) if (!HaveKey(keyID))
throw runtime_error(std::string(__func__) + ": unknown key in key pool"); throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
setAddress.insert(keyID); setAddress.insert(keyID);
} }
} }
@ -3261,7 +3259,7 @@ void CWallet::UpdatedTransaction(const uint256 &hashTx)
{ {
LOCK(cs_wallet); LOCK(cs_wallet);
// Only notify UI if this transaction is in this 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()) if (mi != mapWallet.end())
NotifyTransactionChanged(this, hashTx, CT_UPDATED); NotifyTransactionChanged(this, hashTx, CT_UPDATED);
} }
@ -3932,7 +3930,7 @@ int CMerkleTx::GetBlocksToMaturity() const
{ {
if (!IsCoinBase()) if (!IsCoinBase())
return 0; return 0;
return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain()); return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
} }

View file

@ -22,8 +22,6 @@
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
#include <boost/thread.hpp> #include <boost/thread.hpp>
using namespace std;
static uint64_t nAccountingEntryNumber = 0; static uint64_t nAccountingEntryNumber = 0;
static std::atomic<unsigned int> nWalletDBUpdateCounter; static std::atomic<unsigned int> nWalletDBUpdateCounter;
@ -32,30 +30,30 @@ static std::atomic<unsigned int> nWalletDBUpdateCounter;
// CWalletDB // CWalletDB
// //
bool CWalletDB::WriteName(const string& strAddress, const string& strName) bool CWalletDB::WriteName(const std::string& strAddress, const std::string& strName)
{ {
nWalletDBUpdateCounter++; nWalletDBUpdateCounter++;
return Write(make_pair(string("name"), strAddress), strName); return Write(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, // 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. // receiving addresses must always have an address book entry if they're not change return.
nWalletDBUpdateCounter++; nWalletDBUpdateCounter++;
return Erase(make_pair(string("name"), strAddress)); return Erase(make_pair(std::string("name"), strAddress));
} }
bool CWalletDB::WritePurpose(const string& strAddress, const string& strPurpose) bool CWalletDB::WritePurpose(const std::string& strAddress, const std::string& strPurpose)
{ {
nWalletDBUpdateCounter++; nWalletDBUpdateCounter++;
return Write(make_pair(string("purpose"), strAddress), strPurpose); return Write(make_pair(std::string("purpose"), strAddress), strPurpose);
} }
bool CWalletDB::ErasePurpose(const string& strPurpose) bool CWalletDB::ErasePurpose(const std::string& strPurpose)
{ {
nWalletDBUpdateCounter++; nWalletDBUpdateCounter++;
return Erase(make_pair(string("purpose"), strPurpose)); return Erase(make_pair(std::string("purpose"), strPurpose));
} }
bool CWalletDB::WriteTx(const CWalletTx& wtx) bool CWalletDB::WriteTx(const CWalletTx& wtx)
@ -183,15 +181,15 @@ bool CWalletDB::WriteMinVersion(int nVersion)
return Write(std::string("minversion"), nVersion); return Write(std::string("minversion"), nVersion);
} }
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) bool CWalletDB::ReadAccount(const std::string& strAccount, CAccount& account)
{ {
account.SetNull(); account.SetNull();
return Read(make_pair(string("acc"), strAccount), account); return Read(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(make_pair(std::string("acc"), strAccount), account);
} }
bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry)
@ -204,9 +202,9 @@ bool CWalletDB::WriteAccountingEntry_Backend(const CAccountingEntry& acentry)
return WriteAccountingEntry(++nAccountingEntryNumber, acentry); return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
} }
CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount) CAmount CWalletDB::GetAccountCreditDebit(const std::string& strAccount)
{ {
list<CAccountingEntry> entries; std::list<CAccountingEntry> entries;
ListAccountCreditDebit(strAccount, entries); ListAccountCreditDebit(strAccount, entries);
CAmount nCreditDebit = 0; CAmount nCreditDebit = 0;
@ -216,20 +214,20 @@ CAmount CWalletDB::GetAccountCreditDebit(const string& strAccount)
return nCreditDebit; 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 == "*"); bool fAllAccounts = (strAccount == "*");
Dbc* pcursor = GetCursor(); Dbc* pcursor = GetCursor();
if (!pcursor) if (!pcursor)
throw runtime_error(std::string(__func__) + ": cannot create DB cursor"); throw std::runtime_error(std::string(__func__) + ": cannot create DB cursor");
bool setRange = true; bool setRange = true;
while (true) while (true)
{ {
// Read next record // Read next record
CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssKey(SER_DISK, CLIENT_VERSION);
if (setRange) if (setRange)
ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? string("") : strAccount), uint64_t(0))); ssKey << std::make_pair(std::string("acentry"), std::make_pair((fAllAccounts ? std::string("") : strAccount), uint64_t(0)));
CDataStream ssValue(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION);
int ret = ReadAtCursor(pcursor, ssKey, ssValue, setRange); int ret = ReadAtCursor(pcursor, ssKey, ssValue, setRange);
setRange = false; setRange = false;
@ -238,11 +236,11 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin
else if (ret != 0) else if (ret != 0)
{ {
pcursor->close(); pcursor->close();
throw runtime_error(std::string(__func__) + ": error scanning DB"); throw std::runtime_error(std::string(__func__) + ": error scanning DB");
} }
// Unserialize // Unserialize
string strType; std::string strType;
ssKey >> strType; ssKey >> strType;
if (strType != "acentry") if (strType != "acentry")
break; break;
@ -268,7 +266,7 @@ public:
bool fIsEncrypted; bool fIsEncrypted;
bool fAnyUnordered; bool fAnyUnordered;
int nFileVersion; int nFileVersion;
vector<uint256> vWalletUpgrade; std::vector<uint256> vWalletUpgrade;
CWalletScanState() { CWalletScanState() {
nKeys = nCKeys = nWatchKeys = nKeyMeta = 0; nKeys = nCKeys = nWatchKeys = nKeyMeta = 0;
@ -280,7 +278,7 @@ public:
bool bool
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
CWalletScanState &wss, string& strType, string& strErr) CWalletScanState &wss, std::string& strType, std::string& strErr)
{ {
try { try {
// Unserialize // Unserialize
@ -289,13 +287,13 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
ssKey >> strType; ssKey >> strType;
if (strType == "name") if (strType == "name")
{ {
string strAddress; std::string strAddress;
ssKey >> strAddress; ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].name; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].name;
} }
else if (strType == "purpose") else if (strType == "purpose")
{ {
string strAddress; std::string strAddress;
ssKey >> strAddress; ssKey >> strAddress;
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].purpose; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()].purpose;
} }
@ -336,7 +334,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
} }
else if (strType == "acentry") else if (strType == "acentry")
{ {
string strAccount; std::string strAccount;
ssKey >> strAccount; ssKey >> strAccount;
uint64_t nNumber; uint64_t nNumber;
ssKey >> nNumber; ssKey >> nNumber;
@ -449,7 +447,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
strErr = "Error reading wallet database: CPubKey corrupt"; strErr = "Error reading wallet database: CPubKey corrupt";
return false; return false;
} }
vector<unsigned char> vchPrivKey; std::vector<unsigned char> vchPrivKey;
ssValue >> vchPrivKey; ssValue >> vchPrivKey;
wss.nCKeys++; wss.nCKeys++;
@ -562,7 +560,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
LOCK(pwallet->cs_wallet); LOCK(pwallet->cs_wallet);
try { try {
int nMinVersion = 0; int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion)) if (Read((std::string)"minversion", nMinVersion))
{ {
if (nMinVersion > CLIENT_VERSION) if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW; return DB_TOO_NEW;
@ -592,7 +590,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
} }
// Try to be tolerant of single corrupt records: // Try to be tolerant of single corrupt records:
string strType, strErr; std::string strType, strErr;
if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr))
{ {
// losing keys is considered a catastrophic error, anything else // losing keys is considered a catastrophic error, anything else
@ -659,14 +657,14 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
return result; return result;
} }
DBErrors CWalletDB::FindWalletTx(vector<uint256>& vTxHash, vector<CWalletTx>& vWtx) DBErrors CWalletDB::FindWalletTx(std::vector<uint256>& vTxHash, std::vector<CWalletTx>& vWtx)
{ {
bool fNoncriticalErrors = false; bool fNoncriticalErrors = false;
DBErrors result = DB_LOAD_OK; DBErrors result = DB_LOAD_OK;
try { try {
int nMinVersion = 0; int nMinVersion = 0;
if (Read((string)"minversion", nMinVersion)) if (Read((std::string)"minversion", nMinVersion))
{ {
if (nMinVersion > CLIENT_VERSION) if (nMinVersion > CLIENT_VERSION)
return DB_TOO_NEW; return DB_TOO_NEW;
@ -694,7 +692,7 @@ DBErrors CWalletDB::FindWalletTx(vector<uint256>& vTxHash, vector<CWalletTx>& vW
return DB_CORRUPT; return DB_CORRUPT;
} }
string strType; std::string strType;
ssKey >> strType; ssKey >> strType;
if (strType == "tx") { if (strType == "tx") {
uint256 hash; uint256 hash;
@ -722,11 +720,11 @@ DBErrors CWalletDB::FindWalletTx(vector<uint256>& vTxHash, vector<CWalletTx>& vW
return result; return result;
} }
DBErrors CWalletDB::ZapSelectTx(vector<uint256>& vTxHashIn, vector<uint256>& vTxHashOut) DBErrors CWalletDB::ZapSelectTx(std::vector<uint256>& vTxHashIn, std::vector<uint256>& vTxHashOut)
{ {
// build list of wallet TXs and hashes // build list of wallet TXs and hashes
vector<uint256> vTxHash; std::vector<uint256> vTxHash;
vector<CWalletTx> vWtx; std::vector<CWalletTx> vWtx;
DBErrors err = FindWalletTx(vTxHash, vWtx); DBErrors err = FindWalletTx(vTxHash, vWtx);
if (err != DB_LOAD_OK) { if (err != DB_LOAD_OK) {
return err; return err;
@ -737,7 +735,7 @@ DBErrors CWalletDB::ZapSelectTx(vector<uint256>& vTxHashIn, vector<uint256>& vTx
// erase each matching wallet TX // erase each matching wallet TX
bool delerror = false; bool delerror = false;
vector<uint256>::iterator it = vTxHashIn.begin(); std::vector<uint256>::iterator it = vTxHashIn.begin();
BOOST_FOREACH (uint256 hash, vTxHash) { BOOST_FOREACH (uint256 hash, vTxHash) {
while (it < vTxHashIn.end() && (*it) < hash) { while (it < vTxHashIn.end() && (*it) < hash) {
it++; it++;
@ -760,10 +758,10 @@ DBErrors CWalletDB::ZapSelectTx(vector<uint256>& vTxHashIn, vector<uint256>& vTx
return DB_LOAD_OK; return DB_LOAD_OK;
} }
DBErrors CWalletDB::ZapWalletTx(vector<CWalletTx>& vWtx) DBErrors CWalletDB::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{ {
// build list of wallet TXs // build list of wallet TXs
vector<uint256> vTxHash; std::vector<uint256> vTxHash;
DBErrors err = FindWalletTx(vTxHash, vWtx); DBErrors err = FindWalletTx(vTxHash, vWtx);
if (err != DB_LOAD_OK) if (err != DB_LOAD_OK)
return err; return err;