mirror of
https://github.com/cygnusxi/CurecoinSource.git
synced 2025-07-27 23:54:22 +02:00
Merge pull request #69 from sjneph/compile-warnings-round1
Removed global namespace declarations; fixed compiler warnings
This commit is contained in:
commit
d721c6f1fd
@ -4,7 +4,10 @@
|
|||||||
|
|
||||||
#include "addrman.h"
|
#include "addrman.h"
|
||||||
|
|
||||||
using namespace std;
|
#include <algorithm>
|
||||||
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
|
int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
|
||||||
{
|
{
|
||||||
@ -324,7 +327,7 @@ bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePen
|
|||||||
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
|
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
|
||||||
int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
|
int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
|
||||||
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
|
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
|
||||||
pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
|
pinfo->nTime = std::max((int64)0, addr.nTime - nTimePenalty);
|
||||||
|
|
||||||
// add services
|
// add services
|
||||||
pinfo->nServices |= addr.nServices;
|
pinfo->nServices |= addr.nServices;
|
||||||
@ -349,7 +352,7 @@ bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePen
|
|||||||
return false;
|
return false;
|
||||||
} else {
|
} else {
|
||||||
pinfo = Create(addr, source, &nId);
|
pinfo = Create(addr, source, &nId);
|
||||||
pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
|
pinfo->nTime = std::max((int64)0, (int64)pinfo->nTime - nTimePenalty);
|
||||||
// printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
|
// printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
|
||||||
nNew++;
|
nNew++;
|
||||||
fNew = true;
|
fNew = true;
|
||||||
|
@ -11,9 +11,10 @@
|
|||||||
#include "sync.h"
|
#include "sync.h"
|
||||||
#include "ui_interface.h"
|
#include "ui_interface.h"
|
||||||
|
|
||||||
using namespace std;
|
#include <map>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
map<uint256, CAlert> mapAlerts;
|
std::map<uint256, CAlert> mapAlerts;
|
||||||
CCriticalSection cs_mapAlerts;
|
CCriticalSection cs_mapAlerts;
|
||||||
|
|
||||||
static const char* pszMainKey = "043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195";
|
static const char* pszMainKey = "043fa441fd4203d03f5df2b75ea14e36f20d39f43e7a61aa7552ab9bcd7ecb0e77a3be4585b13fcdaa22ef6e51f1ff6f2929bec2494385b086fb86610e33193195";
|
||||||
@ -51,8 +52,8 @@ std::string CUnsignedAlert::ToString() const
|
|||||||
return strprintf(
|
return strprintf(
|
||||||
"CAlert(\n"
|
"CAlert(\n"
|
||||||
" nVersion = %d\n"
|
" nVersion = %d\n"
|
||||||
" nRelayUntil = %"PRI64d"\n"
|
" nRelayUntil = %" PRI64d "\n"
|
||||||
" nExpiration = %"PRI64d"\n"
|
" nExpiration = %" PRI64d "\n"
|
||||||
" nID = %d\n"
|
" nID = %d\n"
|
||||||
" nCancel = %d\n"
|
" nCancel = %d\n"
|
||||||
" setCancel = %s\n"
|
" setCancel = %s\n"
|
||||||
@ -161,7 +162,7 @@ CAlert CAlert::getAlertByHash(const uint256 &hash)
|
|||||||
CAlert retval;
|
CAlert retval;
|
||||||
{
|
{
|
||||||
LOCK(cs_mapAlerts);
|
LOCK(cs_mapAlerts);
|
||||||
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
|
std::map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
|
||||||
if(mi != mapAlerts.end())
|
if(mi != mapAlerts.end())
|
||||||
retval = mi->second;
|
retval = mi->second;
|
||||||
}
|
}
|
||||||
@ -200,7 +201,7 @@ bool CAlert::ProcessAlert()
|
|||||||
{
|
{
|
||||||
LOCK(cs_mapAlerts);
|
LOCK(cs_mapAlerts);
|
||||||
// Cancel previous alerts
|
// Cancel previous alerts
|
||||||
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
|
for (std::map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
|
||||||
{
|
{
|
||||||
const CAlert& alert = (*mi).second;
|
const CAlert& alert = (*mi).second;
|
||||||
if (Cancels(alert))
|
if (Cancels(alert))
|
||||||
@ -231,7 +232,7 @@ bool CAlert::ProcessAlert()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add to mapAlerts
|
// Add to mapAlerts
|
||||||
mapAlerts.insert(make_pair(GetHash(), *this));
|
mapAlerts.insert(std::make_pair(GetHash(), *this));
|
||||||
// Notify UI if it applies to me
|
// Notify UI if it applies to me
|
||||||
if(AppliesToMe())
|
if(AppliesToMe())
|
||||||
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
|
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
#ifndef curecoin_ALLOCATORS_H
|
#ifndef curecoin_ALLOCATORS_H
|
||||||
#define curecoin_ALLOCATORS_H
|
#define curecoin_ALLOCATORS_H
|
||||||
|
|
||||||
#include <string.h>
|
#include <cstring>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <boost/thread/mutex.hpp>
|
#include <boost/thread/mutex.hpp>
|
||||||
#include <map>
|
#include <map>
|
||||||
@ -212,7 +212,7 @@ struct secure_allocator : public std::allocator<T>
|
|||||||
{
|
{
|
||||||
if (p != NULL)
|
if (p != NULL)
|
||||||
{
|
{
|
||||||
memset(p, 0, sizeof(T) * n);
|
std::memset(p, 0, sizeof(T) * n);
|
||||||
LockedPageManager::instance.UnlockRange(p, sizeof(T) * n);
|
LockedPageManager::instance.UnlockRange(p, sizeof(T) * n);
|
||||||
}
|
}
|
||||||
std::allocator<T>::deallocate(p, n);
|
std::allocator<T>::deallocate(p, n);
|
||||||
@ -246,7 +246,7 @@ struct zero_after_free_allocator : public std::allocator<T>
|
|||||||
void deallocate(T* p, std::size_t n)
|
void deallocate(T* p, std::size_t n)
|
||||||
{
|
{
|
||||||
if (p != NULL)
|
if (p != NULL)
|
||||||
memset(p, 0, sizeof(T) * n);
|
std::memset(p, 0, sizeof(T) * n);
|
||||||
std::allocator<T>::deallocate(p, n);
|
std::allocator<T>::deallocate(p, n);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
19
src/base58.h
19
src/base58.h
@ -15,6 +15,7 @@
|
|||||||
#ifndef curecoin_BASE58_H
|
#ifndef curecoin_BASE58_H
|
||||||
#define curecoin_BASE58_H
|
#define curecoin_BASE58_H
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include "bignum.h"
|
#include "bignum.h"
|
||||||
@ -150,7 +151,7 @@ inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRe
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
|
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
|
||||||
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
|
if (std::memcmp(&hash, &vchRet.end()[-4], 4) != 0)
|
||||||
{
|
{
|
||||||
vchRet.clear();
|
vchRet.clear();
|
||||||
return false;
|
return false;
|
||||||
@ -190,7 +191,7 @@ protected:
|
|||||||
{
|
{
|
||||||
// zero the memory, as it may contain sensitive data
|
// zero the memory, as it may contain sensitive data
|
||||||
if (!vchData.empty())
|
if (!vchData.empty())
|
||||||
memset(&vchData[0], 0, vchData.size());
|
std::memset(&vchData[0], 0, vchData.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
void SetData(int nVersionIn, const void* pdata, size_t nSize)
|
void SetData(int nVersionIn, const void* pdata, size_t nSize)
|
||||||
@ -198,7 +199,7 @@ protected:
|
|||||||
nVersion = nVersionIn;
|
nVersion = nVersionIn;
|
||||||
vchData.resize(nSize);
|
vchData.resize(nSize);
|
||||||
if (!vchData.empty())
|
if (!vchData.empty())
|
||||||
memcpy(&vchData[0], pdata, nSize);
|
std::memcpy(&vchData[0], pdata, nSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
|
void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend)
|
||||||
@ -220,8 +221,8 @@ public:
|
|||||||
nVersion = vchTemp[0];
|
nVersion = vchTemp[0];
|
||||||
vchData.resize(vchTemp.size() - 1);
|
vchData.resize(vchTemp.size() - 1);
|
||||||
if (!vchData.empty())
|
if (!vchData.empty())
|
||||||
memcpy(&vchData[0], &vchTemp[1], vchData.size());
|
std::memcpy(&vchData[0], &vchTemp[1], vchData.size());
|
||||||
memset(&vchTemp[0], 0, vchTemp.size());
|
std::memset(&vchTemp[0], 0, vchTemp.size());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -353,13 +354,13 @@ public:
|
|||||||
case PUBKEY_ADDRESS:
|
case PUBKEY_ADDRESS:
|
||||||
case PUBKEY_ADDRESS_TEST: {
|
case PUBKEY_ADDRESS_TEST: {
|
||||||
uint160 id;
|
uint160 id;
|
||||||
memcpy(&id, &vchData[0], 20);
|
std::memcpy(&id, &vchData[0], 20);
|
||||||
return CKeyID(id);
|
return CKeyID(id);
|
||||||
}
|
}
|
||||||
case SCRIPT_ADDRESS:
|
case SCRIPT_ADDRESS:
|
||||||
case SCRIPT_ADDRESS_TEST: {
|
case SCRIPT_ADDRESS_TEST: {
|
||||||
uint160 id;
|
uint160 id;
|
||||||
memcpy(&id, &vchData[0], 20);
|
std::memcpy(&id, &vchData[0], 20);
|
||||||
return CScriptID(id);
|
return CScriptID(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -373,7 +374,7 @@ public:
|
|||||||
case PUBKEY_ADDRESS:
|
case PUBKEY_ADDRESS:
|
||||||
case PUBKEY_ADDRESS_TEST: {
|
case PUBKEY_ADDRESS_TEST: {
|
||||||
uint160 id;
|
uint160 id;
|
||||||
memcpy(&id, &vchData[0], 20);
|
std::memcpy(&id, &vchData[0], 20);
|
||||||
keyID = CKeyID(id);
|
keyID = CKeyID(id);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -414,7 +415,7 @@ public:
|
|||||||
{
|
{
|
||||||
CSecret vchSecret;
|
CSecret vchSecret;
|
||||||
vchSecret.resize(32);
|
vchSecret.resize(32);
|
||||||
memcpy(&vchSecret[0], &vchData[0], 32);
|
std::memcpy(&vchSecret[0], &vchData[0], 32);
|
||||||
fCompressedOut = vchData.size() == 33;
|
fCompressedOut = vchData.size() == 33;
|
||||||
return vchSecret;
|
return vchSecret;
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,7 @@
|
|||||||
#include <openssl/aes.h>
|
#include <openssl/aes.h>
|
||||||
#include <openssl/evp.h>
|
#include <openssl/evp.h>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
#include <cstring>
|
||||||
#include <string>
|
#include <string>
|
||||||
#ifdef WIN32
|
#ifdef WIN32
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
@ -24,8 +25,8 @@ bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::v
|
|||||||
|
|
||||||
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
|
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
|
||||||
{
|
{
|
||||||
memset(&chKey, 0, sizeof chKey);
|
std::memset(&chKey, 0, sizeof chKey);
|
||||||
memset(&chIV, 0, sizeof chIV);
|
std::memset(&chIV, 0, sizeof chIV);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,8 +39,8 @@ bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigne
|
|||||||
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
|
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
|
std::memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
|
||||||
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
|
std::memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
|
||||||
|
|
||||||
fKeySet = true;
|
fKeySet = true;
|
||||||
return true;
|
return true;
|
||||||
@ -104,7 +105,7 @@ bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, con
|
|||||||
{
|
{
|
||||||
CCrypter cKeyCrypter;
|
CCrypter cKeyCrypter;
|
||||||
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
|
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
|
||||||
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
|
std::memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
|
||||||
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
|
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
|
||||||
return false;
|
return false;
|
||||||
return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext);
|
return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext);
|
||||||
@ -114,7 +115,7 @@ bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned
|
|||||||
{
|
{
|
||||||
CCrypter cKeyCrypter;
|
CCrypter cKeyCrypter;
|
||||||
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
|
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
|
||||||
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
|
std::memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
|
||||||
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
|
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
|
||||||
return false;
|
return false;
|
||||||
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
|
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
|
||||||
|
@ -8,6 +8,8 @@
|
|||||||
#include "key.h"
|
#include "key.h"
|
||||||
#include "serialize.h"
|
#include "serialize.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
|
const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
|
||||||
const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
|
const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
|
||||||
|
|
||||||
@ -76,8 +78,8 @@ public:
|
|||||||
|
|
||||||
void CleanKey()
|
void CleanKey()
|
||||||
{
|
{
|
||||||
memset(&chKey, 0, sizeof chKey);
|
std::memset(&chKey, 0, sizeof chKey);
|
||||||
memset(&chIV, 0, sizeof chIV);
|
std::memset(&chIV, 0, sizeof chIV);
|
||||||
fKeySet = false;
|
fKeySet = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -24,21 +24,22 @@
|
|||||||
#include <boost/asio/ssl.hpp>
|
#include <boost/asio/ssl.hpp>
|
||||||
#include <boost/filesystem/fstream.hpp>
|
#include <boost/filesystem/fstream.hpp>
|
||||||
#include <boost/shared_ptr.hpp>
|
#include <boost/shared_ptr.hpp>
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
#include <list>
|
#include <list>
|
||||||
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <sstream>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#define printf OutputDebugStringF
|
#define printf OutputDebugStringF
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
using namespace boost;
|
|
||||||
using namespace boost::asio;
|
|
||||||
using namespace json_spirit;
|
|
||||||
|
|
||||||
void ThreadRPCServer2(void* parg);
|
void ThreadRPCServer2(void* parg);
|
||||||
|
|
||||||
static std::string strRPCUserColonPass;
|
static std::string strRPCUserColonPass;
|
||||||
|
|
||||||
const Object emptyobj;
|
|
||||||
|
|
||||||
void ThreadRPCServer3(void* parg);
|
void ThreadRPCServer3(void* parg);
|
||||||
|
|
||||||
static inline unsigned short GetDefaultRPCPort()
|
static inline unsigned short GetDefaultRPCPort()
|
||||||
@ -46,55 +47,55 @@ static inline unsigned short GetDefaultRPCPort()
|
|||||||
return GetBoolArg("-testnet", false) ? DEF_TESTNET_RPCPORT : DEF_RPCPORT;
|
return GetBoolArg("-testnet", false) ? DEF_TESTNET_RPCPORT : DEF_RPCPORT;
|
||||||
}
|
}
|
||||||
|
|
||||||
Object JSONRPCError(int code, const string& message)
|
json_spirit::Object JSONRPCError(int code, const std::string& message)
|
||||||
{
|
{
|
||||||
Object error;
|
json_spirit::Object error;
|
||||||
error.push_back(Pair("code", code));
|
error.push_back(json_spirit::Pair("code", code));
|
||||||
error.push_back(Pair("message", message));
|
error.push_back(json_spirit::Pair("message", message));
|
||||||
return error;
|
return error;
|
||||||
}
|
}
|
||||||
|
|
||||||
void RPCTypeCheck(const Array& params,
|
void RPCTypeCheck(const json_spirit::Array& params,
|
||||||
const list<Value_type>& typesExpected,
|
const std::list<json_spirit::Value_type>& typesExpected,
|
||||||
bool fAllowNull)
|
bool fAllowNull)
|
||||||
{
|
{
|
||||||
unsigned int i = 0;
|
unsigned int i = 0;
|
||||||
BOOST_FOREACH(Value_type t, typesExpected)
|
BOOST_FOREACH(json_spirit::Value_type t, typesExpected)
|
||||||
{
|
{
|
||||||
if (params.size() <= i)
|
if (params.size() <= i)
|
||||||
break;
|
break;
|
||||||
|
|
||||||
const Value& v = params[i];
|
const json_spirit::Value& v = params[i];
|
||||||
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
|
if (!((v.type() == t) || (fAllowNull && (v.type() == json_spirit::null_type))))
|
||||||
{
|
{
|
||||||
string err = strprintf("Expected type %s, got %s",
|
std::string err = strprintf("Expected type %s, got %s",
|
||||||
Value_type_name[t], Value_type_name[v.type()]);
|
json_spirit::Value_type_name[t], json_spirit::Value_type_name[v.type()]);
|
||||||
throw JSONRPCError(RPC_TYPE_ERROR, err);
|
throw JSONRPCError(RPC_TYPE_ERROR, err);
|
||||||
}
|
}
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void RPCTypeCheck(const Object& o,
|
void RPCTypeCheck(const json_spirit::Object& o,
|
||||||
const map<string, Value_type>& typesExpected,
|
const std::map<std::string, json_spirit::Value_type>& typesExpected,
|
||||||
bool fAllowNull)
|
bool fAllowNull)
|
||||||
{
|
{
|
||||||
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
|
BOOST_FOREACH(const PAIRTYPE(std::string, json_spirit::Value_type)& t, typesExpected)
|
||||||
{
|
{
|
||||||
const Value& v = find_value(o, t.first);
|
const json_spirit::Value& v = find_value(o, t.first);
|
||||||
if (!fAllowNull && v.type() == null_type)
|
if (!fAllowNull && v.type() == json_spirit::null_type)
|
||||||
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
|
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
|
||||||
|
|
||||||
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
|
if (!((v.type() == t.second) || (fAllowNull && (v.type() == json_spirit::null_type))))
|
||||||
{
|
{
|
||||||
string err = strprintf("Expected type %s for %s, got %s",
|
std::string err = strprintf("Expected type %s for %s, got %s",
|
||||||
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
|
json_spirit::Value_type_name[t.second], t.first.c_str(), json_spirit::Value_type_name[v.type()]);
|
||||||
throw JSONRPCError(RPC_TYPE_ERROR, err);
|
throw JSONRPCError(RPC_TYPE_ERROR, err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int64 AmountFromValue(const Value& value)
|
int64 AmountFromValue(const json_spirit::Value& value)
|
||||||
{
|
{
|
||||||
double dAmount = value.get_real();
|
double dAmount = value.get_real();
|
||||||
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
|
if (dAmount <= 0.0 || dAmount > MAX_MONEY)
|
||||||
@ -105,7 +106,7 @@ int64 AmountFromValue(const Value& value)
|
|||||||
return nAmount;
|
return nAmount;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value ValueFromAmount(int64 amount)
|
json_spirit::Value ValueFromAmount(int64 amount)
|
||||||
{
|
{
|
||||||
return (double)amount / (double)COIN;
|
return (double)amount / (double)COIN;
|
||||||
}
|
}
|
||||||
@ -126,22 +127,22 @@ std::string HexBits(unsigned int nBits)
|
|||||||
/// Note: This interface may still be subject to change.
|
/// Note: This interface may still be subject to change.
|
||||||
///
|
///
|
||||||
|
|
||||||
string CRPCTable::help(string strCommand) const
|
std::string CRPCTable::help(std::string strCommand) const
|
||||||
{
|
{
|
||||||
string strRet;
|
std::string strRet;
|
||||||
set<rpcfn_type> setDone;
|
std::set<rpcfn_type> setDone;
|
||||||
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
|
for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
|
||||||
{
|
{
|
||||||
const CRPCCommand *pcmd = mi->second;
|
const CRPCCommand *pcmd = mi->second;
|
||||||
string strMethod = mi->first;
|
std::string strMethod = mi->first;
|
||||||
// We already filter duplicates, but these deprecated screw up the sort order
|
// We already filter duplicates, but these deprecated screw up the sort order
|
||||||
if (strMethod.find("label") != string::npos)
|
if (strMethod.find("label") != std::string::npos)
|
||||||
continue;
|
continue;
|
||||||
if (strCommand != "" && strMethod != strCommand)
|
if (strCommand != "" && strMethod != strCommand)
|
||||||
continue;
|
continue;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Array params;
|
json_spirit::Array params;
|
||||||
rpcfn_type pfn = pcmd->actor;
|
rpcfn_type pfn = pcmd->actor;
|
||||||
if (setDone.insert(pfn).second)
|
if (setDone.insert(pfn).second)
|
||||||
(*pfn)(params, true);
|
(*pfn)(params, true);
|
||||||
@ -149,9 +150,9 @@ string CRPCTable::help(string strCommand) const
|
|||||||
catch (std::exception& e)
|
catch (std::exception& e)
|
||||||
{
|
{
|
||||||
// Help text is returned in an exception
|
// Help text is returned in an exception
|
||||||
string strHelp = string(e.what());
|
std::string strHelp = std::string(e.what());
|
||||||
if (strCommand == "")
|
if (strCommand == "")
|
||||||
if (strHelp.find('\n') != string::npos)
|
if (strHelp.find('\n') != std::string::npos)
|
||||||
strHelp = strHelp.substr(0, strHelp.find('\n'));
|
strHelp = strHelp.substr(0, strHelp.find('\n'));
|
||||||
strRet += strHelp + "\n";
|
strRet += strHelp + "\n";
|
||||||
}
|
}
|
||||||
@ -162,14 +163,14 @@ string CRPCTable::help(string strCommand) const
|
|||||||
return strRet;
|
return strRet;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value help(const Array& params, bool fHelp)
|
json_spirit::Value help(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 1)
|
if (fHelp || params.size() > 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"help [command]\n"
|
"help [command]\n"
|
||||||
"List commands, or get help for a command.");
|
"List commands, or get help for a command.");
|
||||||
|
|
||||||
string strCommand;
|
std::string strCommand;
|
||||||
if (params.size() > 0)
|
if (params.size() > 0)
|
||||||
strCommand = params[0].get_str();
|
strCommand = params[0].get_str();
|
||||||
|
|
||||||
@ -177,10 +178,10 @@ Value help(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value stop(const Array& params, bool fHelp)
|
json_spirit::Value stop(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 1)
|
if (fHelp || params.size() > 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"stop <detach>\n"
|
"stop <detach>\n"
|
||||||
"<detach> is true or false to detach the database or not for this stop only\n"
|
"<detach> is true or false to detach the database or not for this stop only\n"
|
||||||
"Stop curecoin server (and possibly override the detachdb config value).");
|
"Stop curecoin server (and possibly override the detachdb config value).");
|
||||||
@ -282,9 +283,9 @@ CRPCTable::CRPCTable()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const CRPCCommand *CRPCTable::operator[](string name) const
|
const CRPCCommand *CRPCTable::operator[](std::string name) const
|
||||||
{
|
{
|
||||||
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
|
std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
|
||||||
if (it == mapCommands.end())
|
if (it == mapCommands.end())
|
||||||
return NULL;
|
return NULL;
|
||||||
return (*it).second;
|
return (*it).second;
|
||||||
@ -297,9 +298,9 @@ const CRPCCommand *CRPCTable::operator[](string name) const
|
|||||||
// and to be compatible with other JSON-RPC implementations.
|
// and to be compatible with other JSON-RPC implementations.
|
||||||
//
|
//
|
||||||
|
|
||||||
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
|
std::string HTTPPost(const std::string& strMsg, const std::map<std::string,std::string>& mapRequestHeaders)
|
||||||
{
|
{
|
||||||
ostringstream s;
|
std::ostringstream s;
|
||||||
s << "POST / HTTP/1.1\r\n"
|
s << "POST / HTTP/1.1\r\n"
|
||||||
<< "User-Agent: curecoin-json-rpc/" << FormatFullVersion() << "\r\n"
|
<< "User-Agent: curecoin-json-rpc/" << FormatFullVersion() << "\r\n"
|
||||||
<< "Host: 127.0.0.1\r\n"
|
<< "Host: 127.0.0.1\r\n"
|
||||||
@ -307,27 +308,27 @@ string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeader
|
|||||||
<< "Content-Length: " << strMsg.size() << "\r\n"
|
<< "Content-Length: " << strMsg.size() << "\r\n"
|
||||||
<< "Connection: close\r\n"
|
<< "Connection: close\r\n"
|
||||||
<< "Accept: application/json\r\n";
|
<< "Accept: application/json\r\n";
|
||||||
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
|
BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, mapRequestHeaders)
|
||||||
s << item.first << ": " << item.second << "\r\n";
|
s << item.first << ": " << item.second << "\r\n";
|
||||||
s << "\r\n" << strMsg;
|
s << "\r\n" << strMsg;
|
||||||
|
|
||||||
return s.str();
|
return s.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
string rfc1123Time()
|
std::string rfc1123Time()
|
||||||
{
|
{
|
||||||
char buffer[64];
|
char buffer[64];
|
||||||
time_t now;
|
time_t now;
|
||||||
time(&now);
|
time(&now);
|
||||||
struct tm* now_gmt = gmtime(&now);
|
struct tm* now_gmt = gmtime(&now);
|
||||||
string locale(setlocale(LC_TIME, NULL));
|
std::string locale(setlocale(LC_TIME, NULL));
|
||||||
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
|
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
|
||||||
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
|
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
|
||||||
setlocale(LC_TIME, locale.c_str());
|
setlocale(LC_TIME, locale.c_str());
|
||||||
return string(buffer);
|
return std::string(buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
|
static std::string HTTPReply(int nStatus, const std::string& strMsg, bool keepalive)
|
||||||
{
|
{
|
||||||
if (nStatus == HTTP_UNAUTHORIZED)
|
if (nStatus == HTTP_UNAUTHORIZED)
|
||||||
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
|
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
|
||||||
@ -357,7 +358,7 @@ static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
|
|||||||
"HTTP/1.1 %d %s\r\n"
|
"HTTP/1.1 %d %s\r\n"
|
||||||
"Date: %s\r\n"
|
"Date: %s\r\n"
|
||||||
"Connection: %s\r\n"
|
"Connection: %s\r\n"
|
||||||
"Content-Length: %"PRIszu"\r\n"
|
"Content-Length: %" PRIszu "\r\n"
|
||||||
"Content-Type: application/json\r\n"
|
"Content-Type: application/json\r\n"
|
||||||
"Server: curecoin-json-rpc/%s\r\n"
|
"Server: curecoin-json-rpc/%s\r\n"
|
||||||
"\r\n"
|
"\r\n"
|
||||||
@ -373,9 +374,9 @@ static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
|
|||||||
|
|
||||||
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
|
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
|
||||||
{
|
{
|
||||||
string str;
|
std::string str;
|
||||||
getline(stream, str);
|
getline(stream, str);
|
||||||
vector<string> vWords;
|
std::vector<std::string> vWords;
|
||||||
boost::split(vWords, str, boost::is_any_of(" "));
|
boost::split(vWords, str, boost::is_any_of(" "));
|
||||||
if (vWords.size() < 2)
|
if (vWords.size() < 2)
|
||||||
return HTTP_INTERNAL_SERVER_ERROR;
|
return HTTP_INTERNAL_SERVER_ERROR;
|
||||||
@ -386,22 +387,22 @@ int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
|
|||||||
return atoi(vWords[1].c_str());
|
return atoi(vWords[1].c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
|
int ReadHTTPHeader(std::basic_istream<char>& stream, std::map<std::string, std::string>& mapHeadersRet)
|
||||||
{
|
{
|
||||||
int nLen = 0;
|
int nLen = 0;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
string str;
|
std::string str;
|
||||||
std::getline(stream, str);
|
std::getline(stream, str);
|
||||||
if (str.empty() || str == "\r")
|
if (str.empty() || str == "\r")
|
||||||
break;
|
break;
|
||||||
string::size_type nColon = str.find(":");
|
std::string::size_type nColon = str.find(":");
|
||||||
if (nColon != string::npos)
|
if (nColon != std::string::npos)
|
||||||
{
|
{
|
||||||
string strHeader = str.substr(0, nColon);
|
std::string strHeader = str.substr(0, nColon);
|
||||||
boost::trim(strHeader);
|
boost::trim(strHeader);
|
||||||
boost::to_lower(strHeader);
|
boost::to_lower(strHeader);
|
||||||
string strValue = str.substr(nColon+1);
|
std::string strValue = str.substr(nColon+1);
|
||||||
boost::trim(strValue);
|
boost::trim(strValue);
|
||||||
mapHeadersRet[strHeader] = strValue;
|
mapHeadersRet[strHeader] = strValue;
|
||||||
if (strHeader == "content-length")
|
if (strHeader == "content-length")
|
||||||
@ -411,7 +412,7 @@ int ReadHTTPHeader(std::basic_istream<char>& stream, map<string, string>& mapHea
|
|||||||
return nLen;
|
return nLen;
|
||||||
}
|
}
|
||||||
|
|
||||||
int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet)
|
int ReadHTTP(std::basic_istream<char>& stream, std::map<std::string, std::string>& mapHeadersRet, std::string& strMessageRet)
|
||||||
{
|
{
|
||||||
mapHeadersRet.clear();
|
mapHeadersRet.clear();
|
||||||
strMessageRet = "";
|
strMessageRet = "";
|
||||||
@ -428,12 +429,12 @@ int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRe
|
|||||||
// Read message
|
// Read message
|
||||||
if (nLen > 0)
|
if (nLen > 0)
|
||||||
{
|
{
|
||||||
vector<char> vch(nLen);
|
std::vector<char> vch(nLen);
|
||||||
stream.read(&vch[0], nLen);
|
stream.read(&vch[0], nLen);
|
||||||
strMessageRet = string(vch.begin(), vch.end());
|
strMessageRet = std::string(vch.begin(), vch.end());
|
||||||
}
|
}
|
||||||
|
|
||||||
string sConHdr = mapHeadersRet["connection"];
|
std::string sConHdr = mapHeadersRet["connection"];
|
||||||
|
|
||||||
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
|
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
|
||||||
{
|
{
|
||||||
@ -446,13 +447,13 @@ int ReadHTTP(std::basic_istream<char>& stream, map<string, string>& mapHeadersRe
|
|||||||
return nStatus;
|
return nStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool HTTPAuthorized(map<string, string>& mapHeaders)
|
bool HTTPAuthorized(std::map<std::string, std::string>& mapHeaders)
|
||||||
{
|
{
|
||||||
string strAuth = mapHeaders["authorization"];
|
std::string strAuth = mapHeaders["authorization"];
|
||||||
if (strAuth.substr(0,6) != "Basic ")
|
if (strAuth.substr(0,6) != "Basic ")
|
||||||
return false;
|
return false;
|
||||||
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
|
std::string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
|
||||||
string strUserPass = DecodeBase64(strUserPass64);
|
std::string strUserPass = DecodeBase64(strUserPass64);
|
||||||
return strUserPass == strRPCUserColonPass;
|
return strUserPass == strRPCUserColonPass;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -466,41 +467,41 @@ bool HTTPAuthorized(map<string, string>& mapHeaders)
|
|||||||
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
|
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
|
||||||
//
|
//
|
||||||
|
|
||||||
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
|
std::string JSONRPCRequest(const std::string& strMethod, const json_spirit::Array& params, const json_spirit::Value& id)
|
||||||
{
|
{
|
||||||
Object request;
|
json_spirit::Object request;
|
||||||
request.push_back(Pair("method", strMethod));
|
request.push_back(json_spirit::Pair("method", strMethod));
|
||||||
request.push_back(Pair("params", params));
|
request.push_back(json_spirit::Pair("params", params));
|
||||||
request.push_back(Pair("id", id));
|
request.push_back(json_spirit::Pair("id", id));
|
||||||
return write_string(Value(request), false) + "\n";
|
return write_string(json_spirit::Value(request), false) + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
|
json_spirit::Object JSONRPCReplyObj(const json_spirit::Value& result, const json_spirit::Value& error, const json_spirit::Value& id)
|
||||||
{
|
{
|
||||||
Object reply;
|
json_spirit::Object reply;
|
||||||
if (error.type() != null_type)
|
if (error.type() != json_spirit::null_type)
|
||||||
reply.push_back(Pair("result", Value::null));
|
reply.push_back(json_spirit::Pair("result", json_spirit::Value::null));
|
||||||
else
|
else
|
||||||
reply.push_back(Pair("result", result));
|
reply.push_back(json_spirit::Pair("result", result));
|
||||||
reply.push_back(Pair("error", error));
|
reply.push_back(json_spirit::Pair("error", error));
|
||||||
reply.push_back(Pair("id", id));
|
reply.push_back(json_spirit::Pair("id", id));
|
||||||
return reply;
|
return reply;
|
||||||
}
|
}
|
||||||
|
|
||||||
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
|
std::string JSONRPCReply(const json_spirit::Value& result, const json_spirit::Value& error, const json_spirit::Value& id)
|
||||||
{
|
{
|
||||||
Object reply = JSONRPCReplyObj(result, error, id);
|
json_spirit::Object reply = JSONRPCReplyObj(result, error, id);
|
||||||
return write_string(Value(reply), false) + "\n";
|
return write_string(json_spirit::Value(reply), false) + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
|
void ErrorReply(std::ostream& stream, const json_spirit::Object& objError, const json_spirit::Value& id)
|
||||||
{
|
{
|
||||||
// Send error reply from json-rpc error object
|
// Send error reply from json-rpc error object
|
||||||
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
|
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
|
||||||
int code = find_value(objError, "code").get_int();
|
int code = find_value(objError, "code").get_int();
|
||||||
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
|
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
|
||||||
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
|
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
|
||||||
string strReply = JSONRPCReply(Value::null, objError, id);
|
std::string strReply = JSONRPCReply(json_spirit::Value::null, objError, id);
|
||||||
stream << HTTPReply(nStatus, strReply, false) << std::flush;
|
stream << HTTPReply(nStatus, strReply, false) << std::flush;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -512,16 +513,16 @@ bool ClientAllowed(const boost::asio::ip::address& address)
|
|||||||
|| address.to_v6().is_v4_mapped()))
|
|| address.to_v6().is_v4_mapped()))
|
||||||
return ClientAllowed(address.to_v6().to_v4());
|
return ClientAllowed(address.to_v6().to_v4());
|
||||||
|
|
||||||
if (address == asio::ip::address_v4::loopback()
|
if (address == boost::asio::ip::address_v4::loopback()
|
||||||
|| address == asio::ip::address_v6::loopback()
|
|| address == boost::asio::ip::address_v6::loopback()
|
||||||
|| (address.is_v4()
|
|| (address.is_v4()
|
||||||
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
|
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
|
||||||
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
|
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
const string strAddress = address.to_string();
|
const std::string strAddress = address.to_string();
|
||||||
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
|
const std::vector<std::string>& vAllow = mapMultiArgs["-rpcallowip"];
|
||||||
BOOST_FOREACH(string strAllow, vAllow)
|
BOOST_FOREACH(std::string strAllow, vAllow)
|
||||||
if (WildcardMatch(strAddress, strAllow))
|
if (WildcardMatch(strAddress, strAllow))
|
||||||
return true;
|
return true;
|
||||||
return false;
|
return false;
|
||||||
@ -531,15 +532,15 @@ bool ClientAllowed(const boost::asio::ip::address& address)
|
|||||||
// IOStream device that speaks SSL but can also speak non-SSL
|
// IOStream device that speaks SSL but can also speak non-SSL
|
||||||
//
|
//
|
||||||
template <typename Protocol>
|
template <typename Protocol>
|
||||||
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
|
class SSLIOStreamDevice : public boost::iostreams::device<boost::iostreams::bidirectional> {
|
||||||
public:
|
public:
|
||||||
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
|
SSLIOStreamDevice(boost::asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
|
||||||
{
|
{
|
||||||
fUseSSL = fUseSSLIn;
|
fUseSSL = fUseSSLIn;
|
||||||
fNeedHandshake = fUseSSLIn;
|
fNeedHandshake = fUseSSLIn;
|
||||||
}
|
}
|
||||||
|
|
||||||
void handshake(ssl::stream_base::handshake_type role)
|
void handshake(boost::asio::ssl::stream_base::handshake_type role)
|
||||||
{
|
{
|
||||||
if (!fNeedHandshake) return;
|
if (!fNeedHandshake) return;
|
||||||
fNeedHandshake = false;
|
fNeedHandshake = false;
|
||||||
@ -547,23 +548,23 @@ public:
|
|||||||
}
|
}
|
||||||
std::streamsize read(char* s, std::streamsize n)
|
std::streamsize read(char* s, std::streamsize n)
|
||||||
{
|
{
|
||||||
handshake(ssl::stream_base::server); // HTTPS servers read first
|
handshake(boost::asio::ssl::stream_base::server); // HTTPS servers read first
|
||||||
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
|
if (fUseSSL) return stream.read_some(boost::asio::buffer(s, n));
|
||||||
return stream.next_layer().read_some(asio::buffer(s, n));
|
return stream.next_layer().read_some(boost::asio::buffer(s, n));
|
||||||
}
|
}
|
||||||
std::streamsize write(const char* s, std::streamsize n)
|
std::streamsize write(const char* s, std::streamsize n)
|
||||||
{
|
{
|
||||||
handshake(ssl::stream_base::client); // HTTPS clients write first
|
handshake(boost::asio::ssl::stream_base::client); // HTTPS clients write first
|
||||||
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
|
if (fUseSSL) return boost::asio::write(stream, boost::asio::buffer(s, n));
|
||||||
return asio::write(stream.next_layer(), asio::buffer(s, n));
|
return boost::asio::write(stream.next_layer(), boost::asio::buffer(s, n));
|
||||||
}
|
}
|
||||||
bool connect(const std::string& server, const std::string& port)
|
bool connect(const std::string& server, const std::string& port)
|
||||||
{
|
{
|
||||||
ip::tcp::resolver resolver(GetIOService(stream));
|
boost::asio::ip::tcp::resolver resolver(GetIOService(stream));
|
||||||
ip::tcp::resolver::query query(server.c_str(), port.c_str());
|
boost::asio::ip::tcp::resolver::query query(server.c_str(), port.c_str());
|
||||||
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
|
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
|
||||||
ip::tcp::resolver::iterator end;
|
boost::asio::ip::tcp::resolver::iterator end;
|
||||||
boost::system::error_code error = asio::error::host_not_found;
|
boost::system::error_code error = boost::asio::error::host_not_found;
|
||||||
while (error && endpoint_iterator != end)
|
while (error && endpoint_iterator != end)
|
||||||
{
|
{
|
||||||
stream.lowest_layer().close();
|
stream.lowest_layer().close();
|
||||||
@ -577,7 +578,7 @@ public:
|
|||||||
private:
|
private:
|
||||||
bool fNeedHandshake;
|
bool fNeedHandshake;
|
||||||
bool fUseSSL;
|
bool fUseSSL;
|
||||||
asio::ssl::stream<typename Protocol::socket>& stream;
|
boost::asio::ssl::stream<typename Protocol::socket>& stream;
|
||||||
};
|
};
|
||||||
|
|
||||||
class AcceptedConnection
|
class AcceptedConnection
|
||||||
@ -595,8 +596,8 @@ class AcceptedConnectionImpl : public AcceptedConnection
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
AcceptedConnectionImpl(
|
AcceptedConnectionImpl(
|
||||||
asio::io_service& io_service,
|
boost::asio::io_service& io_service,
|
||||||
ssl::context &context,
|
boost::asio::ssl::context &context,
|
||||||
bool fUseSSL) :
|
bool fUseSSL) :
|
||||||
sslStream(io_service, context),
|
sslStream(io_service, context),
|
||||||
_d(sslStream, fUseSSL),
|
_d(sslStream, fUseSSL),
|
||||||
@ -620,11 +621,11 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
typename Protocol::endpoint peer;
|
typename Protocol::endpoint peer;
|
||||||
asio::ssl::stream<typename Protocol::socket> sslStream;
|
boost::asio::ssl::stream<typename Protocol::socket> sslStream;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
SSLIOStreamDevice<Protocol> _d;
|
SSLIOStreamDevice<Protocol> _d;
|
||||||
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
|
boost::iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
|
||||||
};
|
};
|
||||||
|
|
||||||
void ThreadRPCServer(void* parg)
|
void ThreadRPCServer(void* parg)
|
||||||
@ -650,8 +651,8 @@ void ThreadRPCServer(void* parg)
|
|||||||
|
|
||||||
// Forward declaration required for RPCListen
|
// Forward declaration required for RPCListen
|
||||||
template <typename Protocol, typename SocketAcceptorService>
|
template <typename Protocol, typename SocketAcceptorService>
|
||||||
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
|
static void RPCAcceptHandler(boost::shared_ptr< boost::asio::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
|
||||||
ssl::context& context,
|
boost::asio::ssl::context& context,
|
||||||
bool fUseSSL,
|
bool fUseSSL,
|
||||||
AcceptedConnection* conn,
|
AcceptedConnection* conn,
|
||||||
const boost::system::error_code& error);
|
const boost::system::error_code& error);
|
||||||
@ -660,8 +661,8 @@ static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol,
|
|||||||
* Sets up I/O resources to accept and handle a new connection.
|
* Sets up I/O resources to accept and handle a new connection.
|
||||||
*/
|
*/
|
||||||
template <typename Protocol, typename SocketAcceptorService>
|
template <typename Protocol, typename SocketAcceptorService>
|
||||||
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
|
static void RPCListen(boost::shared_ptr< boost::asio::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
|
||||||
ssl::context& context,
|
boost::asio::ssl::context& context,
|
||||||
const bool fUseSSL)
|
const bool fUseSSL)
|
||||||
{
|
{
|
||||||
// Accept connection
|
// Accept connection
|
||||||
@ -682,8 +683,8 @@ static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketA
|
|||||||
* Accept and handle incoming connection.
|
* Accept and handle incoming connection.
|
||||||
*/
|
*/
|
||||||
template <typename Protocol, typename SocketAcceptorService>
|
template <typename Protocol, typename SocketAcceptorService>
|
||||||
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
|
static void RPCAcceptHandler(boost::shared_ptr< boost::asio::basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
|
||||||
ssl::context& context,
|
boost::asio::ssl::context& context,
|
||||||
const bool fUseSSL,
|
const bool fUseSSL,
|
||||||
AcceptedConnection* conn,
|
AcceptedConnection* conn,
|
||||||
const boost::system::error_code& error)
|
const boost::system::error_code& error)
|
||||||
@ -691,11 +692,11 @@ static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol,
|
|||||||
vnThreadsRunning[THREAD_RPCLISTENER]++;
|
vnThreadsRunning[THREAD_RPCLISTENER]++;
|
||||||
|
|
||||||
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
|
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
|
||||||
if (error != asio::error::operation_aborted
|
if (error != boost::asio::error::operation_aborted
|
||||||
&& acceptor->is_open())
|
&& acceptor->is_open())
|
||||||
RPCListen(acceptor, context, fUseSSL);
|
RPCListen(acceptor, context, fUseSSL);
|
||||||
|
|
||||||
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
|
AcceptedConnectionImpl<boost::asio::ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<boost::asio::ip::tcp>* >(conn);
|
||||||
|
|
||||||
// TODO: Actually handle errors
|
// TODO: Actually handle errors
|
||||||
if (error)
|
if (error)
|
||||||
@ -733,7 +734,7 @@ void ThreadRPCServer2(void* parg)
|
|||||||
{
|
{
|
||||||
unsigned char rand_pwd[32];
|
unsigned char rand_pwd[32];
|
||||||
RAND_bytes(rand_pwd, 32);
|
RAND_bytes(rand_pwd, 32);
|
||||||
string strWhatAmI = "To use curecoind";
|
std::string strWhatAmI = "To use curecoind";
|
||||||
if (mapArgs.count("-server"))
|
if (mapArgs.count("-server"))
|
||||||
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
|
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
|
||||||
else if (mapArgs.count("-daemon"))
|
else if (mapArgs.count("-daemon"))
|
||||||
@ -755,12 +756,12 @@ void ThreadRPCServer2(void* parg)
|
|||||||
|
|
||||||
const bool fUseSSL = GetBoolArg("-rpcssl");
|
const bool fUseSSL = GetBoolArg("-rpcssl");
|
||||||
|
|
||||||
asio::io_service io_service;
|
boost::asio::io_service io_service;
|
||||||
|
|
||||||
ssl::context context(ssl::context::sslv23);
|
boost::asio::ssl::context context(boost::asio::ssl::context::sslv23);
|
||||||
if (fUseSSL)
|
if (fUseSSL)
|
||||||
{
|
{
|
||||||
context.set_options(ssl::context::no_sslv2);
|
context.set_options(boost::asio::ssl::context::no_sslv2);
|
||||||
|
|
||||||
boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
|
boost::filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
|
||||||
if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile;
|
if (!pathCertFile.is_complete()) pathCertFile = boost::filesystem::path(GetDataDir()) / pathCertFile;
|
||||||
@ -769,19 +770,19 @@ void ThreadRPCServer2(void* parg)
|
|||||||
|
|
||||||
boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
|
boost::filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
|
||||||
if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile;
|
if (!pathPKFile.is_complete()) pathPKFile = boost::filesystem::path(GetDataDir()) / pathPKFile;
|
||||||
if (boost::filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), ssl::context::pem);
|
if (boost::filesystem::exists(pathPKFile)) context.use_private_key_file(pathPKFile.string(), boost::asio::ssl::context::pem);
|
||||||
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
|
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
|
||||||
|
|
||||||
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
|
std::string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
|
||||||
SSL_CTX_set_cipher_list(context.native_handle(), strCiphers.c_str());
|
SSL_CTX_set_cipher_list(context.native_handle(), strCiphers.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
|
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
|
||||||
const bool loopback = !mapArgs.count("-rpcallowip");
|
const bool loopback = !mapArgs.count("-rpcallowip");
|
||||||
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
|
boost::asio::ip::address bindAddress = loopback ? boost::asio::ip::address_v6::loopback() : boost::asio::ip::address_v6::any();
|
||||||
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
|
boost::asio::ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
|
||||||
boost::system::error_code v6_only_error;
|
boost::system::error_code v6_only_error;
|
||||||
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(io_service));
|
boost::shared_ptr<boost::asio::ip::tcp::acceptor> acceptor(new boost::asio::ip::tcp::acceptor(io_service));
|
||||||
|
|
||||||
boost::signals2::signal<void ()> StopRequests;
|
boost::signals2::signal<void ()> StopRequests;
|
||||||
|
|
||||||
@ -796,12 +797,12 @@ void ThreadRPCServer2(void* parg)
|
|||||||
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
|
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
|
||||||
|
|
||||||
acceptor->bind(endpoint);
|
acceptor->bind(endpoint);
|
||||||
acceptor->listen(socket_base::max_connections);
|
acceptor->listen(boost::asio::socket_base::max_connections);
|
||||||
|
|
||||||
RPCListen(acceptor, context, fUseSSL);
|
RPCListen(acceptor, context, fUseSSL);
|
||||||
// Cancel outstanding listen-requests for this acceptor when shutting down
|
// Cancel outstanding listen-requests for this acceptor when shutting down
|
||||||
StopRequests.connect(signals2::slot<void ()>(
|
StopRequests.connect(boost::signals2::slot<void ()>(
|
||||||
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
|
static_cast<void (boost::asio::ip::tcp::acceptor::*)()>(&boost::asio::ip::tcp::acceptor::close), acceptor.get())
|
||||||
.track(acceptor));
|
.track(acceptor));
|
||||||
|
|
||||||
fListening = true;
|
fListening = true;
|
||||||
@ -815,19 +816,19 @@ void ThreadRPCServer2(void* parg)
|
|||||||
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
|
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
|
||||||
if (!fListening || loopback || v6_only_error)
|
if (!fListening || loopback || v6_only_error)
|
||||||
{
|
{
|
||||||
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
|
bindAddress = loopback ? boost::asio::ip::address_v4::loopback() : boost::asio::ip::address_v4::any();
|
||||||
endpoint.address(bindAddress);
|
endpoint.address(bindAddress);
|
||||||
|
|
||||||
acceptor.reset(new ip::tcp::acceptor(io_service));
|
acceptor.reset(new boost::asio::ip::tcp::acceptor(io_service));
|
||||||
acceptor->open(endpoint.protocol());
|
acceptor->open(endpoint.protocol());
|
||||||
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
|
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
|
||||||
acceptor->bind(endpoint);
|
acceptor->bind(endpoint);
|
||||||
acceptor->listen(socket_base::max_connections);
|
acceptor->listen(boost::asio::socket_base::max_connections);
|
||||||
|
|
||||||
RPCListen(acceptor, context, fUseSSL);
|
RPCListen(acceptor, context, fUseSSL);
|
||||||
// Cancel outstanding listen-requests for this acceptor when shutting down
|
// Cancel outstanding listen-requests for this acceptor when shutting down
|
||||||
StopRequests.connect(signals2::slot<void ()>(
|
StopRequests.connect(boost::signals2::slot<void ()>(
|
||||||
static_cast<void (ip::tcp::acceptor::*)()>(&ip::tcp::acceptor::close), acceptor.get())
|
static_cast<void (boost::asio::ip::tcp::acceptor::*)()>(&boost::asio::ip::tcp::acceptor::close), acceptor.get())
|
||||||
.track(acceptor));
|
.track(acceptor));
|
||||||
|
|
||||||
fListening = true;
|
fListening = true;
|
||||||
@ -854,75 +855,75 @@ void ThreadRPCServer2(void* parg)
|
|||||||
class JSONRequest
|
class JSONRequest
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
Value id;
|
json_spirit::Value id;
|
||||||
string strMethod;
|
std::string strMethod;
|
||||||
Array params;
|
json_spirit::Array params;
|
||||||
|
|
||||||
JSONRequest() { id = Value::null; }
|
JSONRequest() { id = json_spirit::Value::null; }
|
||||||
void parse(const Value& valRequest);
|
void parse(const json_spirit::Value& valRequest);
|
||||||
};
|
};
|
||||||
|
|
||||||
void JSONRequest::parse(const Value& valRequest)
|
void JSONRequest::parse(const json_spirit::Value& valRequest)
|
||||||
{
|
{
|
||||||
// Parse request
|
// Parse request
|
||||||
if (valRequest.type() != obj_type)
|
if (valRequest.type() != json_spirit::obj_type)
|
||||||
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
|
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
|
||||||
const Object& request = valRequest.get_obj();
|
const json_spirit::Object& request = valRequest.get_obj();
|
||||||
|
|
||||||
// Parse id now so errors from here on will have the id
|
// Parse id now so errors from here on will have the id
|
||||||
id = find_value(request, "id");
|
id = find_value(request, "id");
|
||||||
|
|
||||||
// Parse method
|
// Parse method
|
||||||
Value valMethod = find_value(request, "method");
|
json_spirit::Value valMethod = find_value(request, "method");
|
||||||
if (valMethod.type() == null_type)
|
if (valMethod.type() == json_spirit::null_type)
|
||||||
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
|
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
|
||||||
if (valMethod.type() != str_type)
|
if (valMethod.type() != json_spirit::str_type)
|
||||||
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
|
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
|
||||||
strMethod = valMethod.get_str();
|
strMethod = valMethod.get_str();
|
||||||
if (strMethod != "getwork" && strMethod != "getblocktemplate")
|
if (strMethod != "getwork" && strMethod != "getblocktemplate")
|
||||||
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
|
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
|
||||||
|
|
||||||
// Parse params
|
// Parse params
|
||||||
Value valParams = find_value(request, "params");
|
json_spirit::Value valParams = find_value(request, "params");
|
||||||
if (valParams.type() == array_type)
|
if (valParams.type() == json_spirit::array_type)
|
||||||
params = valParams.get_array();
|
params = valParams.get_array();
|
||||||
else if (valParams.type() == null_type)
|
else if (valParams.type() == json_spirit::null_type)
|
||||||
params = Array();
|
params = json_spirit::Array();
|
||||||
else
|
else
|
||||||
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
|
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
|
||||||
}
|
}
|
||||||
|
|
||||||
static Object JSONRPCExecOne(const Value& req)
|
static json_spirit::Object JSONRPCExecOne(const json_spirit::Value& req)
|
||||||
{
|
{
|
||||||
Object rpc_result;
|
json_spirit::Object rpc_result;
|
||||||
|
|
||||||
JSONRequest jreq;
|
JSONRequest jreq;
|
||||||
try {
|
try {
|
||||||
jreq.parse(req);
|
jreq.parse(req);
|
||||||
|
|
||||||
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
|
json_spirit::Value result = tableRPC.execute(jreq.strMethod, jreq.params);
|
||||||
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
|
rpc_result = JSONRPCReplyObj(result, json_spirit::Value::null, jreq.id);
|
||||||
}
|
}
|
||||||
catch (Object& objError)
|
catch (json_spirit::Object& objError)
|
||||||
{
|
{
|
||||||
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
|
rpc_result = JSONRPCReplyObj(json_spirit::Value::null, objError, jreq.id);
|
||||||
}
|
}
|
||||||
catch (std::exception& e)
|
catch (std::exception& e)
|
||||||
{
|
{
|
||||||
rpc_result = JSONRPCReplyObj(Value::null,
|
rpc_result = JSONRPCReplyObj(json_spirit::Value::null,
|
||||||
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
|
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
return rpc_result;
|
return rpc_result;
|
||||||
}
|
}
|
||||||
|
|
||||||
static string JSONRPCExecBatch(const Array& vReq)
|
static std::string JSONRPCExecBatch(const json_spirit::Array& vReq)
|
||||||
{
|
{
|
||||||
Array ret;
|
json_spirit::Array ret;
|
||||||
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
|
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
|
||||||
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
|
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
|
||||||
|
|
||||||
return write_string(Value(ret), false) + "\n";
|
return write_string(json_spirit::Value(ret), false) + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
static CCriticalSection cs_THREAD_RPCHANDLER;
|
static CCriticalSection cs_THREAD_RPCHANDLER;
|
||||||
@ -950,8 +951,8 @@ void ThreadRPCServer3(void* parg)
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
map<string, string> mapHeaders;
|
std::map<std::string, std::string> mapHeaders;
|
||||||
string strRequest;
|
std::string strRequest;
|
||||||
|
|
||||||
ReadHTTP(conn->stream(), mapHeaders, strRequest);
|
ReadHTTP(conn->stream(), mapHeaders, strRequest);
|
||||||
|
|
||||||
@ -980,30 +981,30 @@ void ThreadRPCServer3(void* parg)
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Parse request
|
// Parse request
|
||||||
Value valRequest;
|
json_spirit::Value valRequest;
|
||||||
if (!read_string(strRequest, valRequest))
|
if (!read_string(strRequest, valRequest))
|
||||||
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
|
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
|
||||||
|
|
||||||
string strReply;
|
std::string strReply;
|
||||||
|
|
||||||
// singleton request
|
// singleton request
|
||||||
if (valRequest.type() == obj_type) {
|
if (valRequest.type() == json_spirit::obj_type) {
|
||||||
jreq.parse(valRequest);
|
jreq.parse(valRequest);
|
||||||
|
|
||||||
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
|
json_spirit::Value result = tableRPC.execute(jreq.strMethod, jreq.params);
|
||||||
|
|
||||||
// Send reply
|
// Send reply
|
||||||
strReply = JSONRPCReply(result, Value::null, jreq.id);
|
strReply = JSONRPCReply(result, json_spirit::Value::null, jreq.id);
|
||||||
|
|
||||||
// array of requests
|
// array of requests
|
||||||
} else if (valRequest.type() == array_type)
|
} else if (valRequest.type() == json_spirit::array_type)
|
||||||
strReply = JSONRPCExecBatch(valRequest.get_array());
|
strReply = JSONRPCExecBatch(valRequest.get_array());
|
||||||
else
|
else
|
||||||
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
|
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
|
||||||
|
|
||||||
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
|
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
|
||||||
}
|
}
|
||||||
catch (Object& objError)
|
catch (json_spirit::Object& objError)
|
||||||
{
|
{
|
||||||
ErrorReply(conn->stream(), objError, jreq.id);
|
ErrorReply(conn->stream(), objError, jreq.id);
|
||||||
break;
|
break;
|
||||||
@ -1030,15 +1031,15 @@ json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_s
|
|||||||
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
|
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
|
||||||
|
|
||||||
// Observe safe mode
|
// Observe safe mode
|
||||||
string strWarning = GetWarnings("rpc");
|
std::string strWarning = GetWarnings("rpc");
|
||||||
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
|
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
|
||||||
!pcmd->okSafeMode)
|
!pcmd->okSafeMode)
|
||||||
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
|
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Execute
|
// Execute
|
||||||
Value result;
|
json_spirit::Value result;
|
||||||
{
|
{
|
||||||
if (pcmd->unlocked)
|
if (pcmd->unlocked)
|
||||||
result = pcmd->actor(params, false);
|
result = pcmd->actor(params, false);
|
||||||
@ -1056,53 +1057,53 @@ json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_s
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Object CallRPC(const string& strMethod, const Array& params)
|
json_spirit::Object CallRPC(const std::string& strMethod, const json_spirit::Array& params)
|
||||||
{
|
{
|
||||||
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
|
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
|
||||||
throw runtime_error(strprintf(
|
throw std::runtime_error(strprintf(
|
||||||
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
|
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
|
||||||
"If the file does not exist, create it with owner-readable-only file permissions."),
|
"If the file does not exist, create it with owner-readable-only file permissions."),
|
||||||
GetConfigFile().string().c_str()));
|
GetConfigFile().string().c_str()));
|
||||||
|
|
||||||
// Connect to localhost
|
// Connect to localhost
|
||||||
bool fUseSSL = GetBoolArg("-rpcssl");
|
bool fUseSSL = GetBoolArg("-rpcssl");
|
||||||
asio::io_service io_service;
|
boost::asio::io_service io_service;
|
||||||
ssl::context context(ssl::context::sslv23);
|
boost::asio::ssl::context context(boost::asio::ssl::context::sslv23);
|
||||||
context.set_options(ssl::context::no_sslv2);
|
context.set_options(boost::asio::ssl::context::no_sslv2);
|
||||||
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
|
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> sslStream(io_service, context);
|
||||||
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
|
SSLIOStreamDevice<boost::asio::ip::tcp> d(sslStream, fUseSSL);
|
||||||
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
|
boost::iostreams::stream< SSLIOStreamDevice<boost::asio::ip::tcp> > stream(d);
|
||||||
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
|
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
|
||||||
throw runtime_error("couldn't connect to server");
|
throw std::runtime_error("couldn't connect to server");
|
||||||
|
|
||||||
// HTTP basic authentication
|
// HTTP basic authentication
|
||||||
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
|
std::string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
|
||||||
map<string, string> mapRequestHeaders;
|
std::map<std::string, std::string> mapRequestHeaders;
|
||||||
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
|
mapRequestHeaders["Authorization"] = std::string("Basic ") + strUserPass64;
|
||||||
|
|
||||||
// Send request
|
// Send request
|
||||||
string strRequest = JSONRPCRequest(strMethod, params, 1);
|
std::string strRequest = JSONRPCRequest(strMethod, params, 1);
|
||||||
string strPost = HTTPPost(strRequest, mapRequestHeaders);
|
std::string strPost = HTTPPost(strRequest, mapRequestHeaders);
|
||||||
stream << strPost << std::flush;
|
stream << strPost << std::flush;
|
||||||
|
|
||||||
// Receive reply
|
// Receive reply
|
||||||
map<string, string> mapHeaders;
|
std::map<std::string, std::string> mapHeaders;
|
||||||
string strReply;
|
std::string strReply;
|
||||||
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
|
int nStatus = ReadHTTP(stream, mapHeaders, strReply);
|
||||||
if (nStatus == HTTP_UNAUTHORIZED)
|
if (nStatus == HTTP_UNAUTHORIZED)
|
||||||
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
|
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
|
||||||
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
|
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
|
||||||
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
|
throw std::runtime_error(strprintf("server returned HTTP error %d", nStatus));
|
||||||
else if (strReply.empty())
|
else if (strReply.empty())
|
||||||
throw runtime_error("no response from server");
|
throw std::runtime_error("no response from server");
|
||||||
|
|
||||||
// Parse reply
|
// Parse reply
|
||||||
Value valReply;
|
json_spirit::Value valReply;
|
||||||
if (!read_string(strReply, valReply))
|
if (!read_string(strReply, valReply))
|
||||||
throw runtime_error("couldn't parse reply from server");
|
throw std::runtime_error("couldn't parse reply from server");
|
||||||
const Object& reply = valReply.get_obj();
|
const json_spirit::Object& reply = valReply.get_obj();
|
||||||
if (reply.empty())
|
if (reply.empty())
|
||||||
throw runtime_error("expected reply to have result, error and id properties");
|
throw std::runtime_error("expected reply to have result, error and id properties");
|
||||||
|
|
||||||
return reply;
|
return reply;
|
||||||
}
|
}
|
||||||
@ -1111,17 +1112,17 @@ Object CallRPC(const string& strMethod, const Array& params)
|
|||||||
|
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
void ConvertTo(Value& value, bool fAllowNull=false)
|
void ConvertTo(json_spirit::Value& value, bool fAllowNull=false)
|
||||||
{
|
{
|
||||||
if (fAllowNull && value.type() == null_type)
|
if (fAllowNull && value.type() == json_spirit::null_type)
|
||||||
return;
|
return;
|
||||||
if (value.type() == str_type)
|
if (value.type() == json_spirit::str_type)
|
||||||
{
|
{
|
||||||
// reinterpret string as unquoted json value
|
// reinterpret string as unquoted json value
|
||||||
Value value2;
|
json_spirit::Value value2;
|
||||||
string strJSON = value.get_str();
|
std::string strJSON = value.get_str();
|
||||||
if (!read_string(strJSON, value2))
|
if (!read_string(strJSON, value2))
|
||||||
throw runtime_error(string("Error parsing JSON:")+strJSON);
|
throw std::runtime_error(std::string("Error parsing JSON:")+strJSON);
|
||||||
ConvertTo<T>(value2, fAllowNull);
|
ConvertTo<T>(value2, fAllowNull);
|
||||||
value = value2;
|
value = value2;
|
||||||
}
|
}
|
||||||
@ -1132,9 +1133,9 @@ void ConvertTo(Value& value, bool fAllowNull=false)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Convert strings to command-specific RPC representation
|
// Convert strings to command-specific RPC representation
|
||||||
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
|
json_spirit::Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
|
||||||
{
|
{
|
||||||
Array params;
|
json_spirit::Array params;
|
||||||
BOOST_FOREACH(const std::string ¶m, strParams)
|
BOOST_FOREACH(const std::string ¶m, strParams)
|
||||||
params.push_back(param);
|
params.push_back(param);
|
||||||
|
|
||||||
@ -1169,29 +1170,29 @@ Array RPCConvertValues(const std::string &strMethod, const std::vector<std::stri
|
|||||||
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
|
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
|
||||||
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
||||||
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
|
if (strMethod == "walletpassphrase" && n > 2) ConvertTo<bool>(params[2]);
|
||||||
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
|
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<json_spirit::Object>(params[0]);
|
||||||
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
||||||
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
|
if (strMethod == "sendmany" && n > 1) ConvertTo<json_spirit::Object>(params[1]);
|
||||||
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
|
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
|
||||||
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
|
if (strMethod == "reservebalance" && n > 0) ConvertTo<bool>(params[0]);
|
||||||
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
|
if (strMethod == "reservebalance" && n > 1) ConvertTo<double>(params[1]);
|
||||||
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
|
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
|
||||||
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
|
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<json_spirit::Array>(params[1]);
|
||||||
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
|
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
|
||||||
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
||||||
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
|
if (strMethod == "listunspent" && n > 2) ConvertTo<json_spirit::Array>(params[2]);
|
||||||
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
|
||||||
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
|
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<json_spirit::Array>(params[0]);
|
||||||
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
|
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<json_spirit::Object>(params[1]);
|
||||||
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
|
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<json_spirit::Array>(params[1], true);
|
||||||
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
|
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<json_spirit::Array>(params[2], true);
|
||||||
|
|
||||||
return params;
|
return params;
|
||||||
}
|
}
|
||||||
|
|
||||||
int CommandLineRPC(int argc, char *argv[])
|
int CommandLineRPC(int argc, char *argv[])
|
||||||
{
|
{
|
||||||
string strPrint;
|
std::string strPrint;
|
||||||
int nRet = 0;
|
int nRet = 0;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@ -1204,21 +1205,21 @@ int CommandLineRPC(int argc, char *argv[])
|
|||||||
|
|
||||||
// Method
|
// Method
|
||||||
if (argc < 2)
|
if (argc < 2)
|
||||||
throw runtime_error("too few parameters");
|
throw std::runtime_error("too few parameters");
|
||||||
string strMethod = argv[1];
|
std::string strMethod = argv[1];
|
||||||
|
|
||||||
// Parameters default to strings
|
// Parameters default to strings
|
||||||
std::vector<std::string> strParams(&argv[2], &argv[argc]);
|
std::vector<std::string> strParams(&argv[2], &argv[argc]);
|
||||||
Array params = RPCConvertValues(strMethod, strParams);
|
json_spirit::Array params = RPCConvertValues(strMethod, strParams);
|
||||||
|
|
||||||
// Execute
|
// Execute
|
||||||
Object reply = CallRPC(strMethod, params);
|
json_spirit::Object reply = CallRPC(strMethod, params);
|
||||||
|
|
||||||
// Parse reply
|
// Parse reply
|
||||||
const Value& result = find_value(reply, "result");
|
const json_spirit::Value& result = find_value(reply, "result");
|
||||||
const Value& error = find_value(reply, "error");
|
const json_spirit::Value& error = find_value(reply, "error");
|
||||||
|
|
||||||
if (error.type() != null_type)
|
if (error.type() != json_spirit::null_type)
|
||||||
{
|
{
|
||||||
// Error
|
// Error
|
||||||
strPrint = "error: " + write_string(error, false);
|
strPrint = "error: " + write_string(error, false);
|
||||||
@ -1228,9 +1229,9 @@ int CommandLineRPC(int argc, char *argv[])
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Result
|
// Result
|
||||||
if (result.type() == null_type)
|
if (result.type() == json_spirit::null_type)
|
||||||
strPrint = "";
|
strPrint = "";
|
||||||
else if (result.type() == str_type)
|
else if (result.type() == json_spirit::str_type)
|
||||||
strPrint = result.get_str();
|
strPrint = result.get_str();
|
||||||
else
|
else
|
||||||
strPrint = write_string(result, true);
|
strPrint = write_string(result, true);
|
||||||
@ -1238,7 +1239,7 @@ int CommandLineRPC(int argc, char *argv[])
|
|||||||
}
|
}
|
||||||
catch (std::exception& e)
|
catch (std::exception& e)
|
||||||
{
|
{
|
||||||
strPrint = string("error: ") + e.what();
|
strPrint = std::string("error: ") + e.what();
|
||||||
nRet = 87;
|
nRet = 87;
|
||||||
}
|
}
|
||||||
catch (...)
|
catch (...)
|
||||||
@ -1270,7 +1271,7 @@ int main(int argc, char *argv[])
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (argc >= 2 && string(argv[1]) == "-server")
|
if (argc >= 2 && std::string(argv[1]) == "-server")
|
||||||
{
|
{
|
||||||
printf("server ready\n");
|
printf("server ready\n");
|
||||||
ThreadRPCServer(NULL);
|
ThreadRPCServer(NULL);
|
||||||
|
@ -4,11 +4,13 @@
|
|||||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||||
|
|
||||||
#ifndef _curecoinRPC_H_
|
#ifndef _curecoinRPC_H_
|
||||||
#define _curecoinRPC_H_ 1
|
#define _curecoinRPC_H_
|
||||||
|
|
||||||
#if BOOST_VERSION >= 106600
|
#if BOOST_VERSION >= 106600
|
||||||
|
#ifndef BOOST_ASIO_ENABLE_OLD_SERVICES
|
||||||
#define BOOST_ASIO_ENABLE_OLD_SERVICES
|
#define BOOST_ASIO_ENABLE_OLD_SERVICES
|
||||||
#endif
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <list>
|
#include <list>
|
||||||
|
103
src/db.cpp
103
src/db.cpp
@ -13,14 +13,17 @@
|
|||||||
#include <boost/filesystem.hpp>
|
#include <boost/filesystem.hpp>
|
||||||
#include <boost/filesystem/fstream.hpp>
|
#include <boost/filesystem/fstream.hpp>
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
#include <sstream>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
#include "sys/stat.h"
|
#include "sys/stat.h"
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
using namespace boost;
|
|
||||||
|
|
||||||
|
|
||||||
unsigned int nWalletDBUpdated;
|
unsigned int nWalletDBUpdated;
|
||||||
|
|
||||||
|
|
||||||
@ -112,10 +115,10 @@ bool CDBEnv::Open(boost::filesystem::path pathEnv_)
|
|||||||
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");
|
||||||
|
|
||||||
if (fShutdown)
|
if (fShutdown)
|
||||||
throw runtime_error("CDBEnv::MakeMock(): during shutdown");
|
throw std::runtime_error("CDBEnv::MakeMock(): during shutdown");
|
||||||
|
|
||||||
printf("CDBEnv::MakeMock()\n");
|
printf("CDBEnv::MakeMock()\n");
|
||||||
|
|
||||||
@ -136,7 +139,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;
|
||||||
@ -168,7 +171,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
|
|||||||
u_int32_t flags = DB_SALVAGE;
|
u_int32_t flags = DB_SALVAGE;
|
||||||
if (fAggressive) flags |= DB_AGGRESSIVE;
|
if (fAggressive) 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);
|
||||||
@ -186,7 +189,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
|
|||||||
// ... 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
|
||||||
|
|
||||||
@ -197,7 +200,7 @@ bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
|
|||||||
if (keyHex != "DATA_END")
|
if (keyHex != "DATA_END")
|
||||||
{
|
{
|
||||||
getline(strDump, valueHex);
|
getline(strDump, valueHex);
|
||||||
vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
|
vResult.push_back(std::make_pair(ParseHex(keyHex),ParseHex(valueHex)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -230,7 +233,7 @@ CDB::CDB(const char *pszFile, const char* pszMode) :
|
|||||||
{
|
{
|
||||||
LOCK(bitdb.cs_db);
|
LOCK(bitdb.cs_db);
|
||||||
if (!bitdb.Open(GetDataDir()))
|
if (!bitdb.Open(GetDataDir()))
|
||||||
throw runtime_error("env open failed");
|
throw std::runtime_error("env open failed");
|
||||||
|
|
||||||
strFile = pszFile;
|
strFile = pszFile;
|
||||||
++bitdb.mapFileUseCount[strFile];
|
++bitdb.mapFileUseCount[strFile];
|
||||||
@ -245,7 +248,7 @@ CDB::CDB(const char *pszFile, const char* pszMode) :
|
|||||||
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", pszFile));
|
throw std::runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
|
||||||
}
|
}
|
||||||
|
|
||||||
ret = pdb->open(NULL, // Txn pointer
|
ret = pdb->open(NULL, // Txn pointer
|
||||||
@ -261,10 +264,10 @@ CDB::CDB(const char *pszFile, const char* pszMode) :
|
|||||||
pdb = NULL;
|
pdb = NULL;
|
||||||
--bitdb.mapFileUseCount[strFile];
|
--bitdb.mapFileUseCount[strFile];
|
||||||
strFile = "";
|
strFile = "";
|
||||||
throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
|
throw std::runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fCreate && !Exists(string("version")))
|
if (fCreate && !Exists(std::string("version")))
|
||||||
{
|
{
|
||||||
bool fTmp = fReadOnly;
|
bool fTmp = fReadOnly;
|
||||||
fReadOnly = false;
|
fReadOnly = false;
|
||||||
@ -311,7 +314,7 @@ void CDB::Close()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void CDBEnv::CloseDb(const string& strFile)
|
void CDBEnv::CloseDb(const std::string& strFile)
|
||||||
{
|
{
|
||||||
{
|
{
|
||||||
LOCK(cs_db);
|
LOCK(cs_db);
|
||||||
@ -326,7 +329,7 @@ void CDBEnv::CloseDb(const string& strFile)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CDBEnv::RemoveDb(const string& strFile)
|
bool CDBEnv::RemoveDb(const std::string& strFile)
|
||||||
{
|
{
|
||||||
this->CloseDb(strFile);
|
this->CloseDb(strFile);
|
||||||
|
|
||||||
@ -335,7 +338,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 (!fShutdown)
|
while (!fShutdown)
|
||||||
{
|
{
|
||||||
@ -350,7 +353,7 @@ bool CDB::Rewrite(const string& strFile, const char* pszSkip)
|
|||||||
|
|
||||||
bool fSuccess = true;
|
bool fSuccess = true;
|
||||||
printf("Rewriting %s...\n", strFile.c_str());
|
printf("Rewriting %s...\n", strFile.c_str());
|
||||||
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);
|
||||||
@ -439,10 +442,10 @@ 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;
|
||||||
printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
|
printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
|
||||||
if (nRefCount == 0)
|
if (nRefCount == 0)
|
||||||
@ -462,7 +465,7 @@ void CDBEnv::Flush(bool fShutdown)
|
|||||||
else
|
else
|
||||||
mi++;
|
mi++;
|
||||||
}
|
}
|
||||||
printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
|
printf("DBFlush(%s)%s ended %15" PRI64d "ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
|
||||||
if (fShutdown)
|
if (fShutdown)
|
||||||
{
|
{
|
||||||
char** listp;
|
char** listp;
|
||||||
@ -488,13 +491,13 @@ bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
|
|||||||
{
|
{
|
||||||
assert(!fClient);
|
assert(!fClient);
|
||||||
txindex.SetNull();
|
txindex.SetNull();
|
||||||
return Read(make_pair(string("tx"), hash), txindex);
|
return Read(std::make_pair(std::string("tx"), hash), txindex);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
|
bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
|
||||||
{
|
{
|
||||||
assert(!fClient);
|
assert(!fClient);
|
||||||
return Write(make_pair(string("tx"), hash), txindex);
|
return Write(std::make_pair(std::string("tx"), hash), txindex);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
|
bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
|
||||||
@ -504,7 +507,7 @@ bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeigh
|
|||||||
// Add to tx index
|
// Add to tx index
|
||||||
uint256 hash = tx.GetHash();
|
uint256 hash = tx.GetHash();
|
||||||
CTxIndex txindex(pos, tx.vout.size());
|
CTxIndex txindex(pos, tx.vout.size());
|
||||||
return Write(make_pair(string("tx"), hash), txindex);
|
return Write(std::make_pair(std::string("tx"), hash), txindex);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::EraseTxIndex(const CTransaction& tx)
|
bool CTxDB::EraseTxIndex(const CTransaction& tx)
|
||||||
@ -512,13 +515,13 @@ bool CTxDB::EraseTxIndex(const CTransaction& tx)
|
|||||||
assert(!fClient);
|
assert(!fClient);
|
||||||
uint256 hash = tx.GetHash();
|
uint256 hash = tx.GetHash();
|
||||||
|
|
||||||
return Erase(make_pair(string("tx"), hash));
|
return Erase(std::make_pair(std::string("tx"), hash));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::ContainsTx(uint256 hash)
|
bool CTxDB::ContainsTx(uint256 hash)
|
||||||
{
|
{
|
||||||
assert(!fClient);
|
assert(!fClient);
|
||||||
return Exists(make_pair(string("tx"), hash));
|
return Exists(std::make_pair(std::string("tx"), hash));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
|
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
|
||||||
@ -549,47 +552,47 @@ bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
|
|||||||
|
|
||||||
bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
|
bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
|
||||||
{
|
{
|
||||||
return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
|
return Write(std::make_pair(std::string("blockindex"), blockindex.GetBlockHash()), blockindex);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
|
bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
|
||||||
{
|
{
|
||||||
return Read(string("hashBestChain"), hashBestChain);
|
return Read(std::string("hashBestChain"), hashBestChain);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
|
bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
|
||||||
{
|
{
|
||||||
return Write(string("hashBestChain"), hashBestChain);
|
return Write(std::string("hashBestChain"), hashBestChain);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
|
bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
|
||||||
{
|
{
|
||||||
return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
|
return Read(std::string("bnBestInvalidTrust"), bnBestInvalidTrust);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
|
bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
|
||||||
{
|
{
|
||||||
return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
|
return Write(std::string("bnBestInvalidTrust"), bnBestInvalidTrust);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
|
bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
|
||||||
{
|
{
|
||||||
return Read(string("hashSyncCheckpoint"), hashCheckpoint);
|
return Read(std::string("hashSyncCheckpoint"), hashCheckpoint);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
|
bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
|
||||||
{
|
{
|
||||||
return Write(string("hashSyncCheckpoint"), hashCheckpoint);
|
return Write(std::string("hashSyncCheckpoint"), hashCheckpoint);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
|
bool CTxDB::ReadCheckpointPubKey(std::string& strPubKey)
|
||||||
{
|
{
|
||||||
return Read(string("strCheckpointPubKey"), strPubKey);
|
return Read(std::string("strCheckpointPubKey"), strPubKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
|
bool CTxDB::WriteCheckpointPubKey(const std::string& strPubKey)
|
||||||
{
|
{
|
||||||
return Write(string("strCheckpointPubKey"), strPubKey);
|
return Write(std::string("strCheckpointPubKey"), strPubKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
CBlockIndex static * InsertBlockIndex(uint256 hash)
|
CBlockIndex static * InsertBlockIndex(uint256 hash)
|
||||||
@ -598,15 +601,15 @@ CBlockIndex static * InsertBlockIndex(uint256 hash)
|
|||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
// Return existing
|
// Return existing
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
|
||||||
if (mi != mapBlockIndex.end())
|
if (mi != mapBlockIndex.end())
|
||||||
return (*mi).second;
|
return (*mi).second;
|
||||||
|
|
||||||
// Create new
|
// Create new
|
||||||
CBlockIndex* pindexNew = new CBlockIndex();
|
CBlockIndex* pindexNew = new CBlockIndex();
|
||||||
if (!pindexNew)
|
if (!pindexNew)
|
||||||
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
|
throw std::runtime_error("LoadBlockIndex() : new CBlockIndex failed");
|
||||||
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
|
mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
|
||||||
pindexNew->phashBlock = &((*mi).first);
|
pindexNew->phashBlock = &((*mi).first);
|
||||||
|
|
||||||
return pindexNew;
|
return pindexNew;
|
||||||
@ -621,12 +624,12 @@ bool CTxDB::LoadBlockIndex()
|
|||||||
return true;
|
return true;
|
||||||
|
|
||||||
// Calculate bnChainTrust
|
// Calculate bnChainTrust
|
||||||
vector<pair<int, CBlockIndex*> > vSortedByHeight;
|
std::vector<std::pair<int, CBlockIndex*> > vSortedByHeight;
|
||||||
vSortedByHeight.reserve(mapBlockIndex.size());
|
vSortedByHeight.reserve(mapBlockIndex.size());
|
||||||
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
|
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
|
||||||
{
|
{
|
||||||
CBlockIndex* pindex = item.second;
|
CBlockIndex* pindex = item.second;
|
||||||
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
|
vSortedByHeight.push_back(std::make_pair(pindex->nHeight, pindex));
|
||||||
}
|
}
|
||||||
sort(vSortedByHeight.begin(), vSortedByHeight.end());
|
sort(vSortedByHeight.begin(), vSortedByHeight.end());
|
||||||
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
|
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
|
||||||
@ -636,7 +639,7 @@ bool CTxDB::LoadBlockIndex()
|
|||||||
// ppcoin: calculate stake modifier checksum
|
// ppcoin: calculate stake modifier checksum
|
||||||
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
|
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
|
||||||
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
|
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
|
||||||
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindex->nHeight, pindex->nStakeModifier);
|
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRI64x, pindex->nHeight, pindex->nStakeModifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load hashBestChain pointer to end of best chain
|
// Load hashBestChain pointer to end of best chain
|
||||||
@ -672,7 +675,7 @@ bool CTxDB::LoadBlockIndex()
|
|||||||
nCheckDepth = nBestHeight;
|
nCheckDepth = nBestHeight;
|
||||||
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
|
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
|
||||||
CBlockIndex* pindexFork = NULL;
|
CBlockIndex* pindexFork = NULL;
|
||||||
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
|
std::map<std::pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
|
||||||
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
|
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
|
||||||
{
|
{
|
||||||
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
|
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
|
||||||
@ -689,7 +692,7 @@ bool CTxDB::LoadBlockIndex()
|
|||||||
// check level 2: verify transaction index validity
|
// check level 2: verify transaction index validity
|
||||||
if (nCheckLevel>1)
|
if (nCheckLevel>1)
|
||||||
{
|
{
|
||||||
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
|
std::pair<unsigned int, unsigned int> pos = std::make_pair(pindex->nFile, pindex->nBlockPos);
|
||||||
mapBlockPos[pos] = pindex;
|
mapBlockPos[pos] = pindex;
|
||||||
BOOST_FOREACH(const CTransaction &tx, block.vtx)
|
BOOST_FOREACH(const CTransaction &tx, block.vtx)
|
||||||
{
|
{
|
||||||
@ -722,7 +725,7 @@ bool CTxDB::LoadBlockIndex()
|
|||||||
{
|
{
|
||||||
if (!txpos.IsNull())
|
if (!txpos.IsNull())
|
||||||
{
|
{
|
||||||
pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
|
std::pair<unsigned int, unsigned int> posFind = std::make_pair(txpos.nFile, txpos.nBlockPos);
|
||||||
if (!mapBlockPos.count(posFind))
|
if (!mapBlockPos.count(posFind))
|
||||||
{
|
{
|
||||||
printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
|
printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
|
||||||
@ -807,7 +810,7 @@ bool CTxDB::LoadBlockIndexGuts()
|
|||||||
// Read next record
|
// Read next record
|
||||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||||
if (fFlags == DB_SET_RANGE)
|
if (fFlags == DB_SET_RANGE)
|
||||||
ssKey << make_pair(string("blockindex"), uint256(0));
|
ssKey << std::make_pair(std::string("blockindex"), uint256(0));
|
||||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||||
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
|
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
|
||||||
fFlags = DB_NEXT;
|
fFlags = DB_NEXT;
|
||||||
@ -819,7 +822,7 @@ bool CTxDB::LoadBlockIndexGuts()
|
|||||||
// Unserialize
|
// Unserialize
|
||||||
|
|
||||||
try {
|
try {
|
||||||
string strType;
|
std::string strType;
|
||||||
ssKey >> strType;
|
ssKey >> strType;
|
||||||
if (strType == "blockindex" && !fRequestShutdown)
|
if (strType == "blockindex" && !fRequestShutdown)
|
||||||
{
|
{
|
||||||
@ -855,7 +858,7 @@ bool CTxDB::LoadBlockIndexGuts()
|
|||||||
|
|
||||||
// ppcoin: build setStakeSeen
|
// ppcoin: build setStakeSeen
|
||||||
if (pindexNew->IsProofOfStake())
|
if (pindexNew->IsProofOfStake())
|
||||||
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
|
setStakeSeen.insert(std::make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@ -934,7 +937,7 @@ bool CAddrDB::Read(CAddrMan& addr)
|
|||||||
// use file size to size memory buffer
|
// use file size to size memory buffer
|
||||||
int fileSize = GetFilesize(filein);
|
int fileSize = GetFilesize(filein);
|
||||||
int dataSize = fileSize - sizeof(uint256);
|
int dataSize = fileSize - sizeof(uint256);
|
||||||
vector<unsigned char> vchData;
|
std::vector<unsigned char> vchData;
|
||||||
vchData.resize(dataSize);
|
vchData.resize(dataSize);
|
||||||
uint256 hashIn;
|
uint256 hashIn;
|
||||||
|
|
||||||
|
24
src/db.h
24
src/db.h
@ -7,6 +7,8 @@
|
|||||||
|
|
||||||
#include "main.h"
|
#include "main.h"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@ -127,7 +129,7 @@ protected:
|
|||||||
Dbt datValue;
|
Dbt datValue;
|
||||||
datValue.set_flags(DB_DBT_MALLOC);
|
datValue.set_flags(DB_DBT_MALLOC);
|
||||||
int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
|
int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
|
||||||
memset(datKey.get_data(), 0, datKey.get_size());
|
std::memset(datKey.get_data(), 0, datKey.get_size());
|
||||||
if (datValue.get_data() == NULL)
|
if (datValue.get_data() == NULL)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -141,8 +143,8 @@ protected:
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Clear and free memory
|
// Clear and free memory
|
||||||
memset(datValue.get_data(), 0, datValue.get_size());
|
std::memset(datValue.get_data(), 0, datValue.get_size());
|
||||||
free(datValue.get_data());
|
std::free(datValue.get_data());
|
||||||
return (ret == 0);
|
return (ret == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -170,8 +172,8 @@ protected:
|
|||||||
int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));
|
int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));
|
||||||
|
|
||||||
// Clear memory in case it was a private key
|
// Clear memory in case it was a private key
|
||||||
memset(datKey.get_data(), 0, datKey.get_size());
|
std::memset(datKey.get_data(), 0, datKey.get_size());
|
||||||
memset(datValue.get_data(), 0, datValue.get_size());
|
std::memset(datValue.get_data(), 0, datValue.get_size());
|
||||||
return (ret == 0);
|
return (ret == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -193,7 +195,7 @@ protected:
|
|||||||
int ret = pdb->del(activeTxn, &datKey, 0);
|
int ret = pdb->del(activeTxn, &datKey, 0);
|
||||||
|
|
||||||
// Clear memory
|
// Clear memory
|
||||||
memset(datKey.get_data(), 0, datKey.get_size());
|
std::memset(datKey.get_data(), 0, datKey.get_size());
|
||||||
return (ret == 0 || ret == DB_NOTFOUND);
|
return (ret == 0 || ret == DB_NOTFOUND);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -213,7 +215,7 @@ protected:
|
|||||||
int ret = pdb->exists(activeTxn, &datKey, 0);
|
int ret = pdb->exists(activeTxn, &datKey, 0);
|
||||||
|
|
||||||
// Clear memory
|
// Clear memory
|
||||||
memset(datKey.get_data(), 0, datKey.get_size());
|
std::memset(datKey.get_data(), 0, datKey.get_size());
|
||||||
return (ret == 0);
|
return (ret == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -260,10 +262,10 @@ protected:
|
|||||||
ssValue.write((char*)datValue.get_data(), datValue.get_size());
|
ssValue.write((char*)datValue.get_data(), datValue.get_size());
|
||||||
|
|
||||||
// Clear and free memory
|
// Clear and free memory
|
||||||
memset(datKey.get_data(), 0, datKey.get_size());
|
std::memset(datKey.get_data(), 0, datKey.get_size());
|
||||||
memset(datValue.get_data(), 0, datValue.get_size());
|
std::memset(datValue.get_data(), 0, datValue.get_size());
|
||||||
free(datKey.get_data());
|
std::free(datKey.get_data());
|
||||||
free(datValue.get_data());
|
std::free(datValue.get_data());
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
42
src/init.cpp
42
src/init.cpp
@ -17,13 +17,13 @@
|
|||||||
#include <boost/algorithm/string/predicate.hpp>
|
#include <boost/algorithm/string/predicate.hpp>
|
||||||
#include <openssl/crypto.h>
|
#include <openssl/crypto.h>
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
#include <signal.h>
|
#include <signal.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
using namespace boost;
|
|
||||||
|
|
||||||
CWallet* pwalletMain;
|
CWallet* pwalletMain;
|
||||||
CClientUIInterface uiInterface;
|
CClientUIInterface uiInterface;
|
||||||
|
|
||||||
@ -217,7 +217,7 @@ bool static Bind(const CService &addr, bool fError = true) {
|
|||||||
// Core-specific options shared between UI and daemon
|
// Core-specific options shared between UI and daemon
|
||||||
std::string HelpMessage()
|
std::string HelpMessage()
|
||||||
{
|
{
|
||||||
string strUsage = _("Options:") + "\n" +
|
std::string strUsage = _("Options:") + "\n" +
|
||||||
" -? " + _("This help message") + "\n" +
|
" -? " + _("This help message") + "\n" +
|
||||||
" -conf=<file> " + _("Specify configuration file (default: curecoin.conf)") + "\n" +
|
" -conf=<file> " + _("Specify configuration file (default: curecoin.conf)") + "\n" +
|
||||||
" -pid=<file> " + _("Specify pid file (default: curecoind.pid)") + "\n" +
|
" -pid=<file> " + _("Specify pid file (default: curecoind.pid)") + "\n" +
|
||||||
@ -510,7 +510,7 @@ bool AppInit2()
|
|||||||
|
|
||||||
if (!bitdb.Open(GetDataDir()))
|
if (!bitdb.Open(GetDataDir()))
|
||||||
{
|
{
|
||||||
string msg = strprintf(_("Error initializing database environment %s!"
|
std::string msg = strprintf(_("Error initializing database environment %s!"
|
||||||
" To recover, BACKUP THAT DIRECTORY, then remove"
|
" To recover, BACKUP THAT DIRECTORY, then remove"
|
||||||
" everything from it except for wallet.dat."), strDataDir.c_str());
|
" everything from it except for wallet.dat."), strDataDir.c_str());
|
||||||
return InitError(msg);
|
return InitError(msg);
|
||||||
@ -528,7 +528,7 @@ bool AppInit2()
|
|||||||
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
|
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
|
||||||
if (r == CDBEnv::RECOVER_OK)
|
if (r == CDBEnv::RECOVER_OK)
|
||||||
{
|
{
|
||||||
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
|
std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
|
||||||
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
|
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
|
||||||
" your balance or transactions are incorrect you should"
|
" your balance or transactions are incorrect you should"
|
||||||
" restore from a backup."), strDataDir.c_str());
|
" restore from a backup."), strDataDir.c_str());
|
||||||
@ -633,7 +633,7 @@ bool AppInit2()
|
|||||||
|
|
||||||
if (mapArgs.count("-externalip"))
|
if (mapArgs.count("-externalip"))
|
||||||
{
|
{
|
||||||
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
|
BOOST_FOREACH(std::string strAddr, mapMultiArgs["-externalip"]) {
|
||||||
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
|
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
|
||||||
if (!addrLocal.IsValid())
|
if (!addrLocal.IsValid())
|
||||||
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
|
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
|
||||||
@ -657,7 +657,7 @@ bool AppInit2()
|
|||||||
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
|
InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n"));
|
||||||
}
|
}
|
||||||
|
|
||||||
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
|
BOOST_FOREACH(std::string strDest, mapMultiArgs["-seednode"])
|
||||||
AddOneShot(strDest);
|
AddOneShot(strDest);
|
||||||
|
|
||||||
// TODO: replace this by DNSseed
|
// TODO: replace this by DNSseed
|
||||||
@ -667,7 +667,7 @@ bool AppInit2()
|
|||||||
|
|
||||||
if (!bitdb.Open(GetDataDir()))
|
if (!bitdb.Open(GetDataDir()))
|
||||||
{
|
{
|
||||||
string msg = strprintf(_("Error initializing database environment %s!"
|
std::string msg = strprintf(_("Error initializing database environment %s!"
|
||||||
" To recover, BACKUP THAT DIRECTORY, then remove"
|
" To recover, BACKUP THAT DIRECTORY, then remove"
|
||||||
" everything from it except for wallet.dat."), strDataDir.c_str());
|
" everything from it except for wallet.dat."), strDataDir.c_str());
|
||||||
return InitError(msg);
|
return InitError(msg);
|
||||||
@ -695,7 +695,7 @@ bool AppInit2()
|
|||||||
printf("Shutdown requested. Exiting.\n");
|
printf("Shutdown requested. Exiting.\n");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
|
printf(" block index %15" PRI64d "ms\n", GetTimeMillis() - nStart);
|
||||||
|
|
||||||
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
|
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
|
||||||
{
|
{
|
||||||
@ -705,9 +705,9 @@ bool AppInit2()
|
|||||||
|
|
||||||
if (mapArgs.count("-printblock"))
|
if (mapArgs.count("-printblock"))
|
||||||
{
|
{
|
||||||
string strMatch = mapArgs["-printblock"];
|
std::string strMatch = mapArgs["-printblock"];
|
||||||
int nFound = 0;
|
int nFound = 0;
|
||||||
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
|
for (std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
|
||||||
{
|
{
|
||||||
uint256 hash = (*mi).first;
|
uint256 hash = (*mi).first;
|
||||||
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
|
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
|
||||||
@ -751,7 +751,7 @@ bool AppInit2()
|
|||||||
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
|
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
|
||||||
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
|
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
|
||||||
{
|
{
|
||||||
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
|
std::string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
|
||||||
" or address book entries might be missing or incorrect."));
|
" or address book entries might be missing or incorrect."));
|
||||||
uiInterface.ThreadSafeMessageBox(msg, _("Curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
|
uiInterface.ThreadSafeMessageBox(msg, _("Curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
|
||||||
}
|
}
|
||||||
@ -797,7 +797,7 @@ bool AppInit2()
|
|||||||
}
|
}
|
||||||
|
|
||||||
printf("%s", strErrors.str().c_str());
|
printf("%s", strErrors.str().c_str());
|
||||||
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
|
printf(" wallet %15" PRI64d "ms\n", GetTimeMillis() - nStart);
|
||||||
|
|
||||||
RegisterWallet(pwalletMain);
|
RegisterWallet(pwalletMain);
|
||||||
|
|
||||||
@ -817,7 +817,7 @@ bool AppInit2()
|
|||||||
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
|
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
|
||||||
nStart = GetTimeMillis();
|
nStart = GetTimeMillis();
|
||||||
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
|
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
|
||||||
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
|
printf(" rescan %15" PRI64d "ms\n", GetTimeMillis() - nStart);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ********************************************************* Step 9: import blocks
|
// ********************************************************* Step 9: import blocks
|
||||||
@ -826,7 +826,7 @@ bool AppInit2()
|
|||||||
{
|
{
|
||||||
uiInterface.InitMessage(_("<font style='color: black'>Importing blockchain data file.</font>"));
|
uiInterface.InitMessage(_("<font style='color: black'>Importing blockchain data file.</font>"));
|
||||||
|
|
||||||
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
|
BOOST_FOREACH(std::string strFile, mapMultiArgs["-loadblock"])
|
||||||
{
|
{
|
||||||
FILE *file = fopen(strFile.c_str(), "rb");
|
FILE *file = fopen(strFile.c_str(), "rb");
|
||||||
if (file)
|
if (file)
|
||||||
@ -858,7 +858,7 @@ bool AppInit2()
|
|||||||
printf("Invalid or missing peers.dat; recreating\n");
|
printf("Invalid or missing peers.dat; recreating\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
|
printf("Loaded %i addresses from peers.dat %" PRI64d "ms\n",
|
||||||
addrman.size(), GetTimeMillis() - nStart);
|
addrman.size(), GetTimeMillis() - nStart);
|
||||||
|
|
||||||
// ********************************************************* Step 11: start node
|
// ********************************************************* Step 11: start node
|
||||||
@ -869,11 +869,11 @@ bool AppInit2()
|
|||||||
RandAddSeedPerfmon();
|
RandAddSeedPerfmon();
|
||||||
|
|
||||||
//// debug print
|
//// debug print
|
||||||
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
|
printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
|
||||||
printf("nBestHeight = %d\n", nBestHeight);
|
printf("nBestHeight = %d\n", nBestHeight);
|
||||||
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size());
|
printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain->setKeyPool.size());
|
||||||
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size());
|
printf("mapWallet.size() = %" PRIszu "\n", pwalletMain->mapWallet.size());
|
||||||
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size());
|
printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain->mapAddressBook.size());
|
||||||
|
|
||||||
if (!NewThread(StartNode, NULL))
|
if (!NewThread(StartNode, NULL))
|
||||||
InitError(_("Error: could not start node"));
|
InitError(_("Error: could not start node"));
|
||||||
|
54
src/irc.cpp
54
src/irc.cpp
@ -8,8 +8,8 @@
|
|||||||
#include "strlcpy.h"
|
#include "strlcpy.h"
|
||||||
#include "base58.h"
|
#include "base58.h"
|
||||||
|
|
||||||
using namespace std;
|
#include <string>
|
||||||
using namespace boost;
|
#include <vector>
|
||||||
|
|
||||||
int nGotIRCAddresses = 0;
|
int nGotIRCAddresses = 0;
|
||||||
|
|
||||||
@ -26,22 +26,22 @@ struct ircaddr
|
|||||||
};
|
};
|
||||||
#pragma pack(pop)
|
#pragma pack(pop)
|
||||||
|
|
||||||
string EncodeAddress(const CService& addr)
|
std::string EncodeAddress(const CService& addr)
|
||||||
{
|
{
|
||||||
struct ircaddr tmp;
|
struct ircaddr tmp;
|
||||||
if (addr.GetInAddr(&tmp.ip))
|
if (addr.GetInAddr(&tmp.ip))
|
||||||
{
|
{
|
||||||
tmp.port = htons(addr.GetPort());
|
tmp.port = htons(addr.GetPort());
|
||||||
|
|
||||||
vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
|
std::vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
|
||||||
return string("u") + EncodeBase58Check(vch);
|
return std::string("u") + EncodeBase58Check(vch);
|
||||||
}
|
}
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
bool DecodeAddress(string str, CService& addr)
|
bool DecodeAddress(std::string str, CService& addr)
|
||||||
{
|
{
|
||||||
vector<unsigned char> vch;
|
std::vector<unsigned char> vch;
|
||||||
if (!DecodeBase58Check(str.substr(1), vch))
|
if (!DecodeBase58Check(str.substr(1), vch))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -75,7 +75,7 @@ static bool Send(SOCKET hSocket, const char* pszSend)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool RecvLineIRC(SOCKET hSocket, string& strLine)
|
bool RecvLineIRC(SOCKET hSocket, std::string& strLine)
|
||||||
{
|
{
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
@ -84,7 +84,7 @@ bool RecvLineIRC(SOCKET hSocket, string& strLine)
|
|||||||
{
|
{
|
||||||
if (fShutdown)
|
if (fShutdown)
|
||||||
return false;
|
return false;
|
||||||
vector<string> vWords;
|
std::vector<std::string> vWords;
|
||||||
ParseString(strLine, ' ', vWords);
|
ParseString(strLine, ' ', vWords);
|
||||||
if (vWords.size() >= 1 && vWords[0] == "PING")
|
if (vWords.size() >= 1 && vWords[0] == "PING")
|
||||||
{
|
{
|
||||||
@ -102,18 +102,18 @@ int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const cha
|
|||||||
{
|
{
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
string strLine;
|
std::string strLine;
|
||||||
strLine.reserve(10000);
|
strLine.reserve(10000);
|
||||||
if (!RecvLineIRC(hSocket, strLine))
|
if (!RecvLineIRC(hSocket, strLine))
|
||||||
return 0;
|
return 0;
|
||||||
printf("IRC %s\n", strLine.c_str());
|
printf("IRC %s\n", strLine.c_str());
|
||||||
if (psz1 && strLine.find(psz1) != string::npos)
|
if (psz1 && strLine.find(psz1) != std::string::npos)
|
||||||
return 1;
|
return 1;
|
||||||
if (psz2 && strLine.find(psz2) != string::npos)
|
if (psz2 && strLine.find(psz2) != std::string::npos)
|
||||||
return 2;
|
return 2;
|
||||||
if (psz3 && strLine.find(psz3) != string::npos)
|
if (psz3 && strLine.find(psz3) != std::string::npos)
|
||||||
return 3;
|
return 3;
|
||||||
if (psz4 && strLine.find(psz4) != string::npos)
|
if (psz4 && strLine.find(psz4) != std::string::npos)
|
||||||
return 4;
|
return 4;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,16 +132,16 @@ bool Wait(int nSeconds)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
|
bool RecvCodeLine(SOCKET hSocket, const char* psz1, std::string& strRet)
|
||||||
{
|
{
|
||||||
strRet.clear();
|
strRet.clear();
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
string strLine;
|
std::string strLine;
|
||||||
if (!RecvLineIRC(hSocket, strLine))
|
if (!RecvLineIRC(hSocket, strLine))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
vector<string> vWords;
|
std::vector<std::string> vWords;
|
||||||
ParseString(strLine, ' ', vWords);
|
ParseString(strLine, ' ', vWords);
|
||||||
if (vWords.size() < 2)
|
if (vWords.size() < 2)
|
||||||
continue;
|
continue;
|
||||||
@ -155,23 +155,23 @@ bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
|
bool GetIPFromIRC(SOCKET hSocket, std::string strMyName, CNetAddr& ipRet)
|
||||||
{
|
{
|
||||||
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
|
Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
|
||||||
|
|
||||||
string strLine;
|
std::string strLine;
|
||||||
if (!RecvCodeLine(hSocket, "302", strLine))
|
if (!RecvCodeLine(hSocket, "302", strLine))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
vector<string> vWords;
|
std::vector<std::string> vWords;
|
||||||
ParseString(strLine, ' ', vWords);
|
ParseString(strLine, ' ', vWords);
|
||||||
if (vWords.size() < 4)
|
if (vWords.size() < 4)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
string str = vWords[3];
|
std::string str = vWords[3];
|
||||||
if (str.rfind("@") == string::npos)
|
if (str.rfind("@") == std::string::npos)
|
||||||
return false;
|
return false;
|
||||||
string strHost = str.substr(str.rfind("@")+1);
|
std::string strHost = str.substr(str.rfind("@")+1);
|
||||||
|
|
||||||
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
|
// Hybrid IRC used by lfnet always returns IP when you userhost yourself,
|
||||||
// but in case another IRC is ever used this should work.
|
// but in case another IRC is ever used this should work.
|
||||||
@ -258,13 +258,13 @@ void ThreadIRCSeed2(void* parg)
|
|||||||
|
|
||||||
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
|
CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses
|
||||||
CService addrLocal;
|
CService addrLocal;
|
||||||
string strMyName;
|
std::string strMyName;
|
||||||
// Don't use our IP as our nick if we're not listening
|
// Don't use our IP as our nick if we're not listening
|
||||||
// or if it keeps failing because the nick is already in use.
|
// or if it keeps failing because the nick is already in use.
|
||||||
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
|
if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3)
|
||||||
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
|
strMyName = EncodeAddress(GetLocalAddress(&addrConnect));
|
||||||
if (strMyName == "")
|
if (strMyName == "")
|
||||||
strMyName = strprintf("x%"PRI64u"", GetRand(1000000000));
|
strMyName = strprintf("x%" PRI64u "", GetRand(1000000000));
|
||||||
|
|
||||||
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
|
Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
|
||||||
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
|
Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
|
||||||
@ -319,14 +319,14 @@ void ThreadIRCSeed2(void* parg)
|
|||||||
}
|
}
|
||||||
|
|
||||||
int64 nStart = GetTime();
|
int64 nStart = GetTime();
|
||||||
string strLine;
|
std::string strLine;
|
||||||
strLine.reserve(10000);
|
strLine.reserve(10000);
|
||||||
while (!fShutdown && RecvLineIRC(hSocket, strLine))
|
while (!fShutdown && RecvLineIRC(hSocket, strLine))
|
||||||
{
|
{
|
||||||
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
|
if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
vector<string> vWords;
|
std::vector<std::string> vWords;
|
||||||
ParseString(strLine, ' ', vWords);
|
ParseString(strLine, ' ', vWords);
|
||||||
if (vWords.size() < 2)
|
if (vWords.size() < 2)
|
||||||
continue;
|
continue;
|
||||||
|
@ -28,8 +28,6 @@ namespace json_spirit
|
|||||||
template< class String_type >
|
template< class String_type >
|
||||||
String_type non_printable_to_string( unsigned int c )
|
String_type non_printable_to_string( unsigned int c )
|
||||||
{
|
{
|
||||||
typedef typename String_type::value_type Char_type;
|
|
||||||
|
|
||||||
String_type result( 6, '\\' );
|
String_type result( 6, '\\' );
|
||||||
|
|
||||||
result[1] = 'u';
|
result[1] = 'u';
|
||||||
|
@ -7,7 +7,11 @@
|
|||||||
#include "kernel.h"
|
#include "kernel.h"
|
||||||
#include "db.h"
|
#include "db.h"
|
||||||
|
|
||||||
using namespace std;
|
#include <algorithm>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
extern int nStakeMaxAge;
|
extern int nStakeMaxAge;
|
||||||
extern int nStakeTargetSpacing;
|
extern int nStakeTargetSpacing;
|
||||||
@ -38,7 +42,7 @@ int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
|
|||||||
// this change increases active coins participating the hash and helps
|
// this change increases active coins participating the hash and helps
|
||||||
// to secure the network when proof-of-stake difficulty is low
|
// to secure the network when proof-of-stake difficulty is low
|
||||||
|
|
||||||
return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
|
return std::min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the last stake modifier and its generation time from a given block
|
// Get the last stake modifier and its generation time from a given block
|
||||||
@ -75,8 +79,8 @@ static int64 GetStakeModifierSelectionInterval()
|
|||||||
// already selected blocks in vSelectedBlocks, and with timestamp up to
|
// already selected blocks in vSelectedBlocks, and with timestamp up to
|
||||||
// nSelectionIntervalStop.
|
// nSelectionIntervalStop.
|
||||||
static bool SelectBlockFromCandidates(
|
static bool SelectBlockFromCandidates(
|
||||||
vector<pair<int64, uint256> >& vSortedByTimestamp,
|
std::vector<std::pair<int64, uint256> >& vSortedByTimestamp,
|
||||||
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
|
std::map<uint256, const CBlockIndex*>& mapSelectedBlocks,
|
||||||
int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
|
int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
|
||||||
const CBlockIndex** pindexSelected)
|
const CBlockIndex** pindexSelected)
|
||||||
{
|
{
|
||||||
@ -149,20 +153,20 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
|
|||||||
return error("ComputeNextStakeModifier: unable to get last modifier");
|
return error("ComputeNextStakeModifier: unable to get last modifier");
|
||||||
if (fDebug)
|
if (fDebug)
|
||||||
{
|
{
|
||||||
printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
|
printf("ComputeNextStakeModifier: prev modifier=0x%016" PRI64x " time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
|
||||||
}
|
}
|
||||||
if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
|
if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
// Sort candidate blocks by timestamp
|
// Sort candidate blocks by timestamp
|
||||||
vector<pair<int64, uint256> > vSortedByTimestamp;
|
std::vector<std::pair<int64, uint256> > vSortedByTimestamp;
|
||||||
vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
|
vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
|
||||||
int64 nSelectionInterval = GetStakeModifierSelectionInterval();
|
int64 nSelectionInterval = GetStakeModifierSelectionInterval();
|
||||||
int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
|
int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
|
||||||
const CBlockIndex* pindex = pindexPrev;
|
const CBlockIndex* pindex = pindexPrev;
|
||||||
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
|
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
|
||||||
{
|
{
|
||||||
vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
|
vSortedByTimestamp.push_back(std::make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
|
||||||
pindex = pindex->pprev;
|
pindex = pindex->pprev;
|
||||||
}
|
}
|
||||||
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
|
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
|
||||||
@ -172,8 +176,8 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
|
|||||||
// Select 64 blocks from candidate blocks to generate stake modifier
|
// Select 64 blocks from candidate blocks to generate stake modifier
|
||||||
uint64 nStakeModifierNew = 0;
|
uint64 nStakeModifierNew = 0;
|
||||||
int64 nSelectionIntervalStop = nSelectionIntervalStart;
|
int64 nSelectionIntervalStop = nSelectionIntervalStart;
|
||||||
map<uint256, const CBlockIndex*> mapSelectedBlocks;
|
std::map<uint256, const CBlockIndex*> mapSelectedBlocks;
|
||||||
for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
|
for (int nRound=0; nRound<std::min(64, (int)vSortedByTimestamp.size()); nRound++)
|
||||||
{
|
{
|
||||||
// add an interval section to the current selection round
|
// add an interval section to the current selection round
|
||||||
nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
|
nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
|
||||||
@ -183,7 +187,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
|
|||||||
// write the entropy bit of the selected block
|
// write the entropy bit of the selected block
|
||||||
nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
|
nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
|
||||||
// add the selected block from candidates to selected list
|
// add the selected block from candidates to selected list
|
||||||
mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
|
mapSelectedBlocks.insert(std::make_pair(pindex->GetBlockHash(), pindex));
|
||||||
if (fDebug && GetBoolArg("-printstakemodifier"))
|
if (fDebug && GetBoolArg("-printstakemodifier"))
|
||||||
printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
|
printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
|
||||||
nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
|
nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
|
||||||
@ -192,7 +196,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
|
|||||||
// Print selection map for visualization of the selected blocks
|
// Print selection map for visualization of the selected blocks
|
||||||
if (fDebug && GetBoolArg("-printstakemodifier"))
|
if (fDebug && GetBoolArg("-printstakemodifier"))
|
||||||
{
|
{
|
||||||
string strSelectionMap = "";
|
std::string strSelectionMap = "";
|
||||||
// '-' indicates proof-of-work blocks not selected
|
// '-' indicates proof-of-work blocks not selected
|
||||||
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
|
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
|
||||||
pindex = pindexPrev;
|
pindex = pindexPrev;
|
||||||
@ -213,7 +217,7 @@ bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModif
|
|||||||
}
|
}
|
||||||
if (fDebug)
|
if (fDebug)
|
||||||
{
|
{
|
||||||
printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
|
printf("ComputeNextStakeModifier: new modifier=0x%016" PRI64x " time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
nStakeModifier = nStakeModifierNew;
|
nStakeModifier = nStakeModifierNew;
|
||||||
@ -294,7 +298,7 @@ bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned
|
|||||||
// v0.3 protocol kernel hash weight starts from 0 at the 30-day min age
|
// v0.3 protocol kernel hash weight starts from 0 at the 30-day min age
|
||||||
// this change increases active coins participating the hash and helps
|
// this change increases active coins participating the hash and helps
|
||||||
// to secure the network when proof-of-stake difficulty is low
|
// to secure the network when proof-of-stake difficulty is low
|
||||||
int64 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
|
int64 nTimeWeight = std::min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
|
||||||
CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
|
CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
|
||||||
|
|
||||||
// Calculate hash
|
// Calculate hash
|
||||||
@ -311,12 +315,12 @@ bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned
|
|||||||
hashProofOfStake = Hash(ss.begin(), ss.end());
|
hashProofOfStake = Hash(ss.begin(), ss.end());
|
||||||
if (fPrintProofOfStake)
|
if (fPrintProofOfStake)
|
||||||
{
|
{
|
||||||
printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
|
printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x " at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
|
||||||
nStakeModifier, nStakeModifierHeight,
|
nStakeModifier, nStakeModifierHeight,
|
||||||
DateTimeStrFormat(nStakeModifierTime).c_str(),
|
DateTimeStrFormat(nStakeModifierTime).c_str(),
|
||||||
mapBlockIndex[blockFrom.GetHash()]->nHeight,
|
mapBlockIndex[blockFrom.GetHash()]->nHeight,
|
||||||
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
|
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
|
||||||
printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
|
printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016" PRI64x " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
|
||||||
"0.3",
|
"0.3",
|
||||||
nStakeModifier,
|
nStakeModifier,
|
||||||
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
|
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
|
||||||
@ -328,12 +332,12 @@ bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned
|
|||||||
return false;
|
return false;
|
||||||
if (fDebug && !fPrintProofOfStake)
|
if (fDebug && !fPrintProofOfStake)
|
||||||
{
|
{
|
||||||
printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
|
printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x " at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
|
||||||
nStakeModifier, nStakeModifierHeight,
|
nStakeModifier, nStakeModifierHeight,
|
||||||
DateTimeStrFormat(nStakeModifierTime).c_str(),
|
DateTimeStrFormat(nStakeModifierTime).c_str(),
|
||||||
mapBlockIndex[blockFrom.GetHash()]->nHeight,
|
mapBlockIndex[blockFrom.GetHash()]->nHeight,
|
||||||
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
|
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
|
||||||
printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
|
printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016" PRI64x " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
|
||||||
"0.3",
|
"0.3",
|
||||||
nStakeModifier,
|
nStakeModifier,
|
||||||
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
|
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
|
||||||
|
292
src/main.cpp
292
src/main.cpp
@ -15,8 +15,14 @@
|
|||||||
#include <boost/filesystem.hpp>
|
#include <boost/filesystem.hpp>
|
||||||
#include <boost/filesystem/fstream.hpp>
|
#include <boost/filesystem/fstream.hpp>
|
||||||
|
|
||||||
using namespace std;
|
#include <cstdio>
|
||||||
using namespace boost;
|
#include <list>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
const bool IsCalculatingGenesisBlockHash = false;
|
const bool IsCalculatingGenesisBlockHash = false;
|
||||||
|
|
||||||
@ -25,15 +31,15 @@ const bool IsCalculatingGenesisBlockHash = false;
|
|||||||
//
|
//
|
||||||
|
|
||||||
CCriticalSection cs_setpwalletRegistered;
|
CCriticalSection cs_setpwalletRegistered;
|
||||||
set<CWallet*> setpwalletRegistered;
|
std::set<CWallet*> setpwalletRegistered;
|
||||||
|
|
||||||
CCriticalSection cs_main;
|
CCriticalSection cs_main;
|
||||||
|
|
||||||
CTxMemPool mempool;
|
CTxMemPool mempool;
|
||||||
unsigned int nTransactionsUpdated = 0;
|
unsigned int nTransactionsUpdated = 0;
|
||||||
|
|
||||||
map<uint256, CBlockIndex*> mapBlockIndex;
|
std::map<uint256, CBlockIndex*> mapBlockIndex;
|
||||||
set<pair<COutPoint, unsigned int> > setStakeSeen;
|
std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
|
||||||
uint256 hashGenesisBlock = hashGenesisBlockOfficial;
|
uint256 hashGenesisBlock = hashGenesisBlockOfficial;
|
||||||
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
|
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
|
||||||
static CBigNum bnProofOfStakeLimit(~uint256(0) >> 24);
|
static CBigNum bnProofOfStakeLimit(~uint256(0) >> 24);
|
||||||
@ -59,18 +65,18 @@ int64 nTimeBestReceived = 0;
|
|||||||
|
|
||||||
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
|
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
|
||||||
|
|
||||||
map<uint256, CBlock*> mapOrphanBlocks;
|
std::map<uint256, CBlock*> mapOrphanBlocks;
|
||||||
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
|
std::multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
|
||||||
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
|
std::set<std::pair<COutPoint, unsigned int> > setStakeSeenOrphan;
|
||||||
map<uint256, uint256> mapProofOfStake;
|
std::map<uint256, uint256> mapProofOfStake;
|
||||||
|
|
||||||
map<uint256, CDataStream*> mapOrphanTransactions;
|
std::map<uint256, CDataStream*> mapOrphanTransactions;
|
||||||
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
|
std::map<uint256, std::map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
|
||||||
|
|
||||||
// Constant stuff for coinbase transactions we create:
|
// Constant stuff for coinbase transactions we create:
|
||||||
CScript COINBASE_FLAGS;
|
CScript COINBASE_FLAGS;
|
||||||
|
|
||||||
const string strMessageMagic = "curecoin Signed Message:\n";
|
const std::string strMessageMagic = "curecoin Signed Message:\n";
|
||||||
|
|
||||||
double dHashesPerSec;
|
double dHashesPerSec;
|
||||||
int64 nHPSTimerStart;
|
int64 nHPSTimerStart;
|
||||||
@ -215,16 +221,16 @@ bool AddOrphanTx(const CDataStream& vMsg)
|
|||||||
// at most 500 megabytes of orphans:
|
// at most 500 megabytes of orphans:
|
||||||
if (pvMsg->size() > 5000)
|
if (pvMsg->size() > 5000)
|
||||||
{
|
{
|
||||||
printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
|
printf("ignoring large orphan tx (size: %" PRIszu ", hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
|
||||||
delete pvMsg;
|
delete pvMsg;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
mapOrphanTransactions[hash] = pvMsg;
|
mapOrphanTransactions[hash] = pvMsg;
|
||||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||||
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
|
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(std::make_pair(hash, pvMsg));
|
||||||
|
|
||||||
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(),
|
printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().substr(0,10).c_str(),
|
||||||
mapOrphanTransactions.size());
|
mapOrphanTransactions.size());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -253,7 +259,7 @@ unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
|
|||||||
{
|
{
|
||||||
// Evict a random orphan:
|
// Evict a random orphan:
|
||||||
uint256 randomhash = GetRandHash();
|
uint256 randomhash = GetRandHash();
|
||||||
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
|
std::map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
|
||||||
if (it == mapOrphanTransactions.end())
|
if (it == mapOrphanTransactions.end())
|
||||||
it = mapOrphanTransactions.begin();
|
it = mapOrphanTransactions.begin();
|
||||||
EraseOrphanTx(it->first);
|
EraseOrphanTx(it->first);
|
||||||
@ -348,7 +354,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
|
|||||||
{
|
{
|
||||||
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
|
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
|
||||||
|
|
||||||
vector<vector<unsigned char> > vSolutions;
|
std::vector<std::vector<unsigned char> > vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
// get the scriptPubKey corresponding to this input:
|
// get the scriptPubKey corresponding to this input:
|
||||||
const CScript& prevScript = prev.scriptPubKey;
|
const CScript& prevScript = prev.scriptPubKey;
|
||||||
@ -363,7 +369,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
|
|||||||
// be quick, because if there are any operations
|
// be quick, because if there are any operations
|
||||||
// beside "push data" in the scriptSig the
|
// beside "push data" in the scriptSig the
|
||||||
// IsStandard() call returns false
|
// IsStandard() call returns false
|
||||||
vector<vector<unsigned char> > stack;
|
std::vector<std::vector<unsigned char> > stack;
|
||||||
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
|
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -372,7 +378,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
|
|||||||
if (stack.empty())
|
if (stack.empty())
|
||||||
return false;
|
return false;
|
||||||
CScript subscript(stack.back().begin(), stack.back().end());
|
CScript subscript(stack.back().begin(), stack.back().end());
|
||||||
vector<vector<unsigned char> > vSolutions2;
|
std::vector<std::vector<unsigned char> > vSolutions2;
|
||||||
txnouttype whichType2;
|
txnouttype whichType2;
|
||||||
if (!Solver(subscript, whichType2, vSolutions2))
|
if (!Solver(subscript, whichType2, vSolutions2))
|
||||||
return false;
|
return false;
|
||||||
@ -450,7 +456,7 @@ int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Is the tx in a block that's in the main chain
|
// Is the tx in a block that's in the main chain
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
||||||
if (mi == mapBlockIndex.end())
|
if (mi == mapBlockIndex.end())
|
||||||
return 0;
|
return 0;
|
||||||
CBlockIndex* pindex = (*mi).second;
|
CBlockIndex* pindex = (*mi).second;
|
||||||
@ -497,7 +503,7 @@ bool CTransaction::CheckTransaction() const
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check for duplicate inputs
|
// Check for duplicate inputs
|
||||||
set<COutPoint> vInOutPoints;
|
std::set<COutPoint> vInOutPoints;
|
||||||
BOOST_FOREACH(const CTxIn& txin, vin)
|
BOOST_FOREACH(const CTxIn& txin, vin)
|
||||||
{
|
{
|
||||||
if (vInOutPoints.count(txin.prevout))
|
if (vInOutPoints.count(txin.prevout))
|
||||||
@ -619,7 +625,7 @@ bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
|
|||||||
if (fCheckInputs)
|
if (fCheckInputs)
|
||||||
{
|
{
|
||||||
MapPrevTx mapInputs;
|
MapPrevTx mapInputs;
|
||||||
map<uint256, CTxIndex> mapUnused;
|
std::map<uint256, CTxIndex> mapUnused;
|
||||||
bool fInvalid = false;
|
bool fInvalid = false;
|
||||||
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
|
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
|
||||||
{
|
{
|
||||||
@ -644,7 +650,7 @@ bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
|
|||||||
// Don't accept it if it can't get into a block
|
// Don't accept it if it can't get into a block
|
||||||
int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
|
int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY);
|
||||||
if (nFees < txMinFee)
|
if (nFees < txMinFee)
|
||||||
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
|
return error("CTxMemPool::accept() : not enough fees %s, %" PRI64d " < %" PRI64d,
|
||||||
hash.ToString().c_str(),
|
hash.ToString().c_str(),
|
||||||
nFees, txMinFee);
|
nFees, txMinFee);
|
||||||
|
|
||||||
@ -697,7 +703,7 @@ bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
|
|||||||
if (ptxOld)
|
if (ptxOld)
|
||||||
EraseFromWallets(ptxOld->GetHash());
|
EraseFromWallets(ptxOld->GetHash());
|
||||||
|
|
||||||
printf("CTxMemPool::accept() : accepted %s (poolsz %"PRIszu")\n",
|
printf("CTxMemPool::accept() : accepted %s (poolsz %" PRIszu ")\n",
|
||||||
hash.ToString().substr(0,10).c_str(),
|
hash.ToString().substr(0,10).c_str(),
|
||||||
mapTx.size());
|
mapTx.size());
|
||||||
return true;
|
return true;
|
||||||
@ -753,7 +759,7 @@ void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
|
|||||||
|
|
||||||
LOCK(cs);
|
LOCK(cs);
|
||||||
vtxid.reserve(mapTx.size());
|
vtxid.reserve(mapTx.size());
|
||||||
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
|
for (std::map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
|
||||||
vtxid.push_back((*mi).first);
|
vtxid.push_back((*mi).first);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -766,7 +772,7 @@ int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
|
|||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
// Find the block it claims to be in
|
// Find the block it claims to be in
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
||||||
if (mi == mapBlockIndex.end())
|
if (mi == mapBlockIndex.end())
|
||||||
return 0;
|
return 0;
|
||||||
CBlockIndex* pindex = (*mi).second;
|
CBlockIndex* pindex = (*mi).second;
|
||||||
@ -790,7 +796,7 @@ int CMerkleTx::GetBlocksToMaturity() const
|
|||||||
{
|
{
|
||||||
if (!(IsCoinBase() || IsCoinStake()))
|
if (!(IsCoinBase() || IsCoinStake()))
|
||||||
return 0;
|
return 0;
|
||||||
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
|
return std::max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -849,7 +855,7 @@ int CTxIndex::GetDepthInMainChain() const
|
|||||||
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
|
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
|
||||||
return 0;
|
return 0;
|
||||||
// Find the block in the index
|
// Find the block in the index
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
|
||||||
if (mi == mapBlockIndex.end())
|
if (mi == mapBlockIndex.end())
|
||||||
return 0;
|
return 0;
|
||||||
CBlockIndex* pindex = (*mi).second;
|
CBlockIndex* pindex = (*mi).second;
|
||||||
@ -1059,21 +1065,21 @@ int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nBits, unsigned int nTi
|
|||||||
{
|
{
|
||||||
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
|
CBigNum bnMidValue = (bnLowerBound + bnUpperBound) / 2;
|
||||||
if (fDebug && GetBoolArg("-printcreation"))
|
if (fDebug && GetBoolArg("-printcreation"))
|
||||||
printf("GetProofOfStakeReward() : lower=%"PRI64d" upper=%"PRI64d" mid=%"PRI64d"\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
|
printf("GetProofOfStakeReward() : lower=%" PRI64d " upper=%" PRI64d " mid=%" PRI64d "\n", bnLowerBound.getuint64(), bnUpperBound.getuint64(), bnMidValue.getuint64());
|
||||||
if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget)
|
if (bnMidValue * bnMidValue * bnMidValue * bnMidValue * bnTargetLimit > bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnRewardCoinYearLimit * bnTarget)
|
||||||
bnUpperBound = bnMidValue;
|
bnUpperBound = bnMidValue;
|
||||||
else
|
else
|
||||||
bnLowerBound = bnMidValue;
|
bnLowerBound = bnMidValue;
|
||||||
}
|
}
|
||||||
nRewardCoinYear = bnUpperBound.getuint64();
|
nRewardCoinYear = bnUpperBound.getuint64();
|
||||||
if (nBestHeight > (int)HF_BLOCK) min(nRewardCoinYear, (int64)(0.04 * MAX_MINT_PROOF_OF_WORK)); // 4% hardfork
|
if (nBestHeight > (int)HF_BLOCK) std::min(nRewardCoinYear, (int64)(0.04 * MAX_MINT_PROOF_OF_WORK)); // 4% hardfork
|
||||||
else nRewardCoinYear = min(nRewardCoinYear, MAX_MINT_PROOF_OF_STAKE);
|
else nRewardCoinYear = std::min(nRewardCoinYear, MAX_MINT_PROOF_OF_STAKE);
|
||||||
|
|
||||||
|
|
||||||
int64 nSubsidy = nRewardCoinYear * nCoinAge * 33 / (365 * 33 + 8) ;
|
int64 nSubsidy = nRewardCoinYear * nCoinAge * 33 / (365 * 33 + 8) ;
|
||||||
|
|
||||||
if (fDebug && GetBoolArg("-printcreation"))
|
if (fDebug && GetBoolArg("-printcreation"))
|
||||||
printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRI64d" nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
|
printf("GetProofOfStakeReward(): create=%s nCoinAge=%" PRI64d " nBits=%d\n", FormatMoney(nSubsidy).c_str(), nCoinAge, nBits);
|
||||||
|
|
||||||
return nSubsidy;
|
return nSubsidy;
|
||||||
}
|
}
|
||||||
@ -1169,7 +1175,7 @@ unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fP
|
|||||||
CBigNum bnNew;
|
CBigNum bnNew;
|
||||||
bnNew.SetCompact(pindexPrev->nBits);
|
bnNew.SetCompact(pindexPrev->nBits);
|
||||||
if (pindexLast->nHeight > (int)HF_BLOCK) nStakeTargetSpacing = 4 * 60; // 4 minute target enforced
|
if (pindexLast->nHeight > (int)HF_BLOCK) nStakeTargetSpacing = 4 * 60; // 4 minute target enforced
|
||||||
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
|
int64 nTargetSpacing = fProofOfStake? nStakeTargetSpacing : std::min(nTargetSpacingWorkMax, (int64) nStakeTargetSpacing * (1 + pindexLast->nHeight - pindexPrev->nHeight));
|
||||||
int64 nInterval = nTargetTimespan / nTargetSpacing;
|
int64 nInterval = nTargetTimespan / nTargetSpacing;
|
||||||
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
|
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
|
||||||
bnNew /= ((nInterval + 1) * nTargetSpacing);
|
bnNew /= ((nInterval + 1) * nTargetSpacing);
|
||||||
@ -1243,7 +1249,7 @@ void static InvalidChainFound(CBlockIndex* pindexNew)
|
|||||||
|
|
||||||
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
|
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
|
||||||
{
|
{
|
||||||
nTime = max(GetBlockTime(), GetAdjustedTime());
|
nTime = std::max(GetBlockTime(), GetAdjustedTime());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -1292,7 +1298,7 @@ bool CTransaction::DisconnectInputs(CTxDB& txdb)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
|
bool CTransaction::FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
|
||||||
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
|
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
|
||||||
{
|
{
|
||||||
// FetchInputs can return false either because we just haven't seen some inputs
|
// FetchInputs can return false either because we just haven't seen some inputs
|
||||||
@ -1360,7 +1366,7 @@ bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTes
|
|||||||
// Revisit this if/when transaction replacement is implemented and allows
|
// Revisit this if/when transaction replacement is implemented and allows
|
||||||
// adding inputs:
|
// adding inputs:
|
||||||
fInvalid = true;
|
fInvalid = true;
|
||||||
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
|
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %" PRIszu " %" PRIszu " prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1410,7 +1416,7 @@ unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
|
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
|
||||||
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
|
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
|
||||||
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
|
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
|
||||||
{
|
{
|
||||||
// Take over previous transactions' spent pointers
|
// Take over previous transactions' spent pointers
|
||||||
@ -1429,7 +1435,7 @@ bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
|
|||||||
CTransaction& txPrev = inputs[prevout.hash].second;
|
CTransaction& txPrev = inputs[prevout.hash].second;
|
||||||
|
|
||||||
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
|
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
|
||||||
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
|
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %" PRIszu " %" PRIszu " prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
|
||||||
|
|
||||||
// If prev is coinbase or coinstake, check that it's matured
|
// If prev is coinbase or coinstake, check that it's matured
|
||||||
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
|
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
|
||||||
@ -1626,7 +1632,7 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
|
|||||||
else
|
else
|
||||||
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
|
nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
|
||||||
|
|
||||||
map<uint256, CTxIndex> mapQueuedChanges;
|
std::map<uint256, CTxIndex> mapQueuedChanges;
|
||||||
int64 nFees = 0;
|
int64 nFees = 0;
|
||||||
int64 nValueIn = 0;
|
int64 nValueIn = 0;
|
||||||
int64 nValueOut = 0;
|
int64 nValueOut = 0;
|
||||||
@ -1694,13 +1700,13 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck)
|
|||||||
// ppcoin: fees are not collected by miners as in curecoin
|
// ppcoin: fees are not collected by miners as in curecoin
|
||||||
// ppcoin: fees are destroyed to compensate the entire network
|
// ppcoin: fees are destroyed to compensate the entire network
|
||||||
if (fDebug && GetBoolArg("-printcreation"))
|
if (fDebug && GetBoolArg("-printcreation"))
|
||||||
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
|
printf("ConnectBlock() : destroy=%s nFees=%" PRI64d "\n", FormatMoney(nFees).c_str(), nFees);
|
||||||
|
|
||||||
if (fJustCheck)
|
if (fJustCheck)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
// Write queued txindex changes
|
// Write queued txindex changes
|
||||||
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
|
for (std::map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
|
||||||
{
|
{
|
||||||
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
|
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
|
||||||
return error("ConnectBlock() : UpdateTxIndex failed");
|
return error("ConnectBlock() : UpdateTxIndex failed");
|
||||||
@ -1753,21 +1759,21 @@ bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// List of what to disconnect
|
// List of what to disconnect
|
||||||
vector<CBlockIndex*> vDisconnect;
|
std::vector<CBlockIndex*> vDisconnect;
|
||||||
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
|
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
|
||||||
vDisconnect.push_back(pindex);
|
vDisconnect.push_back(pindex);
|
||||||
|
|
||||||
// List of what to connect
|
// List of what to connect
|
||||||
vector<CBlockIndex*> vConnect;
|
std::vector<CBlockIndex*> vConnect;
|
||||||
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
|
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
|
||||||
vConnect.push_back(pindex);
|
vConnect.push_back(pindex);
|
||||||
reverse(vConnect.begin(), vConnect.end());
|
reverse(vConnect.begin(), vConnect.end());
|
||||||
|
|
||||||
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
|
printf("REORGANIZE: Disconnect %" PRIszu " blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
|
||||||
printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
|
printf("REORGANIZE: Connect %" PRIszu " blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
|
||||||
|
|
||||||
// Disconnect shorter branch
|
// Disconnect shorter branch
|
||||||
vector<CTransaction> vResurrect;
|
std::vector<CTransaction> vResurrect;
|
||||||
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
|
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
|
||||||
{
|
{
|
||||||
CBlock block;
|
CBlock block;
|
||||||
@ -1783,7 +1789,7 @@ bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Connect longer branch
|
// Connect longer branch
|
||||||
vector<CTransaction> vDelete;
|
std::vector<CTransaction> vDelete;
|
||||||
for (unsigned int i = 0; i < vConnect.size(); i++)
|
for (unsigned int i = 0; i < vConnect.size(); i++)
|
||||||
{
|
{
|
||||||
CBlockIndex* pindex = vConnect[i];
|
CBlockIndex* pindex = vConnect[i];
|
||||||
@ -1892,7 +1898,7 @@ bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!vpindexSecondary.empty())
|
if (!vpindexSecondary.empty())
|
||||||
printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size());
|
printf("Postponing %" PRIszu " reconnects\n", vpindexSecondary.size());
|
||||||
|
|
||||||
// Switch to new best branch
|
// Switch to new best branch
|
||||||
if (!Reorganize(txdb, pindexIntermediate))
|
if (!Reorganize(txdb, pindexIntermediate))
|
||||||
@ -2007,7 +2013,7 @@ bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
|
|||||||
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
|
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
|
||||||
|
|
||||||
if (fDebug && GetBoolArg("-printcoinage"))
|
if (fDebug && GetBoolArg("-printcoinage"))
|
||||||
printf("coin age nValueIn=%"PRI64d" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
|
printf("coin age nValueIn=%" PRI64d " nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
|
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
|
||||||
@ -2035,7 +2041,7 @@ bool CBlock::GetCoinAge(uint64& nCoinAge) const
|
|||||||
if (nCoinAge == 0) // block coin age minimum 1 coin-day
|
if (nCoinAge == 0) // block coin age minimum 1 coin-day
|
||||||
nCoinAge = 1;
|
nCoinAge = 1;
|
||||||
if (fDebug && GetBoolArg("-printcoinage"))
|
if (fDebug && GetBoolArg("-printcoinage"))
|
||||||
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
|
printf("block coin age total nCoinDays=%" PRI64d "\n", nCoinAge);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2051,7 +2057,7 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
|
|||||||
if (!pindexNew)
|
if (!pindexNew)
|
||||||
return error("AddToBlockIndex() : new CBlockIndex failed");
|
return error("AddToBlockIndex() : new CBlockIndex failed");
|
||||||
pindexNew->phashBlock = &hash;
|
pindexNew->phashBlock = &hash;
|
||||||
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
|
std::map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
|
||||||
if (miPrev != mapBlockIndex.end())
|
if (miPrev != mapBlockIndex.end())
|
||||||
{
|
{
|
||||||
pindexNew->pprev = (*miPrev).second;
|
pindexNew->pprev = (*miPrev).second;
|
||||||
@ -2081,12 +2087,12 @@ bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
|
|||||||
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
|
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
|
||||||
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
|
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
|
||||||
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
|
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
|
||||||
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
|
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016" PRI64x, pindexNew->nHeight, nStakeModifier);
|
||||||
|
|
||||||
// Add to mapBlockIndex
|
// Add to mapBlockIndex
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(std::make_pair(hash, pindexNew)).first;
|
||||||
if (pindexNew->IsProofOfStake())
|
if (pindexNew->IsProofOfStake())
|
||||||
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
|
setStakeSeen.insert(std::make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
|
||||||
pindexNew->phashBlock = &((*mi).first);
|
pindexNew->phashBlock = &((*mi).first);
|
||||||
|
|
||||||
// Write to disk block index
|
// Write to disk block index
|
||||||
@ -2166,7 +2172,7 @@ bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
|
|||||||
|
|
||||||
// Check coinstake timestamp
|
// Check coinstake timestamp
|
||||||
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
|
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
|
||||||
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRI64d" nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
|
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%" PRI64d " nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
|
||||||
|
|
||||||
|
|
||||||
// Check transactions
|
// Check transactions
|
||||||
@ -2182,7 +2188,7 @@ bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot) const
|
|||||||
|
|
||||||
// Check for duplicate txids. This is caught by ConnectInputs(),
|
// Check for duplicate txids. This is caught by ConnectInputs(),
|
||||||
// but catching it earlier avoids a potential DoS attack:
|
// but catching it earlier avoids a potential DoS attack:
|
||||||
set<uint256> uniqueTx;
|
std::set<uint256> uniqueTx;
|
||||||
BOOST_FOREACH(const CTransaction& tx, vtx)
|
BOOST_FOREACH(const CTransaction& tx, vtx)
|
||||||
{
|
{
|
||||||
uniqueTx.insert(tx.GetHash());
|
uniqueTx.insert(tx.GetHash());
|
||||||
@ -2221,7 +2227,7 @@ bool CBlock::AcceptBlock()
|
|||||||
return error("AcceptBlock() : block already in mapBlockIndex");
|
return error("AcceptBlock() : block already in mapBlockIndex");
|
||||||
|
|
||||||
// Get prev block index
|
// Get prev block index
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
|
||||||
if (mi == mapBlockIndex.end())
|
if (mi == mapBlockIndex.end())
|
||||||
return DoS(10, error("AcceptBlock() : prev block not found"));
|
return DoS(10, error("AcceptBlock() : prev block not found"));
|
||||||
CBlockIndex* pindexPrev = (*mi).second;
|
CBlockIndex* pindexPrev = (*mi).second;
|
||||||
@ -2341,7 +2347,7 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
|
|||||||
return false; // do not error here as we expect this during initial block download
|
return false; // do not error here as we expect this during initial block download
|
||||||
}
|
}
|
||||||
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
|
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
|
||||||
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
|
mapProofOfStake.insert(std::make_pair(hash, hashProofOfStake));
|
||||||
}
|
}
|
||||||
|
|
||||||
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
|
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
|
||||||
@ -2380,8 +2386,8 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
|
|||||||
else
|
else
|
||||||
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
|
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
|
||||||
}
|
}
|
||||||
mapOrphanBlocks.insert(make_pair(hash, pblock2));
|
mapOrphanBlocks.insert(std::make_pair(hash, pblock2));
|
||||||
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
|
mapOrphanBlocksByPrev.insert(std::make_pair(pblock2->hashPrevBlock, pblock2));
|
||||||
|
|
||||||
// Ask this guy to fill in what we're missing
|
// Ask this guy to fill in what we're missing
|
||||||
if (pfrom)
|
if (pfrom)
|
||||||
@ -2400,12 +2406,12 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
|
|||||||
return error("ProcessBlock() : AcceptBlock FAILED");
|
return error("ProcessBlock() : AcceptBlock FAILED");
|
||||||
|
|
||||||
// Recursively process any orphan blocks that depended on this one
|
// Recursively process any orphan blocks that depended on this one
|
||||||
vector<uint256> vWorkQueue;
|
std::vector<uint256> vWorkQueue;
|
||||||
vWorkQueue.push_back(hash);
|
vWorkQueue.push_back(hash);
|
||||||
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
||||||
{
|
{
|
||||||
uint256 hashPrev = vWorkQueue[i];
|
uint256 hashPrev = vWorkQueue[i];
|
||||||
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
|
for (std::multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
|
||||||
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
|
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
|
||||||
++mi)
|
++mi)
|
||||||
{
|
{
|
||||||
@ -2431,7 +2437,7 @@ bool ProcessBlock(CNode* pfrom, CBlock* pblock)
|
|||||||
// ppcoin: sign block
|
// ppcoin: sign block
|
||||||
bool CBlock::SignBlock(const CKeyStore& keystore)
|
bool CBlock::SignBlock(const CKeyStore& keystore)
|
||||||
{
|
{
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
|
|
||||||
if(!IsProofOfStake())
|
if(!IsProofOfStake())
|
||||||
@ -2492,7 +2498,7 @@ bool CBlock::CheckBlockSignature() const
|
|||||||
if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
|
if (GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
|
||||||
return vchBlockSig.empty();
|
return vchBlockSig.empty();
|
||||||
|
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
|
|
||||||
if(IsProofOfStake())
|
if(IsProofOfStake())
|
||||||
@ -2548,7 +2554,7 @@ bool CheckDiskSpace(uint64 nAdditionalBytes)
|
|||||||
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
|
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
|
||||||
{
|
{
|
||||||
fShutdown = true;
|
fShutdown = true;
|
||||||
string strMessage = _("Warning: Disk space is low!");
|
std::string strMessage = _("Warning: Disk space is low!");
|
||||||
strMiscWarning = strMessage;
|
strMiscWarning = strMessage;
|
||||||
printf("*** %s\n", strMessage.c_str());
|
printf("*** %s\n", strMessage.c_str());
|
||||||
uiInterface.ThreadSafeMessageBox(strMessage, "curecoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
|
uiInterface.ThreadSafeMessageBox(strMessage, "curecoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
|
||||||
@ -2560,7 +2566,7 @@ bool CheckDiskSpace(uint64 nAdditionalBytes)
|
|||||||
|
|
||||||
static boost::filesystem::path BlockFilePath(unsigned int nFile)
|
static boost::filesystem::path BlockFilePath(unsigned int nFile)
|
||||||
{
|
{
|
||||||
string strBlockFn = strprintf("blk%04u.dat", nFile);
|
std::string strBlockFn = strprintf("blk%04u.dat", nFile);
|
||||||
return GetDataDir() / strBlockFn;
|
return GetDataDir() / strBlockFn;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2645,7 +2651,7 @@ bool LoadBlockIndex(bool fAllowNew)
|
|||||||
txNew.nTime = nChainStartTime;
|
txNew.nTime = nChainStartTime;
|
||||||
txNew.vin.resize(1);
|
txNew.vin.resize(1);
|
||||||
txNew.vout.resize(1);
|
txNew.vout.resize(1);
|
||||||
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
|
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
|
||||||
txNew.vout[0].SetEmpty();
|
txNew.vout[0].SetEmpty();
|
||||||
//txNew.vout[0].scriptPubKey = CScript() << ParseHex(pszMainKey) << OP_CHECKSIG;
|
//txNew.vout[0].scriptPubKey = CScript() << ParseHex(pszMainKey) << OP_CHECKSIG;
|
||||||
txNew.strTxComment = "text:curecoin genesis block";
|
txNew.strTxComment = "text:curecoin genesis block";
|
||||||
@ -2714,7 +2720,7 @@ bool LoadBlockIndex(bool fAllowNew)
|
|||||||
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
|
// ppcoin: if checkpoint master key changed must reset sync-checkpoint
|
||||||
{
|
{
|
||||||
CTxDB txdb;
|
CTxDB txdb;
|
||||||
string strPubKey = "";
|
std::string strPubKey = "";
|
||||||
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
|
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
|
||||||
{
|
{
|
||||||
// write checkpoint master key to db
|
// write checkpoint master key to db
|
||||||
@ -2743,8 +2749,8 @@ bool LoadBlockIndex(bool fAllowNew)
|
|||||||
void PrintBlockTree()
|
void PrintBlockTree()
|
||||||
{
|
{
|
||||||
// pre-compute tree structure
|
// pre-compute tree structure
|
||||||
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
|
std::map<CBlockIndex*, std::vector<CBlockIndex*> > mapNext;
|
||||||
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
|
for (std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
|
||||||
{
|
{
|
||||||
CBlockIndex* pindex = (*mi).second;
|
CBlockIndex* pindex = (*mi).second;
|
||||||
mapNext[pindex->pprev].push_back(pindex);
|
mapNext[pindex->pprev].push_back(pindex);
|
||||||
@ -2753,8 +2759,8 @@ void PrintBlockTree()
|
|||||||
// mapNext[pindex->pprev].push_back(pindex);
|
// mapNext[pindex->pprev].push_back(pindex);
|
||||||
}
|
}
|
||||||
|
|
||||||
vector<pair<int, CBlockIndex*> > vStack;
|
std::vector<std::pair<int, CBlockIndex*> > vStack;
|
||||||
vStack.push_back(make_pair(0, pindexGenesisBlock));
|
vStack.push_back(std::make_pair(0, pindexGenesisBlock));
|
||||||
|
|
||||||
int nPrevCol = 0;
|
int nPrevCol = 0;
|
||||||
while (!vStack.empty())
|
while (!vStack.empty())
|
||||||
@ -2785,7 +2791,7 @@ void PrintBlockTree()
|
|||||||
// print item
|
// print item
|
||||||
CBlock block;
|
CBlock block;
|
||||||
block.ReadFromDisk(pindex);
|
block.ReadFromDisk(pindex);
|
||||||
printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"",
|
printf("%d (%u,%u) %s %08x %s mint %7s tx %" PRIszu "",
|
||||||
pindex->nHeight,
|
pindex->nHeight,
|
||||||
pindex->nFile,
|
pindex->nFile,
|
||||||
pindex->nBlockPos,
|
pindex->nBlockPos,
|
||||||
@ -2798,19 +2804,19 @@ void PrintBlockTree()
|
|||||||
PrintWallets(block);
|
PrintWallets(block);
|
||||||
|
|
||||||
// put the main time-chain first
|
// put the main time-chain first
|
||||||
vector<CBlockIndex*>& vNext = mapNext[pindex];
|
std::vector<CBlockIndex*>& vNext = mapNext[pindex];
|
||||||
for (unsigned int i = 0; i < vNext.size(); i++)
|
for (unsigned int i = 0; i < vNext.size(); i++)
|
||||||
{
|
{
|
||||||
if (vNext[i]->pnext)
|
if (vNext[i]->pnext)
|
||||||
{
|
{
|
||||||
swap(vNext[0], vNext[i]);
|
std::swap(vNext[0], vNext[i]);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// iterate children
|
// iterate children
|
||||||
for (unsigned int i = 0; i < vNext.size(); i++)
|
for (unsigned int i = 0; i < vNext.size(); i++)
|
||||||
vStack.push_back(make_pair(nCol+i, vNext[i]));
|
vStack.push_back(std::make_pair(nCol+i, vNext[i]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2835,10 +2841,10 @@ bool LoadExternalBlockFile(FILE* fileIn)
|
|||||||
nPos = (unsigned int)-1;
|
nPos = (unsigned int)-1;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
|
void* nFind = std::memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
|
||||||
if (nFind)
|
if (nFind)
|
||||||
{
|
{
|
||||||
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
|
if (std::memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
|
||||||
{
|
{
|
||||||
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
|
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
|
||||||
break;
|
break;
|
||||||
@ -2870,7 +2876,7 @@ bool LoadExternalBlockFile(FILE* fileIn)
|
|||||||
__PRETTY_FUNCTION__);
|
__PRETTY_FUNCTION__);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
|
printf("Loaded %i blocks from external file in %" PRI64d "ms\n", nLoaded, GetTimeMillis() - nStart);
|
||||||
return nLoaded > 0;
|
return nLoaded > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2887,17 +2893,17 @@ bool LoadExternalBlockFile(FILE* fileIn)
|
|||||||
// CAlert
|
// CAlert
|
||||||
//
|
//
|
||||||
|
|
||||||
extern map<uint256, CAlert> mapAlerts;
|
extern std::map<uint256, CAlert> mapAlerts;
|
||||||
extern CCriticalSection cs_mapAlerts;
|
extern CCriticalSection cs_mapAlerts;
|
||||||
|
|
||||||
static string strMintMessage = "Click 'Settings' then 'Unlock Wallet' to stake.";
|
static std::string strMintMessage = "Click 'Settings' then 'Unlock Wallet' to stake.";
|
||||||
static string strMintWarning;
|
static std::string strMintWarning;
|
||||||
|
|
||||||
string GetWarnings(string strFor)
|
std::string GetWarnings(std::string strFor)
|
||||||
{
|
{
|
||||||
int nPriority = 0;
|
int nPriority = 0;
|
||||||
string strStatusBar;
|
std::string strStatusBar;
|
||||||
string strRPC;
|
std::string strRPC;
|
||||||
|
|
||||||
if (GetBoolArg("-testsafemode"))
|
if (GetBoolArg("-testsafemode"))
|
||||||
strRPC = "test";
|
strRPC = "test";
|
||||||
@ -3000,12 +3006,12 @@ bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
|
|||||||
// a large 4-byte int at any alignment.
|
// a large 4-byte int at any alignment.
|
||||||
unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
|
unsigned char pchMessageStart[4] = { 0xe4, 0xe8, 0xe9, 0xe5 };
|
||||||
|
|
||||||
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
bool static ProcessMessage(CNode* pfrom, std::string strCommand, CDataStream& vRecv)
|
||||||
{
|
{
|
||||||
static map<CService, CPubKey> mapReuseKey;
|
static std::map<CService, CPubKey> mapReuseKey;
|
||||||
RandAddSeedPerfmon();
|
RandAddSeedPerfmon();
|
||||||
if (fDebug)
|
if (fDebug)
|
||||||
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
|
printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
|
||||||
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
|
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
|
||||||
{
|
{
|
||||||
printf("dropmessagestest DROPPING RECV MESSAGE\n");
|
printf("dropmessagestest DROPPING RECV MESSAGE\n");
|
||||||
@ -3076,7 +3082,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
|
|
||||||
// Change version
|
// Change version
|
||||||
pfrom->PushMessage("verack");
|
pfrom->PushMessage("verack");
|
||||||
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
|
pfrom->vSend.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
|
||||||
|
|
||||||
if (!pfrom->fInbound)
|
if (!pfrom->fInbound)
|
||||||
{
|
{
|
||||||
@ -3151,13 +3157,13 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
|
|
||||||
else if (strCommand == "verack")
|
else if (strCommand == "verack")
|
||||||
{
|
{
|
||||||
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
|
pfrom->vRecv.SetVersion(std::min(pfrom->nVersion, PROTOCOL_VERSION));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
else if (strCommand == "addr")
|
else if (strCommand == "addr")
|
||||||
{
|
{
|
||||||
vector<CAddress> vAddr;
|
std::vector<CAddress> vAddr;
|
||||||
vRecv >> vAddr;
|
vRecv >> vAddr;
|
||||||
|
|
||||||
// Don't want addr from older versions unless seeding
|
// Don't want addr from older versions unless seeding
|
||||||
@ -3166,11 +3172,11 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
if (vAddr.size() > 1000)
|
if (vAddr.size() > 1000)
|
||||||
{
|
{
|
||||||
pfrom->Misbehaving(20);
|
pfrom->Misbehaving(20);
|
||||||
return error("message addr size() = %"PRIszu"", vAddr.size());
|
return error("message addr size() = %" PRIszu "", vAddr.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store the new addresses
|
// Store the new addresses
|
||||||
vector<CAddress> vAddrOk;
|
std::vector<CAddress> vAddrOk;
|
||||||
int64 nNow = GetAdjustedTime();
|
int64 nNow = GetAdjustedTime();
|
||||||
int64 nSince = nNow - 10 * 60;
|
int64 nSince = nNow - 10 * 60;
|
||||||
BOOST_FOREACH(CAddress& addr, vAddr)
|
BOOST_FOREACH(CAddress& addr, vAddr)
|
||||||
@ -3194,19 +3200,19 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
uint64 hashAddr = addr.GetHash();
|
uint64 hashAddr = addr.GetHash();
|
||||||
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
|
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
|
||||||
hashRand = Hash(BEGIN(hashRand), END(hashRand));
|
hashRand = Hash(BEGIN(hashRand), END(hashRand));
|
||||||
multimap<uint256, CNode*> mapMix;
|
std::multimap<uint256, CNode*> mapMix;
|
||||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||||
{
|
{
|
||||||
if (pnode->nVersion < CADDR_TIME_VERSION)
|
if (pnode->nVersion < CADDR_TIME_VERSION)
|
||||||
continue;
|
continue;
|
||||||
unsigned int nPointer;
|
unsigned int nPointer;
|
||||||
memcpy(&nPointer, &pnode, sizeof(nPointer));
|
std::memcpy(&nPointer, &pnode, sizeof(nPointer));
|
||||||
uint256 hashKey = hashRand ^ nPointer;
|
uint256 hashKey = hashRand ^ nPointer;
|
||||||
hashKey = Hash(BEGIN(hashKey), END(hashKey));
|
hashKey = Hash(BEGIN(hashKey), END(hashKey));
|
||||||
mapMix.insert(make_pair(hashKey, pnode));
|
mapMix.insert(std::make_pair(hashKey, pnode));
|
||||||
}
|
}
|
||||||
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
|
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
|
||||||
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
|
for (std::multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
|
||||||
((*mi).second)->PushAddress(addr);
|
((*mi).second)->PushAddress(addr);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -3224,12 +3230,12 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
|
|
||||||
else if (strCommand == "inv")
|
else if (strCommand == "inv")
|
||||||
{
|
{
|
||||||
vector<CInv> vInv;
|
std::vector<CInv> vInv;
|
||||||
vRecv >> vInv;
|
vRecv >> vInv;
|
||||||
if (vInv.size() > MAX_INV_SZ)
|
if (vInv.size() > MAX_INV_SZ)
|
||||||
{
|
{
|
||||||
pfrom->Misbehaving(20);
|
pfrom->Misbehaving(20);
|
||||||
return error("message inv size() = %"PRIszu"", vInv.size());
|
return error("message inv size() = %" PRIszu "", vInv.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
// find last block in inv vector
|
// find last block in inv vector
|
||||||
@ -3274,16 +3280,16 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
|
|
||||||
else if (strCommand == "getdata")
|
else if (strCommand == "getdata")
|
||||||
{
|
{
|
||||||
vector<CInv> vInv;
|
std::vector<CInv> vInv;
|
||||||
vRecv >> vInv;
|
vRecv >> vInv;
|
||||||
if (vInv.size() > MAX_INV_SZ)
|
if (vInv.size() > MAX_INV_SZ)
|
||||||
{
|
{
|
||||||
pfrom->Misbehaving(20);
|
pfrom->Misbehaving(20);
|
||||||
return error("message getdata size() = %"PRIszu"", vInv.size());
|
return error("message getdata size() = %" PRIszu "", vInv.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fDebugNet || (vInv.size() != 1))
|
if (fDebugNet || (vInv.size() != 1))
|
||||||
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
|
printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
|
||||||
|
|
||||||
BOOST_FOREACH(const CInv& inv, vInv)
|
BOOST_FOREACH(const CInv& inv, vInv)
|
||||||
{
|
{
|
||||||
@ -3295,7 +3301,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
if (inv.type == MSG_BLOCK)
|
if (inv.type == MSG_BLOCK)
|
||||||
{
|
{
|
||||||
// Send block from disk
|
// Send block from disk
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
|
||||||
if (mi != mapBlockIndex.end())
|
if (mi != mapBlockIndex.end())
|
||||||
{
|
{
|
||||||
CBlock block;
|
CBlock block;
|
||||||
@ -3309,7 +3315,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
// download node to accept as orphan (proof-of-stake
|
// download node to accept as orphan (proof-of-stake
|
||||||
// block might be rejected by stake connection check)
|
// block might be rejected by stake connection check)
|
||||||
// peershares: send latest block
|
// peershares: send latest block
|
||||||
vector<CInv> vInv;
|
std::vector<CInv> vInv;
|
||||||
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
|
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
|
||||||
pfrom->PushMessage("inv", vInv);
|
pfrom->PushMessage("inv", vInv);
|
||||||
pfrom->hashContinue = 0;
|
pfrom->hashContinue = 0;
|
||||||
@ -3322,7 +3328,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
bool pushed = false;
|
bool pushed = false;
|
||||||
{
|
{
|
||||||
LOCK(cs_mapRelay);
|
LOCK(cs_mapRelay);
|
||||||
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
|
std::map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
|
||||||
if (mi != mapRelay.end()) {
|
if (mi != mapRelay.end()) {
|
||||||
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
|
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
|
||||||
pushed = true;
|
pushed = true;
|
||||||
@ -3408,7 +3414,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
if (locator.IsNull())
|
if (locator.IsNull())
|
||||||
{
|
{
|
||||||
// If locator is null, return the hashStop block
|
// If locator is null, return the hashStop block
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
|
||||||
if (mi == mapBlockIndex.end())
|
if (mi == mapBlockIndex.end())
|
||||||
return true;
|
return true;
|
||||||
pindex = (*mi).second;
|
pindex = (*mi).second;
|
||||||
@ -3421,7 +3427,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
pindex = pindex->pnext;
|
pindex = pindex->pnext;
|
||||||
}
|
}
|
||||||
|
|
||||||
vector<CBlock> vHeaders;
|
std::vector<CBlock> vHeaders;
|
||||||
int nLimit = 2000;
|
int nLimit = 2000;
|
||||||
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
|
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
|
||||||
for (; pindex; pindex = pindex->pnext)
|
for (; pindex; pindex = pindex->pnext)
|
||||||
@ -3436,8 +3442,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
|
|
||||||
else if (strCommand == "tx")
|
else if (strCommand == "tx")
|
||||||
{
|
{
|
||||||
vector<uint256> vWorkQueue;
|
std::vector<uint256> vWorkQueue;
|
||||||
vector<uint256> vEraseQueue;
|
std::vector<uint256> vEraseQueue;
|
||||||
CDataStream vMsg(vRecv);
|
CDataStream vMsg(vRecv);
|
||||||
CTxDB txdb("r");
|
CTxDB txdb("r");
|
||||||
CTransaction tx;
|
CTransaction tx;
|
||||||
@ -3459,7 +3465,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
||||||
{
|
{
|
||||||
uint256 hashPrev = vWorkQueue[i];
|
uint256 hashPrev = vWorkQueue[i];
|
||||||
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
|
for (std::map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
|
||||||
mi != mapOrphanTransactionsByPrev[hashPrev].end();
|
mi != mapOrphanTransactionsByPrev[hashPrev].end();
|
||||||
++mi)
|
++mi)
|
||||||
{
|
{
|
||||||
@ -3526,7 +3532,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
else if (strCommand == "getaddr")
|
else if (strCommand == "getaddr")
|
||||||
{
|
{
|
||||||
pfrom->vAddrToSend.clear();
|
pfrom->vAddrToSend.clear();
|
||||||
vector<CAddress> vAddr = addrman.GetAddr();
|
std::vector<CAddress> vAddr = addrman.GetAddr();
|
||||||
BOOST_FOREACH(const CAddress &addr, vAddr)
|
BOOST_FOREACH(const CAddress &addr, vAddr)
|
||||||
pfrom->PushAddress(addr);
|
pfrom->PushAddress(addr);
|
||||||
}
|
}
|
||||||
@ -3536,7 +3542,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
{
|
{
|
||||||
std::vector<uint256> vtxid;
|
std::vector<uint256> vtxid;
|
||||||
mempool.queryHashes(vtxid);
|
mempool.queryHashes(vtxid);
|
||||||
vector<CInv> vInv;
|
std::vector<CInv> vInv;
|
||||||
for (unsigned int i = 0; i < vtxid.size(); i++) {
|
for (unsigned int i = 0; i < vtxid.size(); i++) {
|
||||||
CInv inv(MSG_TX, vtxid[i]);
|
CInv inv(MSG_TX, vtxid[i]);
|
||||||
vInv.push_back(inv);
|
vInv.push_back(inv);
|
||||||
@ -3555,7 +3561,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
|
|
||||||
if (!GetBoolArg("-allowreceivebyip"))
|
if (!GetBoolArg("-allowreceivebyip"))
|
||||||
{
|
{
|
||||||
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
|
pfrom->PushMessage("reply", hashReply, (int)2, std::string(""));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -3583,7 +3589,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
|
|||||||
CRequestTracker tracker;
|
CRequestTracker tracker;
|
||||||
{
|
{
|
||||||
LOCK(pfrom->cs_mapRequests);
|
LOCK(pfrom->cs_mapRequests);
|
||||||
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
|
std::map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
|
||||||
if (mi != pfrom->mapRequests.end())
|
if (mi != pfrom->mapRequests.end())
|
||||||
{
|
{
|
||||||
tracker = (*mi).second;
|
tracker = (*mi).second;
|
||||||
@ -3699,11 +3705,11 @@ bool ProcessMessages(CNode* pfrom)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (pstart - vRecv.begin() > 0)
|
if (pstart - vRecv.begin() > 0)
|
||||||
printf("\n\nPROCESSMESSAGE SKIPPED %"PRIpdd" BYTES\n\n", pstart - vRecv.begin());
|
printf("\n\nPROCESSMESSAGE SKIPPED %" PRIpdd " BYTES\n\n", pstart - vRecv.begin());
|
||||||
vRecv.erase(vRecv.begin(), pstart);
|
vRecv.erase(vRecv.begin(), pstart);
|
||||||
|
|
||||||
// Read header
|
// Read header
|
||||||
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
|
std::vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
|
||||||
CMessageHeader hdr;
|
CMessageHeader hdr;
|
||||||
vRecv >> hdr;
|
vRecv >> hdr;
|
||||||
if (!hdr.IsValid())
|
if (!hdr.IsValid())
|
||||||
@ -3711,7 +3717,7 @@ bool ProcessMessages(CNode* pfrom)
|
|||||||
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
|
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
string strCommand = hdr.GetCommand();
|
std::string strCommand = hdr.GetCommand();
|
||||||
|
|
||||||
// Message size
|
// Message size
|
||||||
unsigned int nMessageSize = hdr.nMessageSize;
|
unsigned int nMessageSize = hdr.nMessageSize;
|
||||||
@ -3730,7 +3736,7 @@ bool ProcessMessages(CNode* pfrom)
|
|||||||
// Checksum
|
// Checksum
|
||||||
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
|
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
|
||||||
unsigned int nChecksum = 0;
|
unsigned int nChecksum = 0;
|
||||||
memcpy(&nChecksum, &hash, sizeof(nChecksum));
|
std::memcpy(&nChecksum, &hash, sizeof(nChecksum));
|
||||||
if (nChecksum != hdr.nChecksum)
|
if (nChecksum != hdr.nChecksum)
|
||||||
{
|
{
|
||||||
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
|
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
|
||||||
@ -3835,7 +3841,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
|
|||||||
//
|
//
|
||||||
if (fSendTrickle)
|
if (fSendTrickle)
|
||||||
{
|
{
|
||||||
vector<CAddress> vAddr;
|
std::vector<CAddress> vAddr;
|
||||||
vAddr.reserve(pto->vAddrToSend.size());
|
vAddr.reserve(pto->vAddrToSend.size());
|
||||||
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
|
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
|
||||||
{
|
{
|
||||||
@ -3860,8 +3866,8 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
|
|||||||
//
|
//
|
||||||
// Message: inventory
|
// Message: inventory
|
||||||
//
|
//
|
||||||
vector<CInv> vInv;
|
std::vector<CInv> vInv;
|
||||||
vector<CInv> vInvWait;
|
std::vector<CInv> vInvWait;
|
||||||
{
|
{
|
||||||
LOCK(pto->cs_inventory);
|
LOCK(pto->cs_inventory);
|
||||||
vInv.reserve(pto->vInventoryToSend.size());
|
vInv.reserve(pto->vInventoryToSend.size());
|
||||||
@ -3918,7 +3924,7 @@ bool SendMessages(CNode* pto, bool fSendTrickle)
|
|||||||
//
|
//
|
||||||
// Message: getdata
|
// Message: getdata
|
||||||
//
|
//
|
||||||
vector<CInv> vGetData;
|
std::vector<CInv> vGetData;
|
||||||
int64 nNow = GetTime() * 1000000;
|
int64 nNow = GetTime() * 1000000;
|
||||||
CTxDB txdb("r");
|
CTxDB txdb("r");
|
||||||
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
|
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
|
||||||
@ -3968,7 +3974,7 @@ int static FormatHashBlocks(void* pbuffer, unsigned int len)
|
|||||||
unsigned char* pdata = (unsigned char*)pbuffer;
|
unsigned char* pdata = (unsigned char*)pbuffer;
|
||||||
unsigned int blocks = 1 + ((len + 8) / 64);
|
unsigned int blocks = 1 + ((len + 8) / 64);
|
||||||
unsigned char* pend = pdata + 64 * blocks;
|
unsigned char* pend = pdata + 64 * blocks;
|
||||||
memset(pdata + len, 0, 64 * blocks - len);
|
std::memset(pdata + len, 0, 64 * blocks - len);
|
||||||
pdata[len] = 0x80;
|
pdata[len] = 0x80;
|
||||||
unsigned int bits = len * 8;
|
unsigned int bits = len * 8;
|
||||||
pend[-1] = (bits >> 0) & 0xff;
|
pend[-1] = (bits >> 0) & 0xff;
|
||||||
@ -4037,7 +4043,7 @@ class COrphan
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
CTransaction* ptx;
|
CTransaction* ptx;
|
||||||
set<uint256> setDependsOn;
|
std::set<uint256> setDependsOn;
|
||||||
double dPriority;
|
double dPriority;
|
||||||
double dFeePerKb;
|
double dFeePerKb;
|
||||||
|
|
||||||
@ -4092,7 +4098,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
CReserveKey reservekey(pwallet);
|
CReserveKey reservekey(pwallet);
|
||||||
|
|
||||||
// Create new block
|
// Create new block
|
||||||
auto_ptr<CBlock> pblock(new CBlock());
|
std::unique_ptr<CBlock> pblock(new CBlock());
|
||||||
if (!pblock.get())
|
if (!pblock.get())
|
||||||
return NULL;
|
return NULL;
|
||||||
|
|
||||||
@ -4143,7 +4149,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
{
|
{
|
||||||
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
|
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake))
|
||||||
{
|
{
|
||||||
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
|
if (txCoinStake.nTime >= std::max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
|
||||||
{ // make sure coinstake would meet timestamp protocol
|
{ // make sure coinstake would meet timestamp protocol
|
||||||
// as it would be the same as the block timestamp
|
// as it would be the same as the block timestamp
|
||||||
pblock->vtx[0].vout[0].SetEmpty();
|
pblock->vtx[0].vout[0].SetEmpty();
|
||||||
@ -4166,13 +4172,13 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
CTxDB txdb("r");
|
CTxDB txdb("r");
|
||||||
|
|
||||||
// Priority order to process transactions
|
// Priority order to process transactions
|
||||||
list<COrphan> vOrphan; // list memory doesn't move
|
std::list<COrphan> vOrphan; // list memory doesn't move
|
||||||
map<uint256, vector<COrphan*> > mapDependers;
|
std::map<uint256, std::vector<COrphan*> > mapDependers;
|
||||||
|
|
||||||
// This vector will be sorted into a priority queue:
|
// This vector will be sorted into a priority queue:
|
||||||
vector<TxPriority> vecPriority;
|
std::vector<TxPriority> vecPriority;
|
||||||
vecPriority.reserve(mempool.mapTx.size());
|
vecPriority.reserve(mempool.mapTx.size());
|
||||||
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
|
for (std::map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
|
||||||
{
|
{
|
||||||
CTransaction& tx = (*mi).second;
|
CTransaction& tx = (*mi).second;
|
||||||
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
|
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
|
||||||
@ -4241,7 +4247,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Collect transactions into block
|
// Collect transactions into block
|
||||||
map<uint256, CTxIndex> mapTestPool;
|
std::map<uint256, CTxIndex> mapTestPool;
|
||||||
uint64 nBlockSize = 1000;
|
uint64 nBlockSize = 1000;
|
||||||
uint64 nBlockTx = 0;
|
uint64 nBlockTx = 0;
|
||||||
int nBlockSigOps = 100;
|
int nBlockSigOps = 100;
|
||||||
@ -4293,7 +4299,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
|
|
||||||
// Connecting shouldn't fail due to dependency on other memory pool transactions
|
// Connecting shouldn't fail due to dependency on other memory pool transactions
|
||||||
// because we're already processing them in order of dependency
|
// because we're already processing them in order of dependency
|
||||||
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
|
std::map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
|
||||||
MapPrevTx mapInputs;
|
MapPrevTx mapInputs;
|
||||||
bool fInvalid;
|
bool fInvalid;
|
||||||
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
|
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
|
||||||
@ -4310,7 +4316,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
|
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
|
||||||
continue;
|
continue;
|
||||||
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
|
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
|
||||||
swap(mapTestPool, mapTestPoolTmp);
|
std::swap(mapTestPool, mapTestPoolTmp);
|
||||||
|
|
||||||
// Added
|
// Added
|
||||||
pblock->vtx.push_back(tx);
|
pblock->vtx.push_back(tx);
|
||||||
@ -4348,7 +4354,7 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
nLastBlockSize = nBlockSize;
|
nLastBlockSize = nBlockSize;
|
||||||
|
|
||||||
if (fDebug && GetBoolArg("-printpriority"))
|
if (fDebug && GetBoolArg("-printpriority"))
|
||||||
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
|
printf("CreateNewBlock(): total size %" PRI64u "\n", nBlockSize);
|
||||||
|
|
||||||
if (pblock->IsProofOfWork())
|
if (pblock->IsProofOfWork())
|
||||||
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash());
|
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(pindexPrev->nHeight+1, nFees, pindexPrev->GetBlockHash());
|
||||||
@ -4358,8 +4364,8 @@ CBlock* CreateNewBlock(CWallet* pwallet, bool fProofOfStake)
|
|||||||
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
|
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
|
||||||
if (pblock->IsProofOfStake())
|
if (pblock->IsProofOfStake())
|
||||||
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
|
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
|
||||||
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
|
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
|
||||||
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
|
pblock->nTime = std::max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
|
||||||
if (pblock->IsProofOfWork())
|
if (pblock->IsProofOfWork())
|
||||||
pblock->UpdateTime(pindexPrev);
|
pblock->UpdateTime(pindexPrev);
|
||||||
pblock->nNonce = 0;
|
pblock->nNonce = 0;
|
||||||
@ -4409,7 +4415,7 @@ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash
|
|||||||
unsigned char pchPadding1[64];
|
unsigned char pchPadding1[64];
|
||||||
}
|
}
|
||||||
tmp;
|
tmp;
|
||||||
memset(&tmp, 0, sizeof(tmp));
|
std::memset(&tmp, 0, sizeof(tmp));
|
||||||
|
|
||||||
tmp.block.nVersion = pblock->nVersion;
|
tmp.block.nVersion = pblock->nVersion;
|
||||||
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
|
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
|
||||||
@ -4428,8 +4434,8 @@ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash
|
|||||||
// Precalc the first half of the first hash, which stays constant
|
// Precalc the first half of the first hash, which stays constant
|
||||||
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
|
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
|
||||||
|
|
||||||
memcpy(pdata, &tmp.block, 128);
|
std::memcpy(pdata, &tmp.block, 128);
|
||||||
memcpy(phash1, &tmp.hash1, 64);
|
std::memcpy(phash1, &tmp.hash1, 64);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -4514,7 +4520,7 @@ void curecoinMiner(CWallet *pwallet, bool fProofOfStake)
|
|||||||
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
|
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
|
||||||
CBlockIndex* pindexPrev = pindexBest;
|
CBlockIndex* pindexPrev = pindexBest;
|
||||||
|
|
||||||
auto_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
|
std::unique_ptr<CBlock> pblock(CreateNewBlock(pwallet, fProofOfStake));
|
||||||
if (!pblock.get())
|
if (!pblock.get())
|
||||||
return;
|
return;
|
||||||
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
|
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
|
||||||
@ -4539,7 +4545,7 @@ void curecoinMiner(CWallet *pwallet, bool fProofOfStake)
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
printf("Running curecoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
|
printf("Running curecoinMiner with %" PRIszu " transactions in block (%u bytes)\n", pblock->vtx.size(),
|
||||||
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
|
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
|
||||||
|
|
||||||
//
|
//
|
||||||
@ -4636,8 +4642,8 @@ void curecoinMiner(CWallet *pwallet, bool fProofOfStake)
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
// Update nTime every few seconds
|
// Update nTime every few seconds
|
||||||
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
|
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
|
||||||
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
|
pblock->nTime = std::max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
|
||||||
pblock->UpdateTime(pindexPrev);
|
pblock->UpdateTime(pindexPrev);
|
||||||
nBlockTime = ByteReverse(pblock->nTime);
|
nBlockTime = ByteReverse(pblock->nTime);
|
||||||
|
|
||||||
|
@ -649,7 +649,7 @@ public:
|
|||||||
{
|
{
|
||||||
std::string str;
|
std::string str;
|
||||||
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
|
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
|
||||||
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d, strTxComment=%s)\n",
|
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%" PRIszu", vout.size=%" PRIszu", nLockTime=%d, strTxComment=%s)\n",
|
||||||
GetHash().ToString().substr(0,10).c_str(),
|
GetHash().ToString().substr(0,10).c_str(),
|
||||||
nTime,
|
nTime,
|
||||||
nVersion,
|
nVersion,
|
||||||
@ -939,7 +939,7 @@ public:
|
|||||||
printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
|
printf("GetStakeEntropyBit: hashSig=%s", hashSig.ToString().c_str());
|
||||||
hashSig >>= 159; // take the first bit of the hash
|
hashSig >>= 159; // take the first bit of the hash
|
||||||
if (fDebug && GetBoolArg("-printstakemodifier"))
|
if (fDebug && GetBoolArg("-printstakemodifier"))
|
||||||
printf(" entropybit=%"PRI64d"\n", hashSig.Get64());
|
printf(" entropybit=%" PRI64d "\n", hashSig.Get64());
|
||||||
return hashSig.Get64();
|
return hashSig.Get64();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1075,7 +1075,7 @@ public:
|
|||||||
|
|
||||||
void print() const
|
void print() const
|
||||||
{
|
{
|
||||||
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
|
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ", vchBlockSig=%s)\n",
|
||||||
GetHash().ToString().c_str(),
|
GetHash().ToString().c_str(),
|
||||||
nVersion,
|
nVersion,
|
||||||
hashPrevBlock.ToString().c_str(),
|
hashPrevBlock.ToString().c_str(),
|
||||||
@ -1338,7 +1338,7 @@ public:
|
|||||||
|
|
||||||
std::string ToString() const
|
std::string ToString() const
|
||||||
{
|
{
|
||||||
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRI64x", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
|
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016" PRI64x ", nStakeModifierChecksum=%08x, hashProofOfStake=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
|
||||||
pprev, pnext, nFile, nBlockPos, nHeight,
|
pprev, pnext, nFile, nBlockPos, nHeight,
|
||||||
FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
|
FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
|
||||||
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
|
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
|
||||||
|
93
src/net.cpp
93
src/net.cpp
@ -11,6 +11,15 @@
|
|||||||
#include "addrman.h"
|
#include "addrman.h"
|
||||||
#include "ui_interface.h"
|
#include "ui_interface.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <deque>
|
||||||
|
#include <list>
|
||||||
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#ifdef WIN32
|
#ifdef WIN32
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#endif
|
#endif
|
||||||
@ -22,8 +31,6 @@
|
|||||||
#include <miniupnpc/upnperrors.h>
|
#include <miniupnpc/upnperrors.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
using namespace boost;
|
|
||||||
|
|
||||||
static const int MAX_OUTBOUND_CONNECTIONS = 24;
|
static const int MAX_OUTBOUND_CONNECTIONS = 24;
|
||||||
|
|
||||||
@ -51,7 +58,7 @@ bool fDiscover = true;
|
|||||||
bool fUseUPnP = false;
|
bool fUseUPnP = false;
|
||||||
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
|
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
|
||||||
static CCriticalSection cs_mapLocalHost;
|
static CCriticalSection cs_mapLocalHost;
|
||||||
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
|
static std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
|
||||||
static bool vfReachable[NET_MAX] = {};
|
static bool vfReachable[NET_MAX] = {};
|
||||||
static bool vfLimited[NET_MAX] = {};
|
static bool vfLimited[NET_MAX] = {};
|
||||||
static CNode* pnodeLocalHost = NULL;
|
static CNode* pnodeLocalHost = NULL;
|
||||||
@ -61,22 +68,22 @@ boost::array<int, THREAD_MAX> vnThreadsRunning;
|
|||||||
static std::vector<SOCKET> vhListenSocket;
|
static std::vector<SOCKET> vhListenSocket;
|
||||||
CAddrMan addrman;
|
CAddrMan addrman;
|
||||||
|
|
||||||
vector<CNode*> vNodes;
|
std::vector<CNode*> vNodes;
|
||||||
CCriticalSection cs_vNodes;
|
CCriticalSection cs_vNodes;
|
||||||
map<CInv, CDataStream> mapRelay;
|
std::map<CInv, CDataStream> mapRelay;
|
||||||
deque<pair<int64, CInv> > vRelayExpiration;
|
std::deque<std::pair<int64, CInv> > vRelayExpiration;
|
||||||
CCriticalSection cs_mapRelay;
|
CCriticalSection cs_mapRelay;
|
||||||
map<CInv, int64> mapAlreadyAskedFor;
|
std::map<CInv, int64> mapAlreadyAskedFor;
|
||||||
|
|
||||||
static deque<string> vOneShots;
|
static std::deque<std::string> vOneShots;
|
||||||
CCriticalSection cs_vOneShots;
|
CCriticalSection cs_vOneShots;
|
||||||
|
|
||||||
set<CNetAddr> setservAddNodeAddresses;
|
std::set<CNetAddr> setservAddNodeAddresses;
|
||||||
CCriticalSection cs_setservAddNodeAddresses;
|
CCriticalSection cs_setservAddNodeAddresses;
|
||||||
|
|
||||||
static CSemaphore *semOutbound = NULL;
|
static CSemaphore *semOutbound = NULL;
|
||||||
|
|
||||||
void AddOneShot(string strDest)
|
void AddOneShot(std::string strDest)
|
||||||
{
|
{
|
||||||
LOCK(cs_vOneShots);
|
LOCK(cs_vOneShots);
|
||||||
vOneShots.push_back(strDest);
|
vOneShots.push_back(strDest);
|
||||||
@ -108,7 +115,7 @@ bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
|
|||||||
int nBestReachability = -1;
|
int nBestReachability = -1;
|
||||||
{
|
{
|
||||||
LOCK(cs_mapLocalHost);
|
LOCK(cs_mapLocalHost);
|
||||||
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
|
for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
|
||||||
{
|
{
|
||||||
int nScore = (*it).second.nScore;
|
int nScore = (*it).second.nScore;
|
||||||
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
|
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
|
||||||
@ -137,7 +144,7 @@ CAddress GetLocalAddress(const CNetAddr *paddrPeer)
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool RecvLine(SOCKET hSocket, string& strLine)
|
bool RecvLine(SOCKET hSocket, std::string& strLine)
|
||||||
{
|
{
|
||||||
strLine = "";
|
strLine = "";
|
||||||
while (true)
|
while (true)
|
||||||
@ -308,7 +315,7 @@ bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const cha
|
|||||||
|
|
||||||
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
|
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
|
||||||
|
|
||||||
string strLine;
|
std::string strLine;
|
||||||
while (RecvLine(hSocket, strLine))
|
while (RecvLine(hSocket, strLine))
|
||||||
{
|
{
|
||||||
if (strLine.empty()) // HTTP response is separated from headers by blank line
|
if (strLine.empty()) // HTTP response is separated from headers by blank line
|
||||||
@ -322,14 +329,14 @@ bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const cha
|
|||||||
}
|
}
|
||||||
if (pszKeyword == NULL)
|
if (pszKeyword == NULL)
|
||||||
break;
|
break;
|
||||||
if (strLine.find(pszKeyword) != string::npos)
|
if (strLine.find(pszKeyword) != std::string::npos)
|
||||||
{
|
{
|
||||||
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
|
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
closesocket(hSocket);
|
closesocket(hSocket);
|
||||||
if (strLine.find("<") != string::npos)
|
if (strLine.find("<") != std::string::npos)
|
||||||
strLine = strLine.substr(0, strLine.find("<"));
|
strLine = strLine.substr(0, strLine.find("<"));
|
||||||
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
|
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
|
||||||
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
|
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
|
||||||
@ -555,7 +562,7 @@ void CNode::PushVersion()
|
|||||||
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
|
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
|
||||||
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
|
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
|
||||||
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
|
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
|
||||||
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
|
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()), nBestHeight);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -662,7 +669,7 @@ void ThreadSocketHandler(void* parg)
|
|||||||
void ThreadSocketHandler2(void* parg)
|
void ThreadSocketHandler2(void* parg)
|
||||||
{
|
{
|
||||||
printf("ThreadSocketHandler started\n");
|
printf("ThreadSocketHandler started\n");
|
||||||
list<CNode*> vNodesDisconnected;
|
std::list<CNode*> vNodesDisconnected;
|
||||||
unsigned int nPrevNodeCount = 0;
|
unsigned int nPrevNodeCount = 0;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
@ -673,7 +680,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
{
|
{
|
||||||
LOCK(cs_vNodes);
|
LOCK(cs_vNodes);
|
||||||
// Disconnect unused nodes
|
// Disconnect unused nodes
|
||||||
vector<CNode*> vNodesCopy = vNodes;
|
std::vector<CNode*> vNodesCopy = vNodes;
|
||||||
BOOST_FOREACH(CNode* pnode, vNodesCopy)
|
BOOST_FOREACH(CNode* pnode, vNodesCopy)
|
||||||
{
|
{
|
||||||
if (pnode->fDisconnect ||
|
if (pnode->fDisconnect ||
|
||||||
@ -690,7 +697,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
pnode->Cleanup();
|
pnode->Cleanup();
|
||||||
|
|
||||||
// hold in disconnected pool until all refs are released
|
// hold in disconnected pool until all refs are released
|
||||||
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
|
pnode->nReleaseTime = std::max(pnode->nReleaseTime, GetTime() + 15 * 60);
|
||||||
if (pnode->fNetworkNode || pnode->fInbound)
|
if (pnode->fNetworkNode || pnode->fInbound)
|
||||||
pnode->Release();
|
pnode->Release();
|
||||||
vNodesDisconnected.push_back(pnode);
|
vNodesDisconnected.push_back(pnode);
|
||||||
@ -698,7 +705,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Delete disconnected nodes
|
// Delete disconnected nodes
|
||||||
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
|
std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
|
||||||
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
|
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
|
||||||
{
|
{
|
||||||
// wait until threads are done using it
|
// wait until threads are done using it
|
||||||
@ -755,7 +762,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
|
|
||||||
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
|
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
|
||||||
FD_SET(hListenSocket, &fdsetRecv);
|
FD_SET(hListenSocket, &fdsetRecv);
|
||||||
hSocketMax = max(hSocketMax, hListenSocket);
|
hSocketMax = std::max(hSocketMax, hListenSocket);
|
||||||
have_fds = true;
|
have_fds = true;
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
@ -766,7 +773,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
continue;
|
continue;
|
||||||
FD_SET(pnode->hSocket, &fdsetRecv);
|
FD_SET(pnode->hSocket, &fdsetRecv);
|
||||||
FD_SET(pnode->hSocket, &fdsetError);
|
FD_SET(pnode->hSocket, &fdsetError);
|
||||||
hSocketMax = max(hSocketMax, pnode->hSocket);
|
hSocketMax = std::max(hSocketMax, pnode->hSocket);
|
||||||
have_fds = true;
|
have_fds = true;
|
||||||
{
|
{
|
||||||
TRY_LOCK(pnode->cs_vSend, lockSend);
|
TRY_LOCK(pnode->cs_vSend, lockSend);
|
||||||
@ -859,7 +866,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
//
|
//
|
||||||
// Service each socket
|
// Service each socket
|
||||||
//
|
//
|
||||||
vector<CNode*> vNodesCopy;
|
std::vector<CNode*> vNodesCopy;
|
||||||
{
|
{
|
||||||
LOCK(cs_vNodes);
|
LOCK(cs_vNodes);
|
||||||
vNodesCopy = vNodes;
|
vNodesCopy = vNodes;
|
||||||
@ -886,7 +893,7 @@ void ThreadSocketHandler2(void* parg)
|
|||||||
|
|
||||||
if (nPos > ReceiveBufferSize()) {
|
if (nPos > ReceiveBufferSize()) {
|
||||||
if (!pnode->fDisconnect)
|
if (!pnode->fDisconnect)
|
||||||
printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
|
printf("socket recv flood control disconnect (%" PRIszu " bytes)\n", vRecv.size());
|
||||||
pnode->CloseSocketDisconnect();
|
pnode->CloseSocketDisconnect();
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@ -1065,7 +1072,7 @@ void ThreadMapPort2(void* parg)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
string strDesc = "curecoin " + FormatFullVersion();
|
std::string strDesc = "curecoin " + FormatFullVersion();
|
||||||
#if MINIUPNPC_API_VERSION >= 8
|
#if MINIUPNPC_API_VERSION >= 8
|
||||||
/* miniupnpc 1.6 */
|
/* miniupnpc 1.6 */
|
||||||
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
|
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
|
||||||
@ -1191,8 +1198,8 @@ void ThreadDNSAddressSeed2(void* parg)
|
|||||||
if (HaveNameProxy()) {
|
if (HaveNameProxy()) {
|
||||||
AddOneShot(strDNSSeed[seed_idx][1]);
|
AddOneShot(strDNSSeed[seed_idx][1]);
|
||||||
} else {
|
} else {
|
||||||
vector<CNetAddr> vaddr;
|
std::vector<CNetAddr> vaddr;
|
||||||
vector<CAddress> vAdd;
|
std::vector<CAddress> vAdd;
|
||||||
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
|
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
|
||||||
{
|
{
|
||||||
BOOST_FOREACH(CNetAddr& ip, vaddr)
|
BOOST_FOREACH(CNetAddr& ip, vaddr)
|
||||||
@ -1235,7 +1242,7 @@ void DumpAddresses()
|
|||||||
CAddrDB adb;
|
CAddrDB adb;
|
||||||
adb.Write(addrman);
|
adb.Write(addrman);
|
||||||
|
|
||||||
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
|
printf("Flushed %d addresses to peers.dat %" PRI64d "ms\n",
|
||||||
addrman.size(), GetTimeMillis() - nStart);
|
addrman.size(), GetTimeMillis() - nStart);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1290,7 +1297,7 @@ void ThreadOpenConnections(void* parg)
|
|||||||
|
|
||||||
void static ProcessOneShot()
|
void static ProcessOneShot()
|
||||||
{
|
{
|
||||||
string strDest;
|
std::string strDest;
|
||||||
{
|
{
|
||||||
LOCK(cs_vOneShots);
|
LOCK(cs_vOneShots);
|
||||||
if (vOneShots.empty())
|
if (vOneShots.empty())
|
||||||
@ -1337,7 +1344,7 @@ void ThreadOpenConnections2(void* parg)
|
|||||||
for (int64 nLoop = 0;; nLoop++)
|
for (int64 nLoop = 0;; nLoop++)
|
||||||
{
|
{
|
||||||
ProcessOneShot();
|
ProcessOneShot();
|
||||||
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
|
BOOST_FOREACH(std::string strAddr, mapMultiArgs["-connect"])
|
||||||
{
|
{
|
||||||
CAddress addr;
|
CAddress addr;
|
||||||
OpenNetworkConnection(addr, NULL, strAddr.c_str());
|
OpenNetworkConnection(addr, NULL, strAddr.c_str());
|
||||||
@ -1399,7 +1406,7 @@ void ThreadOpenConnections2(void* parg)
|
|||||||
// Only connect out to one peer per network group (/16 for IPv4).
|
// Only connect out to one peer per network group (/16 for IPv4).
|
||||||
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
|
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
|
||||||
int nOutbound = 0;
|
int nOutbound = 0;
|
||||||
set<vector<unsigned char> > setConnected;
|
std::set<std::vector<unsigned char> > setConnected;
|
||||||
{
|
{
|
||||||
LOCK(cs_vNodes);
|
LOCK(cs_vNodes);
|
||||||
BOOST_FOREACH(CNode* pnode, vNodes) {
|
BOOST_FOREACH(CNode* pnode, vNodes) {
|
||||||
@ -1416,7 +1423,7 @@ void ThreadOpenConnections2(void* parg)
|
|||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
|
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
|
||||||
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
|
CAddress addr = addrman.Select(10 + std::min(nOutbound,8)*10);
|
||||||
|
|
||||||
// if we selected an invalid address, restart
|
// if we selected an invalid address, restart
|
||||||
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
|
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
|
||||||
@ -1479,7 +1486,7 @@ void ThreadOpenAddedConnections2(void* parg)
|
|||||||
|
|
||||||
if (HaveNameProxy()) {
|
if (HaveNameProxy()) {
|
||||||
while(!fShutdown) {
|
while(!fShutdown) {
|
||||||
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
|
BOOST_FOREACH(std::string& strAddNode, mapMultiArgs["-addnode"]) {
|
||||||
CAddress addr;
|
CAddress addr;
|
||||||
CSemaphoreGrant grant(*semOutbound);
|
CSemaphoreGrant grant(*semOutbound);
|
||||||
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
|
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
|
||||||
@ -1492,10 +1499,10 @@ void ThreadOpenAddedConnections2(void* parg)
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
vector<vector<CService> > vservAddressesToAdd(0);
|
std::vector<std::vector<CService> > vservAddressesToAdd(0);
|
||||||
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
|
BOOST_FOREACH(std::string& strAddNode, mapMultiArgs["-addnode"])
|
||||||
{
|
{
|
||||||
vector<CService> vservNode(0);
|
std::vector<CService> vservNode(0);
|
||||||
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
|
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
|
||||||
{
|
{
|
||||||
vservAddressesToAdd.push_back(vservNode);
|
vservAddressesToAdd.push_back(vservNode);
|
||||||
@ -1508,13 +1515,13 @@ void ThreadOpenAddedConnections2(void* parg)
|
|||||||
}
|
}
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
|
std::vector<std::vector<CService> > vservConnectAddresses = vservAddressesToAdd;
|
||||||
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
|
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
|
||||||
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
|
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
|
||||||
{
|
{
|
||||||
LOCK(cs_vNodes);
|
LOCK(cs_vNodes);
|
||||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||||
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
|
for (std::vector<std::vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
|
||||||
BOOST_FOREACH(CService& addrNode, *(it))
|
BOOST_FOREACH(CService& addrNode, *(it))
|
||||||
if (pnode->addr == addrNode)
|
if (pnode->addr == addrNode)
|
||||||
{
|
{
|
||||||
@ -1523,7 +1530,7 @@ void ThreadOpenAddedConnections2(void* parg)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
|
BOOST_FOREACH(std::vector<CService>& vserv, vservConnectAddresses)
|
||||||
{
|
{
|
||||||
CSemaphoreGrant grant(*semOutbound);
|
CSemaphoreGrant grant(*semOutbound);
|
||||||
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
|
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
|
||||||
@ -1607,7 +1614,7 @@ void ThreadMessageHandler2(void* parg)
|
|||||||
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
|
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
|
||||||
while (!fShutdown)
|
while (!fShutdown)
|
||||||
{
|
{
|
||||||
vector<CNode*> vNodesCopy;
|
std::vector<CNode*> vNodesCopy;
|
||||||
{
|
{
|
||||||
LOCK(cs_vNodes);
|
LOCK(cs_vNodes);
|
||||||
vNodesCopy = vNodes;
|
vNodesCopy = vNodes;
|
||||||
@ -1664,7 +1671,7 @@ void ThreadMessageHandler2(void* parg)
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
bool BindListenPort(const CService &addrBind, string& strError)
|
bool BindListenPort(const CService &addrBind, std::string& strError)
|
||||||
{
|
{
|
||||||
strError = "";
|
strError = "";
|
||||||
int nOne = 1;
|
int nOne = 1;
|
||||||
@ -1781,7 +1788,7 @@ void static Discover()
|
|||||||
char pszHostName[1000] = "";
|
char pszHostName[1000] = "";
|
||||||
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
|
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
|
||||||
{
|
{
|
||||||
vector<CNetAddr> vaddr;
|
std::vector<CNetAddr> vaddr;
|
||||||
if (LookupHost(pszHostName, vaddr))
|
if (LookupHost(pszHostName, vaddr))
|
||||||
{
|
{
|
||||||
BOOST_FOREACH (const CNetAddr &addr, vaddr)
|
BOOST_FOREACH (const CNetAddr &addr, vaddr)
|
||||||
@ -1834,7 +1841,7 @@ void StartNode(void* parg)
|
|||||||
|
|
||||||
if (semOutbound == NULL) {
|
if (semOutbound == NULL) {
|
||||||
// initialize semaphore
|
// initialize semaphore
|
||||||
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
|
int nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
|
||||||
semOutbound = new CSemaphore(nMaxOutbound);
|
semOutbound = new CSemaphore(nMaxOutbound);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -320,7 +320,7 @@ public:
|
|||||||
// the key is the earliest time the request can be sent
|
// the key is the earliest time the request can be sent
|
||||||
int64& nRequestTime = mapAlreadyAskedFor[inv];
|
int64& nRequestTime = mapAlreadyAskedFor[inv];
|
||||||
if (fDebugNet)
|
if (fDebugNet)
|
||||||
printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
|
printf("askfor %s %" PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
|
||||||
|
|
||||||
// Make sure not to reuse time indexes to keep things in the same order
|
// Make sure not to reuse time indexes to keep things in the same order
|
||||||
int64 nNow = (GetTime() - 1) * 1000000;
|
int64 nNow = (GetTime() - 1) * 1000000;
|
||||||
|
@ -7,6 +7,11 @@
|
|||||||
#include "util.h"
|
#include "util.h"
|
||||||
#include "sync.h"
|
#include "sync.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
#include <sys/fcntl.h>
|
#include <sys/fcntl.h>
|
||||||
#endif
|
#endif
|
||||||
@ -14,7 +19,6 @@
|
|||||||
#include "strlcpy.h"
|
#include "strlcpy.h"
|
||||||
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
|
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
|
|
||||||
// Settings
|
// Settings
|
||||||
static proxyType proxyInfo[NET_MAX];
|
static proxyType proxyInfo[NET_MAX];
|
||||||
@ -68,7 +72,7 @@ bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsign
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct addrinfo aiHint;
|
struct addrinfo aiHint;
|
||||||
memset(&aiHint, 0, sizeof(struct addrinfo));
|
std::memset(&aiHint, 0, sizeof(struct addrinfo));
|
||||||
|
|
||||||
aiHint.ai_socktype = SOCK_STREAM;
|
aiHint.ai_socktype = SOCK_STREAM;
|
||||||
aiHint.ai_protocol = IPPROTO_TCP;
|
aiHint.ai_protocol = IPPROTO_TCP;
|
||||||
@ -187,8 +191,8 @@ bool static Socks4(const CService &addrDest, SOCKET& hSocket)
|
|||||||
closesocket(hSocket);
|
closesocket(hSocket);
|
||||||
return error("Cannot get proxy destination address");
|
return error("Cannot get proxy destination address");
|
||||||
}
|
}
|
||||||
memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
|
std::memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
|
||||||
memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
|
std::memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
|
||||||
char* pszSocks4 = pszSocks4IP;
|
char* pszSocks4 = pszSocks4IP;
|
||||||
int nSize = sizeof(pszSocks4IP);
|
int nSize = sizeof(pszSocks4IP);
|
||||||
|
|
||||||
@ -215,7 +219,7 @@ bool static Socks4(const CService &addrDest, SOCKET& hSocket)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool static Socks5(string strDest, int port, SOCKET& hSocket)
|
bool static Socks5(std::string strDest, int port, SOCKET& hSocket)
|
||||||
{
|
{
|
||||||
printf("SOCKS5 connecting %s\n", strDest.c_str());
|
printf("SOCKS5 connecting %s\n", strDest.c_str());
|
||||||
if (strDest.size() > 255)
|
if (strDest.size() > 255)
|
||||||
@ -244,7 +248,7 @@ bool static Socks5(string strDest, int port, SOCKET& hSocket)
|
|||||||
closesocket(hSocket);
|
closesocket(hSocket);
|
||||||
return error("Proxy failed to initialize");
|
return error("Proxy failed to initialize");
|
||||||
}
|
}
|
||||||
string strSocks5("\5\1");
|
std::string strSocks5("\5\1");
|
||||||
strSocks5 += '\000'; strSocks5 += '\003';
|
strSocks5 += '\000'; strSocks5 += '\003';
|
||||||
strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
|
strSocks5 += static_cast<char>(std::min((int)strDest.size(), 255));
|
||||||
strSocks5 += strDest;
|
strSocks5 += strDest;
|
||||||
@ -513,9 +517,9 @@ bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
|
|||||||
|
|
||||||
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
|
bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout)
|
||||||
{
|
{
|
||||||
string strDest;
|
std::string strDest;
|
||||||
int port = portDefault;
|
int port = portDefault;
|
||||||
SplitHostPort(string(pszDest), port, strDest);
|
SplitHostPort(std::string(pszDest), port, strDest);
|
||||||
|
|
||||||
SOCKET hSocket = INVALID_SOCKET;
|
SOCKET hSocket = INVALID_SOCKET;
|
||||||
|
|
||||||
@ -548,12 +552,12 @@ bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest
|
|||||||
|
|
||||||
void CNetAddr::Init()
|
void CNetAddr::Init()
|
||||||
{
|
{
|
||||||
memset(ip, 0, 16);
|
std::memset(ip, 0, 16);
|
||||||
}
|
}
|
||||||
|
|
||||||
void CNetAddr::SetIP(const CNetAddr& ipIn)
|
void CNetAddr::SetIP(const CNetAddr& ipIn)
|
||||||
{
|
{
|
||||||
memcpy(ip, ipIn.ip, sizeof(ip));
|
std::memcpy(ip, ipIn.ip, sizeof(ip));
|
||||||
}
|
}
|
||||||
|
|
||||||
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
|
static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43};
|
||||||
@ -565,7 +569,7 @@ bool CNetAddr::SetSpecial(const std::string &strName)
|
|||||||
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
|
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
|
||||||
if (vchAddr.size() != 16-sizeof(pchOnionCat))
|
if (vchAddr.size() != 16-sizeof(pchOnionCat))
|
||||||
return false;
|
return false;
|
||||||
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
|
std::memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
|
||||||
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
|
for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++)
|
||||||
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
|
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
|
||||||
return true;
|
return true;
|
||||||
@ -574,7 +578,7 @@ bool CNetAddr::SetSpecial(const std::string &strName)
|
|||||||
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
|
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 11).c_str());
|
||||||
if (vchAddr.size() != 16-sizeof(pchGarliCat))
|
if (vchAddr.size() != 16-sizeof(pchGarliCat))
|
||||||
return false;
|
return false;
|
||||||
memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
|
std::memcpy(ip, pchOnionCat, sizeof(pchGarliCat));
|
||||||
for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
|
for (unsigned int i=0; i<16-sizeof(pchGarliCat); i++)
|
||||||
ip[i + sizeof(pchGarliCat)] = vchAddr[i];
|
ip[i + sizeof(pchGarliCat)] = vchAddr[i];
|
||||||
return true;
|
return true;
|
||||||
@ -589,14 +593,14 @@ CNetAddr::CNetAddr()
|
|||||||
|
|
||||||
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
|
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
|
||||||
{
|
{
|
||||||
memcpy(ip, pchIPv4, 12);
|
std::memcpy(ip, pchIPv4, 12);
|
||||||
memcpy(ip+12, &ipv4Addr, 4);
|
std::memcpy(ip+12, &ipv4Addr, 4);
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef USE_IPV6
|
#ifdef USE_IPV6
|
||||||
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
|
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
|
||||||
{
|
{
|
||||||
memcpy(ip, &ipv6Addr, 16);
|
std::memcpy(ip, &ipv6Addr, 16);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@ -623,7 +627,7 @@ unsigned int CNetAddr::GetByte(int n) const
|
|||||||
|
|
||||||
bool CNetAddr::IsIPv4() const
|
bool CNetAddr::IsIPv4() const
|
||||||
{
|
{
|
||||||
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
|
return (std::memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::IsIPv6() const
|
bool CNetAddr::IsIPv6() const
|
||||||
@ -657,7 +661,7 @@ bool CNetAddr::IsRFC3964() const
|
|||||||
bool CNetAddr::IsRFC6052() const
|
bool CNetAddr::IsRFC6052() const
|
||||||
{
|
{
|
||||||
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
|
static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0};
|
||||||
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
|
return (std::memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::IsRFC4380() const
|
bool CNetAddr::IsRFC4380() const
|
||||||
@ -668,7 +672,7 @@ bool CNetAddr::IsRFC4380() const
|
|||||||
bool CNetAddr::IsRFC4862() const
|
bool CNetAddr::IsRFC4862() const
|
||||||
{
|
{
|
||||||
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
|
static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0};
|
||||||
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
|
return (std::memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::IsRFC4193() const
|
bool CNetAddr::IsRFC4193() const
|
||||||
@ -679,7 +683,7 @@ bool CNetAddr::IsRFC4193() const
|
|||||||
bool CNetAddr::IsRFC6145() const
|
bool CNetAddr::IsRFC6145() const
|
||||||
{
|
{
|
||||||
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
|
static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0};
|
||||||
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
|
return (std::memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::IsRFC4843() const
|
bool CNetAddr::IsRFC4843() const
|
||||||
@ -689,12 +693,12 @@ bool CNetAddr::IsRFC4843() const
|
|||||||
|
|
||||||
bool CNetAddr::IsTor() const
|
bool CNetAddr::IsTor() const
|
||||||
{
|
{
|
||||||
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
|
return (std::memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::IsI2P() const
|
bool CNetAddr::IsI2P() const
|
||||||
{
|
{
|
||||||
return (memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
|
return (std::memcmp(ip, pchGarliCat, sizeof(pchGarliCat)) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::IsLocal() const
|
bool CNetAddr::IsLocal() const
|
||||||
@ -705,7 +709,7 @@ bool CNetAddr::IsLocal() const
|
|||||||
|
|
||||||
// IPv6 loopback (::1/128)
|
// IPv6 loopback (::1/128)
|
||||||
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
|
static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
|
||||||
if (memcmp(ip, pchLocal, 16) == 0)
|
if (std::memcmp(ip, pchLocal, 16) == 0)
|
||||||
return true;
|
return true;
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@ -725,12 +729,12 @@ bool CNetAddr::IsValid() const
|
|||||||
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
|
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
|
||||||
// so if the first length field is garbled, it reads the second batch
|
// so if the first length field is garbled, it reads the second batch
|
||||||
// of addr misaligned by 3 bytes.
|
// of addr misaligned by 3 bytes.
|
||||||
if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
|
if (std::memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// unspecified IPv6 address (::/128)
|
// unspecified IPv6 address (::/128)
|
||||||
unsigned char ipNone[16] = {};
|
unsigned char ipNone[16] = {};
|
||||||
if (memcmp(ip, ipNone, 16) == 0)
|
if (std::memcmp(ip, ipNone, 16) == 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// documentation IPv6 address
|
// documentation IPv6 address
|
||||||
@ -741,12 +745,12 @@ bool CNetAddr::IsValid() const
|
|||||||
{
|
{
|
||||||
// INADDR_NONE
|
// INADDR_NONE
|
||||||
uint32_t ipNone = INADDR_NONE;
|
uint32_t ipNone = INADDR_NONE;
|
||||||
if (memcmp(ip+12, &ipNone, 4) == 0)
|
if (std::memcmp(ip+12, &ipNone, 4) == 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// 0
|
// 0
|
||||||
ipNone = 0;
|
ipNone = 0;
|
||||||
if (memcmp(ip+12, &ipNone, 4) == 0)
|
if (std::memcmp(ip+12, &ipNone, 4) == 0)
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -810,31 +814,31 @@ std::string CNetAddr::ToString() const
|
|||||||
|
|
||||||
bool operator==(const CNetAddr& a, const CNetAddr& b)
|
bool operator==(const CNetAddr& a, const CNetAddr& b)
|
||||||
{
|
{
|
||||||
return (memcmp(a.ip, b.ip, 16) == 0);
|
return (std::memcmp(a.ip, b.ip, 16) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool operator!=(const CNetAddr& a, const CNetAddr& b)
|
bool operator!=(const CNetAddr& a, const CNetAddr& b)
|
||||||
{
|
{
|
||||||
return (memcmp(a.ip, b.ip, 16) != 0);
|
return (std::memcmp(a.ip, b.ip, 16) != 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool operator<(const CNetAddr& a, const CNetAddr& b)
|
bool operator<(const CNetAddr& a, const CNetAddr& b)
|
||||||
{
|
{
|
||||||
return (memcmp(a.ip, b.ip, 16) < 0);
|
return (std::memcmp(a.ip, b.ip, 16) < 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
|
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
|
||||||
{
|
{
|
||||||
if (!IsIPv4())
|
if (!IsIPv4())
|
||||||
return false;
|
return false;
|
||||||
memcpy(pipv4Addr, ip+12, 4);
|
std::memcpy(pipv4Addr, ip+12, 4);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef USE_IPV6
|
#ifdef USE_IPV6
|
||||||
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
|
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
|
||||||
{
|
{
|
||||||
memcpy(pipv6Addr, ip, 16);
|
std::memcpy(pipv6Addr, ip, 16);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@ -918,7 +922,7 @@ uint64 CNetAddr::GetHash() const
|
|||||||
{
|
{
|
||||||
uint256 hash = Hash(&ip[0], &ip[16]);
|
uint256 hash = Hash(&ip[0], &ip[16]);
|
||||||
uint64 nRet;
|
uint64 nRet;
|
||||||
memcpy(&nRet, &hash, sizeof(nRet));
|
std::memcpy(&nRet, &hash, sizeof(nRet));
|
||||||
return nRet;
|
return nRet;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1116,7 +1120,7 @@ bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
|
|||||||
return false;
|
return false;
|
||||||
*addrlen = sizeof(struct sockaddr_in);
|
*addrlen = sizeof(struct sockaddr_in);
|
||||||
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
|
struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr;
|
||||||
memset(paddrin, 0, *addrlen);
|
std::memset(paddrin, 0, *addrlen);
|
||||||
if (!GetInAddr(&paddrin->sin_addr))
|
if (!GetInAddr(&paddrin->sin_addr))
|
||||||
return false;
|
return false;
|
||||||
paddrin->sin_family = AF_INET;
|
paddrin->sin_family = AF_INET;
|
||||||
@ -1129,7 +1133,7 @@ bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const
|
|||||||
return false;
|
return false;
|
||||||
*addrlen = sizeof(struct sockaddr_in6);
|
*addrlen = sizeof(struct sockaddr_in6);
|
||||||
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
|
struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr;
|
||||||
memset(paddrin6, 0, *addrlen);
|
std::memset(paddrin6, 0, *addrlen);
|
||||||
if (!GetIn6Addr(&paddrin6->sin6_addr))
|
if (!GetIn6Addr(&paddrin6->sin6_addr))
|
||||||
return false;
|
return false;
|
||||||
paddrin6->sin6_family = AF_INET6;
|
paddrin6->sin6_family = AF_INET6;
|
||||||
@ -1144,7 +1148,7 @@ std::vector<unsigned char> CService::GetKey() const
|
|||||||
{
|
{
|
||||||
std::vector<unsigned char> vKey;
|
std::vector<unsigned char> vKey;
|
||||||
vKey.resize(18);
|
vKey.resize(18);
|
||||||
memcpy(&vKey[0], ip, 16);
|
std::memcpy(&vKey[0], ip, 16);
|
||||||
vKey[16] = port / 0x100;
|
vKey[16] = port / 0x100;
|
||||||
vKey[17] = port & 0x0FF;
|
vKey[17] = port & 0x0FF;
|
||||||
return vKey;
|
return vKey;
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
// Copyright (c) 2013 curecoin Developers
|
// Copyright (c) 2013 curecoin Developers
|
||||||
|
|
||||||
#include <string.h>
|
#include <cstring>
|
||||||
#include "pbkdf2.h"
|
#include "pbkdf2.h"
|
||||||
|
|
||||||
static inline uint32_t be32dec(const void *pp)
|
static inline uint32_t be32dec(const void *pp)
|
||||||
@ -38,20 +38,20 @@ void HMAC_SHA256_Init(HMAC_SHA256_CTX * ctx, const void * _K, size_t Klen)
|
|||||||
|
|
||||||
/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */
|
/* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */
|
||||||
SHA256_Init(&ctx->ictx);
|
SHA256_Init(&ctx->ictx);
|
||||||
memset(pad, 0x36, 64);
|
std::memset(pad, 0x36, 64);
|
||||||
for (i = 0; i < Klen; i++)
|
for (i = 0; i < Klen; i++)
|
||||||
pad[i] ^= K[i];
|
pad[i] ^= K[i];
|
||||||
SHA256_Update(&ctx->ictx, pad, 64);
|
SHA256_Update(&ctx->ictx, pad, 64);
|
||||||
|
|
||||||
/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */
|
/* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */
|
||||||
SHA256_Init(&ctx->octx);
|
SHA256_Init(&ctx->octx);
|
||||||
memset(pad, 0x5c, 64);
|
std::memset(pad, 0x5c, 64);
|
||||||
for (i = 0; i < Klen; i++)
|
for (i = 0; i < Klen; i++)
|
||||||
pad[i] ^= K[i];
|
pad[i] ^= K[i];
|
||||||
SHA256_Update(&ctx->octx, pad, 64);
|
SHA256_Update(&ctx->octx, pad, 64);
|
||||||
|
|
||||||
/* Clean the stack. */
|
/* Clean the stack. */
|
||||||
memset(khash, 0, 32);
|
std::memset(khash, 0, 32);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Add bytes to the HMAC-SHA256 operation. */
|
/* Add bytes to the HMAC-SHA256 operation. */
|
||||||
@ -76,7 +76,7 @@ void HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX * ctx)
|
|||||||
SHA256_Final(digest, &ctx->octx);
|
SHA256_Final(digest, &ctx->octx);
|
||||||
|
|
||||||
/* Clean the stack. */
|
/* Clean the stack. */
|
||||||
memset(ihash, 0, 32);
|
std::memset(ihash, 0, 32);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -131,5 +131,5 @@ void PBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * sal
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Clean PShctx, since we never called _Final on it. */
|
/* Clean PShctx, since we never called _Final on it. */
|
||||||
memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
|
std::memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX));
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,9 @@
|
|||||||
#include "util.h"
|
#include "util.h"
|
||||||
#include "netbase.h"
|
#include "netbase.h"
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
#ifndef WIN32
|
#ifndef WIN32
|
||||||
# include <arpa/inet.h>
|
# include <arpa/inet.h>
|
||||||
#endif
|
#endif
|
||||||
@ -20,8 +23,8 @@ static const char* ppszTypeName[] =
|
|||||||
|
|
||||||
CMessageHeader::CMessageHeader()
|
CMessageHeader::CMessageHeader()
|
||||||
{
|
{
|
||||||
memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
|
std::memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
|
||||||
memset(pchCommand, 0, sizeof(pchCommand));
|
std::memset(pchCommand, 0, sizeof(pchCommand));
|
||||||
pchCommand[1] = 1;
|
pchCommand[1] = 1;
|
||||||
nMessageSize = -1;
|
nMessageSize = -1;
|
||||||
nChecksum = 0;
|
nChecksum = 0;
|
||||||
@ -29,8 +32,8 @@ CMessageHeader::CMessageHeader()
|
|||||||
|
|
||||||
CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
|
CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
|
||||||
{
|
{
|
||||||
memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
|
std::memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
|
||||||
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
|
std::strncpy(pchCommand, pszCommand, COMMAND_SIZE);
|
||||||
nMessageSize = nMessageSizeIn;
|
nMessageSize = nMessageSizeIn;
|
||||||
nChecksum = 0;
|
nChecksum = 0;
|
||||||
}
|
}
|
||||||
@ -46,7 +49,7 @@ std::string CMessageHeader::GetCommand() const
|
|||||||
bool CMessageHeader::IsValid() const
|
bool CMessageHeader::IsValid() const
|
||||||
{
|
{
|
||||||
// Check start string
|
// Check start string
|
||||||
if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
|
if (std::memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
// Check the command string for errors
|
// Check the command string for errors
|
||||||
|
@ -74,9 +74,9 @@ public:
|
|||||||
void updateEntry(const QString &address, const QString &label, bool isMine, int status)
|
void updateEntry(const QString &address, const QString &label, bool isMine, int status)
|
||||||
{
|
{
|
||||||
// Find address / label in model
|
// Find address / label in model
|
||||||
QList<AddressTableEntry>::iterator lower = qLowerBound(
|
QList<AddressTableEntry>::iterator lower = std::lower_bound(
|
||||||
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
|
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
|
||||||
QList<AddressTableEntry>::iterator upper = qUpperBound(
|
QList<AddressTableEntry>::iterator upper = std::upper_bound(
|
||||||
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
|
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
|
||||||
int lowerIndex = (lower - cachedAddressTable.begin());
|
int lowerIndex = (lower - cachedAddressTable.begin());
|
||||||
int upperIndex = (upper - cachedAddressTable.begin());
|
int upperIndex = (upper - cachedAddressTable.begin());
|
||||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -11,6 +11,7 @@
|
|||||||
#include "wallet.h"
|
#include "wallet.h"
|
||||||
#include "ui_interface.h"
|
#include "ui_interface.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <QLocale>
|
#include <QLocale>
|
||||||
#include <QList>
|
#include <QList>
|
||||||
#include <QColor>
|
#include <QColor>
|
||||||
@ -95,9 +96,9 @@ public:
|
|||||||
bool inWallet = mi != wallet->mapWallet.end();
|
bool inWallet = mi != wallet->mapWallet.end();
|
||||||
|
|
||||||
// Find bounds of this transaction in model
|
// Find bounds of this transaction in model
|
||||||
QList<TransactionRecord>::iterator lower = qLowerBound(
|
QList<TransactionRecord>::iterator lower = std::lower_bound(
|
||||||
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
|
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
|
||||||
QList<TransactionRecord>::iterator upper = qUpperBound(
|
QList<TransactionRecord>::iterator upper = std::upper_bound(
|
||||||
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
|
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
|
||||||
int lowerIndex = (lower - cachedWallet.begin());
|
int lowerIndex = (lower - cachedWallet.begin());
|
||||||
int upperIndex = (upper - cachedWallet.begin());
|
int upperIndex = (upper - cachedWallet.begin());
|
||||||
|
@ -6,8 +6,8 @@
|
|||||||
#include "main.h"
|
#include "main.h"
|
||||||
#include "curecoinrpc.h"
|
#include "curecoinrpc.h"
|
||||||
|
|
||||||
using namespace json_spirit;
|
#include <stdexcept>
|
||||||
using namespace std;
|
#include <vector>
|
||||||
|
|
||||||
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
|
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
|
||||||
|
|
||||||
@ -68,41 +68,41 @@ double GetPoSKernelPS()
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
|
json_spirit::Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail)
|
||||||
{
|
{
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
result.push_back(Pair("hash", block.GetHash().GetHex()));
|
result.push_back(json_spirit::Pair("hash", block.GetHash().GetHex()));
|
||||||
CMerkleTx txGen(block.vtx[0]);
|
CMerkleTx txGen(block.vtx[0]);
|
||||||
txGen.SetMerkleBranch(&block);
|
txGen.SetMerkleBranch(&block);
|
||||||
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
|
result.push_back(json_spirit::Pair("confirmations", (int)txGen.GetDepthInMainChain()));
|
||||||
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
|
result.push_back(json_spirit::Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
|
||||||
result.push_back(Pair("height", blockindex->nHeight));
|
result.push_back(json_spirit::Pair("height", blockindex->nHeight));
|
||||||
result.push_back(Pair("version", block.nVersion));
|
result.push_back(json_spirit::Pair("version", block.nVersion));
|
||||||
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
|
result.push_back(json_spirit::Pair("merkleroot", block.hashMerkleRoot.GetHex()));
|
||||||
result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint)));
|
result.push_back(json_spirit::Pair("mint", ValueFromAmount(blockindex->nMint)));
|
||||||
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
|
result.push_back(json_spirit::Pair("time", (boost::int64_t)block.GetBlockTime()));
|
||||||
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
|
result.push_back(json_spirit::Pair("nonce", (boost::uint64_t)block.nNonce));
|
||||||
result.push_back(Pair("bits", HexBits(block.nBits)));
|
result.push_back(json_spirit::Pair("bits", HexBits(block.nBits)));
|
||||||
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
|
result.push_back(json_spirit::Pair("difficulty", GetDifficulty(blockindex)));
|
||||||
|
|
||||||
if (blockindex->pprev)
|
if (blockindex->pprev)
|
||||||
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
|
result.push_back(json_spirit::Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
|
||||||
if (blockindex->pnext)
|
if (blockindex->pnext)
|
||||||
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
|
result.push_back(json_spirit::Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
|
||||||
|
|
||||||
result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
|
result.push_back(json_spirit::Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": "")));
|
||||||
result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
|
result.push_back(json_spirit::Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex()));
|
||||||
result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
|
result.push_back(json_spirit::Pair("entropybit", (int)blockindex->GetStakeEntropyBit()));
|
||||||
result.push_back(Pair("modifier", strprintf("%016"PRI64x, blockindex->nStakeModifier)));
|
result.push_back(json_spirit::Pair("modifier", strprintf("%016" PRI64x, blockindex->nStakeModifier)));
|
||||||
result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
|
result.push_back(json_spirit::Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum)));
|
||||||
Array txinfo;
|
json_spirit::Array txinfo;
|
||||||
BOOST_FOREACH (const CTransaction& tx, block.vtx)
|
BOOST_FOREACH (const CTransaction& tx, block.vtx)
|
||||||
{
|
{
|
||||||
if (fPrintTransactionDetail)
|
if (fPrintTransactionDetail)
|
||||||
{
|
{
|
||||||
Object entry;
|
json_spirit::Object entry;
|
||||||
|
|
||||||
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
|
entry.push_back(json_spirit::Pair("txid", tx.GetHash().GetHex()));
|
||||||
TxToJSON(tx, 0, entry);
|
TxToJSON(tx, 0, entry);
|
||||||
|
|
||||||
txinfo.push_back(entry);
|
txinfo.push_back(entry);
|
||||||
@ -111,17 +111,17 @@ Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPri
|
|||||||
txinfo.push_back(tx.GetHash().GetHex());
|
txinfo.push_back(tx.GetHash().GetHex());
|
||||||
}
|
}
|
||||||
|
|
||||||
result.push_back(Pair("tx", txinfo));
|
result.push_back(json_spirit::Pair("tx", txinfo));
|
||||||
result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
|
result.push_back(json_spirit::Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end())));
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value getblockcount(const Array& params, bool fHelp)
|
json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getblockcount\n"
|
"getblockcount\n"
|
||||||
"Returns the number of blocks in the longest block chain.");
|
"Returns the number of blocks in the longest block chain.");
|
||||||
|
|
||||||
@ -129,25 +129,25 @@ Value getblockcount(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value getdifficulty(const Array& params, bool fHelp)
|
json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getdifficulty\n"
|
"getdifficulty\n"
|
||||||
"Returns the difficulty as a multiple of the minimum difficulty.");
|
"Returns the difficulty as a multiple of the minimum difficulty.");
|
||||||
|
|
||||||
Object obj;
|
json_spirit::Object obj;
|
||||||
obj.push_back(Pair("proof-of-work", GetDifficulty()));
|
obj.push_back(json_spirit::Pair("proof-of-work", GetDifficulty()));
|
||||||
obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
|
obj.push_back(json_spirit::Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
|
||||||
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
|
obj.push_back(json_spirit::Pair("search-interval", (int)nLastCoinStakeSearchInterval));
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value settxfee(const Array& params, bool fHelp)
|
json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
|
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"settxfee <amount>\n"
|
"settxfee <amount>\n"
|
||||||
"<amount> is a real and is rounded to the nearest 0.01");
|
"<amount> is a real and is rounded to the nearest 0.01");
|
||||||
|
|
||||||
@ -157,42 +157,42 @@ Value settxfee(const Array& params, bool fHelp)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getrawmempool(const Array& params, bool fHelp)
|
json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getrawmempool\n"
|
"getrawmempool\n"
|
||||||
"Returns all transaction ids in memory pool.");
|
"Returns all transaction ids in memory pool.");
|
||||||
|
|
||||||
vector<uint256> vtxid;
|
std::vector<uint256> vtxid;
|
||||||
mempool.queryHashes(vtxid);
|
mempool.queryHashes(vtxid);
|
||||||
|
|
||||||
Array a;
|
json_spirit::Array a;
|
||||||
BOOST_FOREACH(const uint256& hash, vtxid)
|
BOOST_FOREACH(const uint256& hash, vtxid)
|
||||||
a.push_back(hash.ToString());
|
a.push_back(hash.ToString());
|
||||||
|
|
||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getblockhash(const Array& params, bool fHelp)
|
json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 1)
|
if (fHelp || params.size() != 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getblockhash <index>\n"
|
"getblockhash <index>\n"
|
||||||
"Returns hash of block in best-block-chain at <index>.");
|
"Returns hash of block in best-block-chain at <index>.");
|
||||||
|
|
||||||
int nHeight = params[0].get_int();
|
int nHeight = params[0].get_int();
|
||||||
if (nHeight < 0 || nHeight > nBestHeight)
|
if (nHeight < 0 || nHeight > nBestHeight)
|
||||||
throw runtime_error("Block number out of range.");
|
throw std::runtime_error("Block number out of range.");
|
||||||
|
|
||||||
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
|
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
|
||||||
return pblockindex->phashBlock->GetHex();
|
return pblockindex->phashBlock->GetHex();
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getblock(const Array& params, bool fHelp)
|
json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getblock <hash> [txinfo]\n"
|
"getblock <hash> [txinfo]\n"
|
||||||
"txinfo optional to print more detailed tx info\n"
|
"txinfo optional to print more detailed tx info\n"
|
||||||
"Returns details of a block with given block-hash.");
|
"Returns details of a block with given block-hash.");
|
||||||
@ -210,17 +210,17 @@ Value getblock(const Array& params, bool fHelp)
|
|||||||
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
|
return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false);
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getblockbynumber(const Array& params, bool fHelp)
|
json_spirit::Value getblockbynumber(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getblock <number> [txinfo]\n"
|
"getblock <number> [txinfo]\n"
|
||||||
"txinfo optional to print more detailed tx info\n"
|
"txinfo optional to print more detailed tx info\n"
|
||||||
"Returns details of a block with given block-number.");
|
"Returns details of a block with given block-number.");
|
||||||
|
|
||||||
int nHeight = params[0].get_int();
|
int nHeight = params[0].get_int();
|
||||||
if (nHeight < 0 || nHeight > nBestHeight)
|
if (nHeight < 0 || nHeight > nBestHeight)
|
||||||
throw runtime_error("Block number out of range.");
|
throw std::runtime_error("Block number out of range.");
|
||||||
|
|
||||||
CBlock block;
|
CBlock block;
|
||||||
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
|
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
|
||||||
@ -236,22 +236,22 @@ Value getblockbynumber(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ppcoin: get information of sync-checkpoint
|
// ppcoin: get information of sync-checkpoint
|
||||||
Value getcheckpoint(const Array& params, bool fHelp)
|
json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getcheckpoint\n"
|
"getcheckpoint\n"
|
||||||
"Show info of synchronized checkpoint.\n");
|
"Show info of synchronized checkpoint.\n");
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
CBlockIndex* pindexCheckpoint;
|
CBlockIndex* pindexCheckpoint;
|
||||||
|
|
||||||
result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
|
result.push_back(json_spirit::Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str()));
|
||||||
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
|
pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint];
|
||||||
result.push_back(Pair("height", pindexCheckpoint->nHeight));
|
result.push_back(json_spirit::Pair("height", pindexCheckpoint->nHeight));
|
||||||
result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
|
result.push_back(json_spirit::Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str()));
|
||||||
if (mapArgs.count("-checkpointkey"))
|
if (mapArgs.count("-checkpointkey"))
|
||||||
result.push_back(Pair("checkpointmaster", true));
|
result.push_back(json_spirit::Pair("checkpointmaster", true));
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@ -9,10 +9,10 @@
|
|||||||
|
|
||||||
#include <boost/lexical_cast.hpp>
|
#include <boost/lexical_cast.hpp>
|
||||||
|
|
||||||
#define printf OutputDebugStringF
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
using namespace json_spirit;
|
#define printf OutputDebugStringF
|
||||||
using namespace std;
|
|
||||||
|
|
||||||
class CTxDump
|
class CTxDump
|
||||||
{
|
{
|
||||||
@ -32,15 +32,15 @@ public:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Value importprivkey(const Array& params, bool fHelp)
|
json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"importprivkey <curecoinPrivkey> [label]\n"
|
"importprivkey <curecoinPrivkey> [label]\n"
|
||||||
"Adds a private key (as returned by dumpprivkey) to your wallet.");
|
"Adds a private key (as returned by dumpprivkey) to your wallet.");
|
||||||
|
|
||||||
string strSecret = params[0].get_str();
|
std::string strSecret = params[0].get_str();
|
||||||
string strLabel = "";
|
std::string strLabel = "";
|
||||||
if (params.size() > 1)
|
if (params.size() > 1)
|
||||||
strLabel = params[1].get_str();
|
strLabel = params[1].get_str();
|
||||||
CcurecoinSecret vchSecret;
|
CcurecoinSecret vchSecret;
|
||||||
@ -68,17 +68,17 @@ Value importprivkey(const Array& params, bool fHelp)
|
|||||||
pwalletMain->ReacceptWalletTransactions();
|
pwalletMain->ReacceptWalletTransactions();
|
||||||
}
|
}
|
||||||
|
|
||||||
return Value::null;
|
return json_spirit::Value::null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value dumpprivkey(const Array& params, bool fHelp)
|
json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 1)
|
if (fHelp || params.size() != 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"dumpprivkey <curecoinAddress>\n"
|
"dumpprivkey <curecoinAddress>\n"
|
||||||
"Reveals the private key corresponding to <curecoinaddress>.");
|
"Reveals the private key corresponding to <curecoinaddress>.");
|
||||||
|
|
||||||
string strAddress = params[0].get_str();
|
std::string strAddress = params[0].get_str();
|
||||||
CcurecoinAddress address;
|
CcurecoinAddress address;
|
||||||
if (!address.SetString(strAddress))
|
if (!address.SetString(strAddress))
|
||||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid curecoin address");
|
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid curecoin address");
|
||||||
|
@ -8,15 +8,18 @@
|
|||||||
#include "init.h"
|
#include "init.h"
|
||||||
#include "curecoinrpc.h"
|
#include "curecoinrpc.h"
|
||||||
|
|
||||||
using namespace json_spirit;
|
#include <algorithm>
|
||||||
using namespace std;
|
#include <map>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
extern unsigned int nStakeTargetSpacing;
|
extern unsigned int nStakeTargetSpacing;
|
||||||
|
|
||||||
Value getgenerate(const Array& params, bool fHelp)
|
json_spirit::Value getgenerate(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getgenerate\n"
|
"getgenerate\n"
|
||||||
"Returns true or false.");
|
"Returns true or false.");
|
||||||
|
|
||||||
@ -24,10 +27,10 @@ Value getgenerate(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value setgenerate(const Array& params, bool fHelp)
|
json_spirit::Value setgenerate(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"setgenerate <generate> [genproclimit]\n"
|
"setgenerate <generate> [genproclimit]\n"
|
||||||
"<generate> is true or false to turn generation on or off.\n"
|
"<generate> is true or false to turn generation on or off.\n"
|
||||||
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
|
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
|
||||||
@ -46,14 +49,14 @@ Value setgenerate(const Array& params, bool fHelp)
|
|||||||
mapArgs["-gen"] = (fGenerate ? "1" : "0");
|
mapArgs["-gen"] = (fGenerate ? "1" : "0");
|
||||||
|
|
||||||
Generatecurecoins(fGenerate, pwalletMain);
|
Generatecurecoins(fGenerate, pwalletMain);
|
||||||
return Value::null;
|
return json_spirit::Value::null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value gethashespersec(const Array& params, bool fHelp)
|
json_spirit::Value gethashespersec(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"gethashespersec\n"
|
"gethashespersec\n"
|
||||||
"Returns a recent hashes per second performance measurement while generating.");
|
"Returns a recent hashes per second performance measurement while generating.");
|
||||||
|
|
||||||
@ -63,7 +66,7 @@ Value gethashespersec(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Litecoin: Return average network hashes per second based on last number of blocks.
|
// Litecoin: Return average network hashes per second based on last number of blocks.
|
||||||
Value GetNetworkHashPS(int lookup) {
|
json_spirit::Value GetNetworkHashPS(int lookup) {
|
||||||
if (pindexBest == NULL)
|
if (pindexBest == NULL)
|
||||||
return 0;
|
return 0;
|
||||||
|
|
||||||
@ -86,10 +89,10 @@ Value GetNetworkHashPS(int lookup) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value getnetworkhashps(const Array& params, bool fHelp)
|
json_spirit::Value getnetworkhashps(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 1)
|
if (fHelp || params.size() > 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getnetworkhashps [blocks]\n"
|
"getnetworkhashps [blocks]\n"
|
||||||
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
|
"Returns the estimated network hashes per second based on the last 120 blocks.\n"
|
||||||
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.");
|
"Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.");
|
||||||
@ -98,33 +101,33 @@ Value getnetworkhashps(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value getmininginfo(const Array& params, bool fHelp)
|
json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getmininginfo\n"
|
"getmininginfo\n"
|
||||||
"Returns an object containing mining-related information.");
|
"Returns an object containing mining-related information.");
|
||||||
|
|
||||||
Object obj;
|
json_spirit::Object obj;
|
||||||
obj.push_back(Pair("blocks", (int)nBestHeight));
|
obj.push_back(json_spirit::Pair("blocks", (int)nBestHeight));
|
||||||
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
|
obj.push_back(json_spirit::Pair("currentblocksize",(uint64_t)nLastBlockSize));
|
||||||
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
|
obj.push_back(json_spirit::Pair("currentblocktx",(uint64_t)nLastBlockTx));
|
||||||
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
|
obj.push_back(json_spirit::Pair("difficulty", (double)GetDifficulty()));
|
||||||
// obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
|
// obj.push_back(json_spirit::Pair("netstakeweight", GetPoSKernelPS()));
|
||||||
obj.push_back(Pair("errors", GetWarnings("statusbar")));
|
obj.push_back(json_spirit::Pair("errors", GetWarnings("statusbar")));
|
||||||
obj.push_back(Pair("generate", GetBoolArg("-gen")));
|
obj.push_back(json_spirit::Pair("generate", GetBoolArg("-gen")));
|
||||||
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
|
obj.push_back(json_spirit::Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
|
||||||
obj.push_back(Pair("hashespersec", gethashespersec(params, false)));
|
obj.push_back(json_spirit::Pair("hashespersec", gethashespersec(params, false)));
|
||||||
obj.push_back(Pair("networkhashps", getnetworkhashps(params, false)));
|
obj.push_back(json_spirit::Pair("networkhashps", getnetworkhashps(params, false)));
|
||||||
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
|
obj.push_back(json_spirit::Pair("pooledtx", (uint64_t)mempool.size()));
|
||||||
obj.push_back(Pair("testnet", fTestNet));
|
obj.push_back(json_spirit::Pair("testnet", fTestNet));
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getstakinginfo(const Array& params, bool fHelp)
|
json_spirit::Value getstakinginfo(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getstakinginfo\n"
|
"getstakinginfo\n"
|
||||||
"Returns an object containing staking-related information.");
|
"Returns an object containing staking-related information.");
|
||||||
|
|
||||||
@ -135,31 +138,31 @@ Value getstakinginfo(const Array& params, bool fHelp)
|
|||||||
bool staking = nLastCoinStakeSearchInterval && nWeight;
|
bool staking = nLastCoinStakeSearchInterval && nWeight;
|
||||||
int nExpectedTime = staking ? (nStakeTargetSpacing * nNetworkWeight / nWeight) : -1;
|
int nExpectedTime = staking ? (nStakeTargetSpacing * nNetworkWeight / nWeight) : -1;
|
||||||
|
|
||||||
Object obj;
|
json_spirit::Object obj;
|
||||||
|
|
||||||
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
|
obj.push_back(json_spirit::Pair("enabled", GetBoolArg("-staking", true)));
|
||||||
obj.push_back(Pair("staking", staking));
|
obj.push_back(json_spirit::Pair("staking", staking));
|
||||||
obj.push_back(Pair("errors", GetWarnings("statusbar")));
|
obj.push_back(json_spirit::Pair("errors", GetWarnings("statusbar")));
|
||||||
|
|
||||||
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
|
obj.push_back(json_spirit::Pair("currentblocksize", (uint64_t)nLastBlockSize));
|
||||||
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
|
obj.push_back(json_spirit::Pair("currentblocktx", (uint64_t)nLastBlockTx));
|
||||||
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
|
obj.push_back(json_spirit::Pair("pooledtx", (uint64_t)mempool.size()));
|
||||||
|
|
||||||
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
|
obj.push_back(json_spirit::Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
|
||||||
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
|
obj.push_back(json_spirit::Pair("search-interval", (int)nLastCoinStakeSearchInterval));
|
||||||
|
|
||||||
obj.push_back(Pair("weight", (uint64_t)nWeight));
|
obj.push_back(json_spirit::Pair("weight", (uint64_t)nWeight));
|
||||||
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
|
obj.push_back(json_spirit::Pair("netstakeweight", (uint64_t)nNetworkWeight));
|
||||||
|
|
||||||
obj.push_back(Pair("expectedtime", nExpectedTime));
|
obj.push_back(json_spirit::Pair("expectedtime", nExpectedTime));
|
||||||
|
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getworkex(const Array& params, bool fHelp)
|
json_spirit::Value getworkex(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 2)
|
if (fHelp || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getworkex [data, coinbase]\n"
|
"getworkex [data, coinbase]\n"
|
||||||
"If [data, coinbase] is not specified, returns extended work data.\n"
|
"If [data, coinbase] is not specified, returns extended work data.\n"
|
||||||
);
|
);
|
||||||
@ -170,9 +173,9 @@ Value getworkex(const Array& params, bool fHelp)
|
|||||||
if (IsInitialBlockDownload())
|
if (IsInitialBlockDownload())
|
||||||
throw JSONRPCError(-10, "Curecoin is downloading blocks...");
|
throw JSONRPCError(-10, "Curecoin is downloading blocks...");
|
||||||
|
|
||||||
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
|
typedef std::map<uint256, std::pair<CBlock*, CScript> > mapNewBlock_t;
|
||||||
static mapNewBlock_t mapNewBlock;
|
static mapNewBlock_t mapNewBlock;
|
||||||
static vector<CBlock*> vNewBlock;
|
static std::vector<CBlock*> vNewBlock;
|
||||||
static CReserveKey reservekey(pwalletMain);
|
static CReserveKey reservekey(pwalletMain);
|
||||||
|
|
||||||
if (params.size() == 0)
|
if (params.size() == 0)
|
||||||
@ -205,7 +208,7 @@ Value getworkex(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update nTime
|
// Update nTime
|
||||||
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
|
pblock->nTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
|
||||||
pblock->nNonce = 0;
|
pblock->nNonce = 0;
|
||||||
|
|
||||||
// Update nExtraNonce
|
// Update nExtraNonce
|
||||||
@ -226,21 +229,21 @@ Value getworkex(const Array& params, bool fHelp)
|
|||||||
CTransaction coinbaseTx = pblock->vtx[0];
|
CTransaction coinbaseTx = pblock->vtx[0];
|
||||||
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
|
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
|
result.push_back(json_spirit::Pair("data", HexStr(BEGIN(pdata), END(pdata))));
|
||||||
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
|
result.push_back(json_spirit::Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
|
||||||
|
|
||||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||||
ssTx << coinbaseTx;
|
ssTx << coinbaseTx;
|
||||||
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
|
result.push_back(json_spirit::Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
|
||||||
|
|
||||||
Array merkle_arr;
|
json_spirit::Array merkle_arr;
|
||||||
|
|
||||||
BOOST_FOREACH(uint256 merkleh, merkle) {
|
BOOST_FOREACH(uint256 merkleh, merkle) {
|
||||||
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
|
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
|
||||||
}
|
}
|
||||||
|
|
||||||
result.push_back(Pair("merkle", merkle_arr));
|
result.push_back(json_spirit::Pair("merkle", merkle_arr));
|
||||||
|
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -248,8 +251,8 @@ Value getworkex(const Array& params, bool fHelp)
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Parse parameters
|
// Parse parameters
|
||||||
vector<unsigned char> vchData = ParseHex(params[0].get_str());
|
std::vector<unsigned char> vchData = ParseHex(params[0].get_str());
|
||||||
vector<unsigned char> coinbase;
|
std::vector<unsigned char> coinbase;
|
||||||
|
|
||||||
if(params.size() == 2)
|
if(params.size() == 2)
|
||||||
coinbase = ParseHex(params[1].get_str());
|
coinbase = ParseHex(params[1].get_str());
|
||||||
@ -286,10 +289,10 @@ Value getworkex(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value getwork(const Array& params, bool fHelp)
|
json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 1)
|
if (fHelp || params.size() > 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getwork [data]\n"
|
"getwork [data]\n"
|
||||||
"If [data] is not specified, returns formatted hash data to work on:\n"
|
"If [data] is not specified, returns formatted hash data to work on:\n"
|
||||||
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
|
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
|
||||||
@ -304,9 +307,9 @@ Value getwork(const Array& params, bool fHelp)
|
|||||||
if (IsInitialBlockDownload())
|
if (IsInitialBlockDownload())
|
||||||
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Curecoin is downloading blocks...");
|
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Curecoin is downloading blocks...");
|
||||||
|
|
||||||
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
|
typedef std::map<uint256, std::pair<CBlock*, CScript> > mapNewBlock_t;
|
||||||
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
|
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
|
||||||
static vector<CBlock*> vNewBlock;
|
static std::vector<CBlock*> vNewBlock;
|
||||||
static CReserveKey reservekey(pwalletMain);
|
static CReserveKey reservekey(pwalletMain);
|
||||||
|
|
||||||
if (params.size() == 0)
|
if (params.size() == 0)
|
||||||
@ -365,17 +368,17 @@ Value getwork(const Array& params, bool fHelp)
|
|||||||
|
|
||||||
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
|
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
|
result.push_back(json_spirit::Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
|
||||||
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
|
result.push_back(json_spirit::Pair("data", HexStr(BEGIN(pdata), END(pdata))));
|
||||||
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
|
result.push_back(json_spirit::Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
|
||||||
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
|
result.push_back(json_spirit::Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
// Parse parameters
|
// Parse parameters
|
||||||
vector<unsigned char> vchData = ParseHex(params[0].get_str());
|
std::vector<unsigned char> vchData = ParseHex(params[0].get_str());
|
||||||
if (vchData.size() != 128)
|
if (vchData.size() != 128)
|
||||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
|
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
|
||||||
CBlock* pdata = (CBlock*)&vchData[0];
|
CBlock* pdata = (CBlock*)&vchData[0];
|
||||||
@ -402,10 +405,10 @@ Value getwork(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Value getblocktemplate(const Array& params, bool fHelp)
|
json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 1)
|
if (fHelp || params.size() > 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getblocktemplate [params]\n"
|
"getblocktemplate [params]\n"
|
||||||
"Returns data needed to construct a block to work on:\n"
|
"Returns data needed to construct a block to work on:\n"
|
||||||
" \"version\" : block version\n"
|
" \"version\" : block version\n"
|
||||||
@ -427,11 +430,11 @@ Value getblocktemplate(const Array& params, bool fHelp)
|
|||||||
std::string strMode = "template";
|
std::string strMode = "template";
|
||||||
if (params.size() > 0)
|
if (params.size() > 0)
|
||||||
{
|
{
|
||||||
const Object& oparam = params[0].get_obj();
|
const json_spirit::Object& oparam = params[0].get_obj();
|
||||||
const Value& modeval = find_value(oparam, "mode");
|
const json_spirit::Value& modeval = find_value(oparam, "mode");
|
||||||
if (modeval.type() == str_type)
|
if (modeval.type() == json_spirit::str_type)
|
||||||
strMode = modeval.get_str();
|
strMode = modeval.get_str();
|
||||||
else if (modeval.type() == null_type)
|
else if (modeval.type() == json_spirit::null_type)
|
||||||
{
|
{
|
||||||
/* Do nothing */
|
/* Do nothing */
|
||||||
}
|
}
|
||||||
@ -484,8 +487,8 @@ Value getblocktemplate(const Array& params, bool fHelp)
|
|||||||
pblock->UpdateTime(pindexPrev);
|
pblock->UpdateTime(pindexPrev);
|
||||||
pblock->nNonce = 0;
|
pblock->nNonce = 0;
|
||||||
|
|
||||||
Array transactions;
|
json_spirit::Array transactions;
|
||||||
map<uint256, int64_t> setTxIndex;
|
std::map<uint256, int64_t> setTxIndex;
|
||||||
int i = 0;
|
int i = 0;
|
||||||
CTxDB txdb("r");
|
CTxDB txdb("r");
|
||||||
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
|
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
|
||||||
@ -496,43 +499,43 @@ Value getblocktemplate(const Array& params, bool fHelp)
|
|||||||
if (tx.IsCoinBase() || tx.IsCoinStake())
|
if (tx.IsCoinBase() || tx.IsCoinStake())
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
Object entry;
|
json_spirit::Object entry;
|
||||||
|
|
||||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||||
ssTx << tx;
|
ssTx << tx;
|
||||||
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
|
entry.push_back(json_spirit::Pair("data", HexStr(ssTx.begin(), ssTx.end())));
|
||||||
|
|
||||||
entry.push_back(Pair("hash", txHash.GetHex()));
|
entry.push_back(json_spirit::Pair("hash", txHash.GetHex()));
|
||||||
|
|
||||||
MapPrevTx mapInputs;
|
MapPrevTx mapInputs;
|
||||||
map<uint256, CTxIndex> mapUnused;
|
std::map<uint256, CTxIndex> mapUnused;
|
||||||
bool fInvalid = false;
|
bool fInvalid = false;
|
||||||
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
|
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
|
||||||
{
|
{
|
||||||
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
|
entry.push_back(json_spirit::Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
|
||||||
|
|
||||||
Array deps;
|
json_spirit::Array deps;
|
||||||
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
|
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
|
||||||
{
|
{
|
||||||
if (setTxIndex.count(inp.first))
|
if (setTxIndex.count(inp.first))
|
||||||
deps.push_back(setTxIndex[inp.first]);
|
deps.push_back(setTxIndex[inp.first]);
|
||||||
}
|
}
|
||||||
entry.push_back(Pair("depends", deps));
|
entry.push_back(json_spirit::Pair("depends", deps));
|
||||||
|
|
||||||
int64_t nSigOps = tx.GetLegacySigOpCount();
|
int64_t nSigOps = tx.GetLegacySigOpCount();
|
||||||
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
|
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
|
||||||
entry.push_back(Pair("sigops", nSigOps));
|
entry.push_back(json_spirit::Pair("sigops", nSigOps));
|
||||||
}
|
}
|
||||||
|
|
||||||
transactions.push_back(entry);
|
transactions.push_back(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object aux;
|
json_spirit::Object aux;
|
||||||
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
|
aux.push_back(json_spirit::Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
|
||||||
|
|
||||||
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
|
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
|
||||||
|
|
||||||
static Array aMutable;
|
static json_spirit::Array aMutable;
|
||||||
if (aMutable.empty())
|
if (aMutable.empty())
|
||||||
{
|
{
|
||||||
aMutable.push_back("time");
|
aMutable.push_back("time");
|
||||||
@ -540,35 +543,35 @@ Value getblocktemplate(const Array& params, bool fHelp)
|
|||||||
aMutable.push_back("prevblock");
|
aMutable.push_back("prevblock");
|
||||||
}
|
}
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
result.push_back(Pair("version", pblock->nVersion));
|
result.push_back(json_spirit::Pair("version", pblock->nVersion));
|
||||||
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
|
result.push_back(json_spirit::Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
|
||||||
result.push_back(Pair("transactions", transactions));
|
result.push_back(json_spirit::Pair("transactions", transactions));
|
||||||
result.push_back(Pair("coinbaseaux", aux));
|
result.push_back(json_spirit::Pair("coinbaseaux", aux));
|
||||||
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
|
result.push_back(json_spirit::Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
|
||||||
result.push_back(Pair("target", hashTarget.GetHex()));
|
result.push_back(json_spirit::Pair("target", hashTarget.GetHex()));
|
||||||
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
|
result.push_back(json_spirit::Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
|
||||||
result.push_back(Pair("mutable", aMutable));
|
result.push_back(json_spirit::Pair("mutable", aMutable));
|
||||||
result.push_back(Pair("noncerange", "00000000ffffffff"));
|
result.push_back(json_spirit::Pair("noncerange", "00000000ffffffff"));
|
||||||
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
|
result.push_back(json_spirit::Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
|
||||||
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
|
result.push_back(json_spirit::Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
|
||||||
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
|
result.push_back(json_spirit::Pair("curtime", (int64_t)pblock->nTime));
|
||||||
result.push_back(Pair("bits", HexBits(pblock->nBits)));
|
result.push_back(json_spirit::Pair("bits", HexBits(pblock->nBits)));
|
||||||
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
|
result.push_back(json_spirit::Pair("height", (int64_t)(pindexPrev->nHeight+1)));
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value submitblock(const Array& params, bool fHelp)
|
json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"submitblock <hex data> [optional-params-obj]\n"
|
"submitblock <hex data> [optional-params-obj]\n"
|
||||||
"[optional-params-obj] parameter is currently ignored.\n"
|
"[optional-params-obj] parameter is currently ignored.\n"
|
||||||
"Attempts to submit new block to network.\n"
|
"Attempts to submit new block to network.\n"
|
||||||
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
|
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
|
||||||
|
|
||||||
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
|
std::vector<unsigned char> blockData(ParseHex(params[0].get_str()));
|
||||||
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
|
||||||
CBlock block;
|
CBlock block;
|
||||||
try {
|
try {
|
||||||
@ -585,6 +588,6 @@ Value submitblock(const Array& params, bool fHelp)
|
|||||||
if (!fAccepted)
|
if (!fAccepted)
|
||||||
return "rejected";
|
return "rejected";
|
||||||
|
|
||||||
return Value::null;
|
return json_spirit::Value::null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -9,13 +9,15 @@
|
|||||||
#include "db.h"
|
#include "db.h"
|
||||||
#include "walletdb.h"
|
#include "walletdb.h"
|
||||||
|
|
||||||
using namespace json_spirit;
|
#include <map>
|
||||||
using namespace std;
|
#include <stdexcept>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
Value getconnectioncount(const Array& params, bool fHelp)
|
|
||||||
|
json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getconnectioncount\n"
|
"getconnectioncount\n"
|
||||||
"Returns the number of connections to other nodes.");
|
"Returns the number of connections to other nodes.");
|
||||||
|
|
||||||
@ -36,32 +38,32 @@ static void CopyNodeStats(std::vector<CNodeStats>& vstats)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getpeerinfo(const Array& params, bool fHelp)
|
json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 0)
|
if (fHelp || params.size() != 0)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getpeerinfo\n"
|
"getpeerinfo\n"
|
||||||
"Returns data about each connected network node.");
|
"Returns data about each connected network node.");
|
||||||
|
|
||||||
vector<CNodeStats> vstats;
|
std::vector<CNodeStats> vstats;
|
||||||
CopyNodeStats(vstats);
|
CopyNodeStats(vstats);
|
||||||
|
|
||||||
Array ret;
|
json_spirit::Array ret;
|
||||||
|
|
||||||
BOOST_FOREACH(const CNodeStats& stats, vstats) {
|
BOOST_FOREACH(const CNodeStats& stats, vstats) {
|
||||||
Object obj;
|
json_spirit::Object obj;
|
||||||
|
|
||||||
obj.push_back(Pair("addr", stats.addrName));
|
obj.push_back(json_spirit::Pair("addr", stats.addrName));
|
||||||
obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices)));
|
obj.push_back(json_spirit::Pair("services", strprintf("%08" PRI64x, stats.nServices)));
|
||||||
obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend));
|
obj.push_back(json_spirit::Pair("lastsend", (boost::int64_t)stats.nLastSend));
|
||||||
obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
|
obj.push_back(json_spirit::Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
|
||||||
obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected));
|
obj.push_back(json_spirit::Pair("conntime", (boost::int64_t)stats.nTimeConnected));
|
||||||
obj.push_back(Pair("version", stats.nVersion));
|
obj.push_back(json_spirit::Pair("version", stats.nVersion));
|
||||||
obj.push_back(Pair("subver", stats.strSubVer));
|
obj.push_back(json_spirit::Pair("subver", stats.strSubVer));
|
||||||
obj.push_back(Pair("inbound", stats.fInbound));
|
obj.push_back(json_spirit::Pair("inbound", stats.fInbound));
|
||||||
obj.push_back(Pair("releasetime", (boost::int64_t)stats.nReleaseTime));
|
obj.push_back(json_spirit::Pair("releasetime", (boost::int64_t)stats.nReleaseTime));
|
||||||
obj.push_back(Pair("startingheight", stats.nStartingHeight));
|
obj.push_back(json_spirit::Pair("startingheight", stats.nStartingHeight));
|
||||||
obj.push_back(Pair("banscore", stats.nMisbehavior));
|
obj.push_back(json_spirit::Pair("banscore", stats.nMisbehavior));
|
||||||
|
|
||||||
ret.push_back(obj);
|
ret.push_back(obj);
|
||||||
}
|
}
|
||||||
@ -70,16 +72,16 @@ Value getpeerinfo(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
extern CCriticalSection cs_mapAlerts;
|
extern CCriticalSection cs_mapAlerts;
|
||||||
extern map<uint256, CAlert> mapAlerts;
|
extern std::map<uint256, CAlert> mapAlerts;
|
||||||
|
|
||||||
// ppcoin: send alert.
|
// ppcoin: send alert.
|
||||||
// There is a known deadlock situation with ThreadMessageHandler
|
// There is a known deadlock situation with ThreadMessageHandler
|
||||||
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
|
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
|
||||||
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
|
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
|
||||||
Value sendalert(const Array& params, bool fHelp)
|
json_spirit::Value sendalert(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 6)
|
if (fHelp || params.size() < 6)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
|
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
|
||||||
"<message> is the alert text message\n"
|
"<message> is the alert text message\n"
|
||||||
"<privatekey> is hex string of alert master private key\n"
|
"<privatekey> is hex string of alert master private key\n"
|
||||||
@ -106,15 +108,15 @@ Value sendalert(const Array& params, bool fHelp)
|
|||||||
|
|
||||||
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
|
||||||
sMsg << (CUnsignedAlert)alert;
|
sMsg << (CUnsignedAlert)alert;
|
||||||
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
|
alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
|
||||||
|
|
||||||
vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
|
std::vector<unsigned char> vchPrivKey = ParseHex(params[1].get_str());
|
||||||
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
|
key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
|
||||||
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
|
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"Unable to sign alert, check private key?\n");
|
"Unable to sign alert, check private key?\n");
|
||||||
if(!alert.ProcessAlert())
|
if(!alert.ProcessAlert())
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"Failed to process alert.\n");
|
"Failed to process alert.\n");
|
||||||
// Relay alert
|
// Relay alert
|
||||||
{
|
{
|
||||||
@ -123,14 +125,14 @@ Value sendalert(const Array& params, bool fHelp)
|
|||||||
alert.RelayTo(pnode);
|
alert.RelayTo(pnode);
|
||||||
}
|
}
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
result.push_back(Pair("strStatusBar", alert.strStatusBar));
|
result.push_back(json_spirit::Pair("strStatusBar", alert.strStatusBar));
|
||||||
result.push_back(Pair("nVersion", alert.nVersion));
|
result.push_back(json_spirit::Pair("nVersion", alert.nVersion));
|
||||||
result.push_back(Pair("nMinVer", alert.nMinVer));
|
result.push_back(json_spirit::Pair("nMinVer", alert.nMinVer));
|
||||||
result.push_back(Pair("nMaxVer", alert.nMaxVer));
|
result.push_back(json_spirit::Pair("nMaxVer", alert.nMaxVer));
|
||||||
result.push_back(Pair("nPriority", alert.nPriority));
|
result.push_back(json_spirit::Pair("nPriority", alert.nPriority));
|
||||||
result.push_back(Pair("nID", alert.nID));
|
result.push_back(json_spirit::Pair("nID", alert.nID));
|
||||||
if (alert.nCancel > 0)
|
if (alert.nCancel > 0)
|
||||||
result.push_back(Pair("nCancel", alert.nCancel));
|
result.push_back(json_spirit::Pair("nCancel", alert.nCancel));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
@ -13,102 +13,106 @@
|
|||||||
#include "net.h"
|
#include "net.h"
|
||||||
#include "wallet.h"
|
#include "wallet.h"
|
||||||
|
|
||||||
using namespace std;
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
using namespace boost;
|
using namespace boost;
|
||||||
using namespace boost::assign;
|
using namespace boost::assign;
|
||||||
using namespace json_spirit;
|
|
||||||
|
|
||||||
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
|
void ScriptPubKeyToJSON(const CScript& scriptPubKey, json_spirit::Object& out)
|
||||||
{
|
{
|
||||||
txnouttype type;
|
txnouttype type;
|
||||||
vector<CTxDestination> addresses;
|
std::vector<CTxDestination> addresses;
|
||||||
int nRequired;
|
int nRequired;
|
||||||
|
|
||||||
out.push_back(Pair("asm", scriptPubKey.ToString()));
|
out.push_back(json_spirit::Pair("asm", scriptPubKey.ToString()));
|
||||||
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
|
out.push_back(json_spirit::Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
|
||||||
|
|
||||||
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
|
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
|
||||||
{
|
{
|
||||||
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
|
out.push_back(json_spirit::Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
out.push_back(Pair("reqSigs", nRequired));
|
out.push_back(json_spirit::Pair("reqSigs", nRequired));
|
||||||
out.push_back(Pair("type", GetTxnOutputType(type)));
|
out.push_back(json_spirit::Pair("type", GetTxnOutputType(type)));
|
||||||
|
|
||||||
Array a;
|
json_spirit::Array a;
|
||||||
BOOST_FOREACH(const CTxDestination& addr, addresses)
|
BOOST_FOREACH(const CTxDestination& addr, addresses)
|
||||||
a.push_back(CcurecoinAddress(addr).ToString());
|
a.push_back(CcurecoinAddress(addr).ToString());
|
||||||
out.push_back(Pair("addresses", a));
|
out.push_back(json_spirit::Pair("addresses", a));
|
||||||
}
|
}
|
||||||
|
|
||||||
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
|
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry)
|
||||||
{
|
{
|
||||||
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
|
entry.push_back(json_spirit::Pair("txid", tx.GetHash().GetHex()));
|
||||||
entry.push_back(Pair("version", tx.nVersion));
|
entry.push_back(json_spirit::Pair("version", tx.nVersion));
|
||||||
entry.push_back(Pair("time", (boost::int64_t)tx.nTime));
|
entry.push_back(json_spirit::Pair("time", (boost::int64_t)tx.nTime));
|
||||||
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
|
entry.push_back(json_spirit::Pair("locktime", (boost::int64_t)tx.nLockTime));
|
||||||
if (tx.nVersion >= 2)
|
if (tx.nVersion >= 2)
|
||||||
{
|
{
|
||||||
entry.push_back(Pair("tx-comment", tx.strTxComment));
|
entry.push_back(json_spirit::Pair("tx-comment", tx.strTxComment));
|
||||||
}
|
}
|
||||||
|
|
||||||
Array vin;
|
json_spirit::Array vin;
|
||||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||||
{
|
{
|
||||||
Object in;
|
json_spirit::Object in;
|
||||||
if (tx.IsCoinBase())
|
if (tx.IsCoinBase())
|
||||||
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
|
in.push_back(json_spirit::Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
|
in.push_back(json_spirit::Pair("txid", txin.prevout.hash.GetHex()));
|
||||||
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
|
in.push_back(json_spirit::Pair("vout", (boost::int64_t)txin.prevout.n));
|
||||||
Object o;
|
json_spirit::Object o;
|
||||||
o.push_back(Pair("asm", txin.scriptSig.ToString()));
|
o.push_back(json_spirit::Pair("asm", txin.scriptSig.ToString()));
|
||||||
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
|
o.push_back(json_spirit::Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
|
||||||
in.push_back(Pair("scriptSig", o));
|
in.push_back(json_spirit::Pair("scriptSig", o));
|
||||||
}
|
}
|
||||||
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
|
in.push_back(json_spirit::Pair("sequence", (boost::int64_t)txin.nSequence));
|
||||||
vin.push_back(in);
|
vin.push_back(in);
|
||||||
}
|
}
|
||||||
entry.push_back(Pair("vin", vin));
|
entry.push_back(json_spirit::Pair("vin", vin));
|
||||||
Array vout;
|
json_spirit::Array vout;
|
||||||
for (unsigned int i = 0; i < tx.vout.size(); i++)
|
for (unsigned int i = 0; i < tx.vout.size(); i++)
|
||||||
{
|
{
|
||||||
const CTxOut& txout = tx.vout[i];
|
const CTxOut& txout = tx.vout[i];
|
||||||
Object out;
|
json_spirit::Object out;
|
||||||
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
|
out.push_back(json_spirit::Pair("value", ValueFromAmount(txout.nValue)));
|
||||||
out.push_back(Pair("n", (boost::int64_t)i));
|
out.push_back(json_spirit::Pair("n", (boost::int64_t)i));
|
||||||
Object o;
|
json_spirit::Object o;
|
||||||
ScriptPubKeyToJSON(txout.scriptPubKey, o);
|
ScriptPubKeyToJSON(txout.scriptPubKey, o);
|
||||||
out.push_back(Pair("scriptPubKey", o));
|
out.push_back(json_spirit::Pair("scriptPubKey", o));
|
||||||
vout.push_back(out);
|
vout.push_back(out);
|
||||||
}
|
}
|
||||||
entry.push_back(Pair("vout", vout));
|
entry.push_back(json_spirit::Pair("vout", vout));
|
||||||
|
|
||||||
if (hashBlock != 0)
|
if (hashBlock != 0)
|
||||||
{
|
{
|
||||||
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
|
entry.push_back(json_spirit::Pair("blockhash", hashBlock.GetHex()));
|
||||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
||||||
if (mi != mapBlockIndex.end() && (*mi).second)
|
if (mi != mapBlockIndex.end() && (*mi).second)
|
||||||
{
|
{
|
||||||
CBlockIndex* pindex = (*mi).second;
|
CBlockIndex* pindex = (*mi).second;
|
||||||
if (pindex->IsInMainChain())
|
if (pindex->IsInMainChain())
|
||||||
{
|
{
|
||||||
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
|
entry.push_back(json_spirit::Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
|
||||||
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
|
entry.push_back(json_spirit::Pair("time", (boost::int64_t)pindex->nTime));
|
||||||
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
|
entry.push_back(json_spirit::Pair("blocktime", (boost::int64_t)pindex->nTime));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
entry.push_back(Pair("confirmations", 0));
|
entry.push_back(json_spirit::Pair("confirmations", 0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Value getrawtransaction(const Array& params, bool fHelp)
|
json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"getrawtransaction <txid> [verbose=0]\n"
|
"getrawtransaction <txid> [verbose=0]\n"
|
||||||
"If verbose=0, returns a string that is\n"
|
"If verbose=0, returns a string that is\n"
|
||||||
"serialized, hex-encoded data for <txid>.\n"
|
"serialized, hex-encoded data for <txid>.\n"
|
||||||
@ -129,21 +133,21 @@ Value getrawtransaction(const Array& params, bool fHelp)
|
|||||||
|
|
||||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||||
ssTx << tx;
|
ssTx << tx;
|
||||||
string strHex = HexStr(ssTx.begin(), ssTx.end());
|
std::string strHex = HexStr(ssTx.begin(), ssTx.end());
|
||||||
|
|
||||||
if (!fVerbose)
|
if (!fVerbose)
|
||||||
return strHex;
|
return strHex;
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
result.push_back(Pair("hex", strHex));
|
result.push_back(json_spirit::Pair("hex", strHex));
|
||||||
TxToJSON(tx, hashBlock, result);
|
TxToJSON(tx, hashBlock, result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value listunspent(const Array& params, bool fHelp)
|
json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() > 3)
|
if (fHelp || params.size() > 3)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
|
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
|
||||||
"Returns array of unspent transaction outputs\n"
|
"Returns array of unspent transaction outputs\n"
|
||||||
"with between minconf and maxconf (inclusive) confirmations.\n"
|
"with between minconf and maxconf (inclusive) confirmations.\n"
|
||||||
@ -151,7 +155,7 @@ Value listunspent(const Array& params, bool fHelp)
|
|||||||
"Results are an array of Objects, each of which has:\n"
|
"Results are an array of Objects, each of which has:\n"
|
||||||
"{txid, vout, scriptPubKey, amount, confirmations}");
|
"{txid, vout, scriptPubKey, amount, confirmations}");
|
||||||
|
|
||||||
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
|
RPCTypeCheck(params, list_of(json_spirit::int_type)(json_spirit::int_type)(json_spirit::array_type));
|
||||||
|
|
||||||
int nMinDepth = 1;
|
int nMinDepth = 1;
|
||||||
if (params.size() > 0)
|
if (params.size() > 0)
|
||||||
@ -161,23 +165,23 @@ Value listunspent(const Array& params, bool fHelp)
|
|||||||
if (params.size() > 1)
|
if (params.size() > 1)
|
||||||
nMaxDepth = params[1].get_int();
|
nMaxDepth = params[1].get_int();
|
||||||
|
|
||||||
set<CcurecoinAddress> setAddress;
|
std::set<CcurecoinAddress> setAddress;
|
||||||
if (params.size() > 2)
|
if (params.size() > 2)
|
||||||
{
|
{
|
||||||
Array inputs = params[2].get_array();
|
json_spirit::Array inputs = params[2].get_array();
|
||||||
BOOST_FOREACH(Value& input, inputs)
|
BOOST_FOREACH(json_spirit::Value& input, inputs)
|
||||||
{
|
{
|
||||||
CcurecoinAddress address(input.get_str());
|
CcurecoinAddress address(input.get_str());
|
||||||
if (!address.IsValid())
|
if (!address.IsValid())
|
||||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid curecoin address: ")+input.get_str());
|
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid curecoin address: ")+input.get_str());
|
||||||
if (setAddress.count(address))
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Array results;
|
json_spirit::Array results;
|
||||||
vector<COutput> vecOutputs;
|
std::vector<COutput> vecOutputs;
|
||||||
pwalletMain->AvailableCoins(vecOutputs, false);
|
pwalletMain->AvailableCoins(vecOutputs, false);
|
||||||
BOOST_FOREACH(const COutput& out, vecOutputs)
|
BOOST_FOREACH(const COutput& out, vecOutputs)
|
||||||
{
|
{
|
||||||
@ -196,22 +200,22 @@ Value listunspent(const Array& params, bool fHelp)
|
|||||||
|
|
||||||
int64 nValue = out.tx->vout[out.i].nValue;
|
int64 nValue = out.tx->vout[out.i].nValue;
|
||||||
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
|
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
|
||||||
Object entry;
|
json_spirit::Object entry;
|
||||||
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
|
entry.push_back(json_spirit::Pair("txid", out.tx->GetHash().GetHex()));
|
||||||
entry.push_back(Pair("vout", out.i));
|
entry.push_back(json_spirit::Pair("vout", out.i));
|
||||||
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
|
entry.push_back(json_spirit::Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
|
||||||
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
|
entry.push_back(json_spirit::Pair("amount",ValueFromAmount(nValue)));
|
||||||
entry.push_back(Pair("confirmations",out.nDepth));
|
entry.push_back(json_spirit::Pair("confirmations",out.nDepth));
|
||||||
results.push_back(entry);
|
results.push_back(entry);
|
||||||
}
|
}
|
||||||
|
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value createrawtransaction(const Array& params, bool fHelp)
|
json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 2)
|
if (fHelp || params.size() != 2)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
|
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
|
||||||
"Create a transaction spending given inputs\n"
|
"Create a transaction spending given inputs\n"
|
||||||
"(array of objects containing transaction id and output number),\n"
|
"(array of objects containing transaction id and output number),\n"
|
||||||
@ -220,26 +224,26 @@ Value createrawtransaction(const Array& params, bool fHelp)
|
|||||||
"Note that the transaction's inputs are not signed, and\n"
|
"Note that the transaction's inputs are not signed, and\n"
|
||||||
"it is not stored in the wallet or transmitted to the network.");
|
"it is not stored in the wallet or transmitted to the network.");
|
||||||
|
|
||||||
RPCTypeCheck(params, list_of(array_type)(obj_type));
|
RPCTypeCheck(params, list_of(json_spirit::array_type)(json_spirit::obj_type));
|
||||||
|
|
||||||
Array inputs = params[0].get_array();
|
json_spirit::Array inputs = params[0].get_array();
|
||||||
Object sendTo = params[1].get_obj();
|
json_spirit::Object sendTo = params[1].get_obj();
|
||||||
|
|
||||||
CTransaction rawTx;
|
CTransaction rawTx;
|
||||||
|
|
||||||
BOOST_FOREACH(Value& input, inputs)
|
BOOST_FOREACH(json_spirit::Value& input, inputs)
|
||||||
{
|
{
|
||||||
const Object& o = input.get_obj();
|
const json_spirit::Object& o = input.get_obj();
|
||||||
|
|
||||||
const Value& txid_v = find_value(o, "txid");
|
const json_spirit::Value& txid_v = find_value(o, "txid");
|
||||||
if (txid_v.type() != str_type)
|
if (txid_v.type() != json_spirit::str_type)
|
||||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
|
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
|
||||||
string txid = txid_v.get_str();
|
std::string txid = txid_v.get_str();
|
||||||
if (!IsHex(txid))
|
if (!IsHex(txid))
|
||||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
|
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
|
||||||
|
|
||||||
const Value& vout_v = find_value(o, "vout");
|
const json_spirit::Value& vout_v = find_value(o, "vout");
|
||||||
if (vout_v.type() != int_type)
|
if (vout_v.type() != json_spirit::int_type)
|
||||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
|
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
|
||||||
int nOutput = vout_v.get_int();
|
int nOutput = vout_v.get_int();
|
||||||
if (nOutput < 0)
|
if (nOutput < 0)
|
||||||
@ -249,15 +253,15 @@ Value createrawtransaction(const Array& params, bool fHelp)
|
|||||||
rawTx.vin.push_back(in);
|
rawTx.vin.push_back(in);
|
||||||
}
|
}
|
||||||
|
|
||||||
set<CcurecoinAddress> setAddress;
|
std::set<CcurecoinAddress> setAddress;
|
||||||
BOOST_FOREACH(const Pair& s, sendTo)
|
BOOST_FOREACH(const json_spirit::Pair& s, sendTo)
|
||||||
{
|
{
|
||||||
CcurecoinAddress address(s.name_);
|
CcurecoinAddress address(s.name_);
|
||||||
if (!address.IsValid())
|
if (!address.IsValid())
|
||||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid curecoin address: ")+s.name_);
|
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid curecoin address: ")+s.name_);
|
||||||
|
|
||||||
if (setAddress.count(address))
|
if (setAddress.count(address))
|
||||||
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
|
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+s.name_);
|
||||||
setAddress.insert(address);
|
setAddress.insert(address);
|
||||||
|
|
||||||
CScript scriptPubKey;
|
CScript scriptPubKey;
|
||||||
@ -273,16 +277,16 @@ Value createrawtransaction(const Array& params, bool fHelp)
|
|||||||
return HexStr(ss.begin(), ss.end());
|
return HexStr(ss.begin(), ss.end());
|
||||||
}
|
}
|
||||||
|
|
||||||
Value decoderawtransaction(const Array& params, bool fHelp)
|
json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() != 1)
|
if (fHelp || params.size() != 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"decoderawtransaction <hex string>\n"
|
"decoderawtransaction <hex string>\n"
|
||||||
"Return a JSON object representing the serialized, hex-encoded transaction.");
|
"Return a JSON object representing the serialized, hex-encoded transaction.");
|
||||||
|
|
||||||
RPCTypeCheck(params, list_of(str_type));
|
RPCTypeCheck(params, list_of(json_spirit::str_type));
|
||||||
|
|
||||||
vector<unsigned char> txData(ParseHex(params[0].get_str()));
|
std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
|
||||||
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
||||||
CTransaction tx;
|
CTransaction tx;
|
||||||
try {
|
try {
|
||||||
@ -292,16 +296,16 @@ Value decoderawtransaction(const Array& params, bool fHelp)
|
|||||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
|
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
TxToJSON(tx, 0, result);
|
TxToJSON(tx, 0, result);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value signrawtransaction(const Array& params, bool fHelp)
|
json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 4)
|
if (fHelp || params.size() < 1 || params.size() > 4)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
|
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
|
||||||
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
|
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
|
||||||
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
|
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
|
||||||
@ -315,11 +319,11 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
" complete : 1 if transaction has a complete set of signature (0 if not)"
|
" complete : 1 if transaction has a complete set of signature (0 if not)"
|
||||||
+ HelpRequiringPassphrase());
|
+ HelpRequiringPassphrase());
|
||||||
|
|
||||||
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
|
RPCTypeCheck(params, list_of(json_spirit::str_type)(json_spirit::array_type)(json_spirit::array_type)(json_spirit::str_type), true);
|
||||||
|
|
||||||
vector<unsigned char> txData(ParseHex(params[0].get_str()));
|
std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
|
||||||
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
||||||
vector<CTransaction> txVariants;
|
std::vector<CTransaction> txVariants;
|
||||||
while (!ssData.empty())
|
while (!ssData.empty())
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
@ -341,13 +345,13 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
bool fComplete = true;
|
bool fComplete = true;
|
||||||
|
|
||||||
// Fetch previous transactions (inputs):
|
// Fetch previous transactions (inputs):
|
||||||
map<COutPoint, CScript> mapPrevOut;
|
std::map<COutPoint, CScript> mapPrevOut;
|
||||||
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
|
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
|
||||||
{
|
{
|
||||||
CTransaction tempTx;
|
CTransaction tempTx;
|
||||||
MapPrevTx mapPrevTx;
|
MapPrevTx mapPrevTx;
|
||||||
CTxDB txdb("r");
|
CTxDB txdb("r");
|
||||||
map<uint256, CTxIndex> unused;
|
std::map<uint256, CTxIndex> unused;
|
||||||
bool fInvalid;
|
bool fInvalid;
|
||||||
|
|
||||||
// FetchInputs aborts on failure, so we go one at a time.
|
// FetchInputs aborts on failure, so we go one at a time.
|
||||||
@ -364,19 +368,19 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add previous txouts given in the RPC call:
|
// Add previous txouts given in the RPC call:
|
||||||
if (params.size() > 1 && params[1].type() != null_type)
|
if (params.size() > 1 && params[1].type() != json_spirit::null_type)
|
||||||
{
|
{
|
||||||
Array prevTxs = params[1].get_array();
|
json_spirit::Array prevTxs = params[1].get_array();
|
||||||
BOOST_FOREACH(Value& p, prevTxs)
|
BOOST_FOREACH(json_spirit::Value& p, prevTxs)
|
||||||
{
|
{
|
||||||
if (p.type() != obj_type)
|
if (p.type() != json_spirit::obj_type)
|
||||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
|
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
|
||||||
|
|
||||||
Object prevOut = p.get_obj();
|
json_spirit::Object prevOut = p.get_obj();
|
||||||
|
|
||||||
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
|
RPCTypeCheck(prevOut, map_list_of("txid", json_spirit::str_type)("vout", json_spirit::int_type)("scriptPubKey", json_spirit::str_type));
|
||||||
|
|
||||||
string txidHex = find_value(prevOut, "txid").get_str();
|
std::string txidHex = find_value(prevOut, "txid").get_str();
|
||||||
if (!IsHex(txidHex))
|
if (!IsHex(txidHex))
|
||||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
|
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
|
||||||
uint256 txid;
|
uint256 txid;
|
||||||
@ -386,10 +390,10 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
if (nOut < 0)
|
if (nOut < 0)
|
||||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
|
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
|
||||||
|
|
||||||
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
|
std::string pkHex = find_value(prevOut, "scriptPubKey").get_str();
|
||||||
if (!IsHex(pkHex))
|
if (!IsHex(pkHex))
|
||||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
|
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
|
||||||
vector<unsigned char> pkData(ParseHex(pkHex));
|
std::vector<unsigned char> pkData(ParseHex(pkHex));
|
||||||
CScript scriptPubKey(pkData.begin(), pkData.end());
|
CScript scriptPubKey(pkData.begin(), pkData.end());
|
||||||
|
|
||||||
COutPoint outpoint(txid, nOut);
|
COutPoint outpoint(txid, nOut);
|
||||||
@ -398,7 +402,7 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
// Complain if scriptPubKey doesn't match
|
// Complain if scriptPubKey doesn't match
|
||||||
if (mapPrevOut[outpoint] != scriptPubKey)
|
if (mapPrevOut[outpoint] != scriptPubKey)
|
||||||
{
|
{
|
||||||
string err("Previous output scriptPubKey mismatch:\n");
|
std::string err("Previous output scriptPubKey mismatch:\n");
|
||||||
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
|
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
|
||||||
scriptPubKey.ToString();
|
scriptPubKey.ToString();
|
||||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
|
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
|
||||||
@ -411,11 +415,11 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
|
|
||||||
bool fGivenKeys = false;
|
bool fGivenKeys = false;
|
||||||
CBasicKeyStore tempKeystore;
|
CBasicKeyStore tempKeystore;
|
||||||
if (params.size() > 2 && params[2].type() != null_type)
|
if (params.size() > 2 && params[2].type() != json_spirit::null_type)
|
||||||
{
|
{
|
||||||
fGivenKeys = true;
|
fGivenKeys = true;
|
||||||
Array keys = params[2].get_array();
|
json_spirit::Array keys = params[2].get_array();
|
||||||
BOOST_FOREACH(Value k, keys)
|
BOOST_FOREACH(json_spirit::Value k, keys)
|
||||||
{
|
{
|
||||||
CcurecoinSecret vchSecret;
|
CcurecoinSecret vchSecret;
|
||||||
bool fGood = vchSecret.SetString(k.get_str());
|
bool fGood = vchSecret.SetString(k.get_str());
|
||||||
@ -434,18 +438,18 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
|
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
|
||||||
|
|
||||||
int nHashType = SIGHASH_ALL;
|
int nHashType = SIGHASH_ALL;
|
||||||
if (params.size() > 3 && params[3].type() != null_type)
|
if (params.size() > 3 && params[3].type() != json_spirit::null_type)
|
||||||
{
|
{
|
||||||
static map<string, int> mapSigHashValues =
|
static std::map<std::string, int> mapSigHashValues =
|
||||||
boost::assign::map_list_of
|
boost::assign::map_list_of
|
||||||
(string("ALL"), int(SIGHASH_ALL))
|
(std::string("ALL"), int(SIGHASH_ALL))
|
||||||
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
|
(std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
|
||||||
(string("NONE"), int(SIGHASH_NONE))
|
(std::string("NONE"), int(SIGHASH_NONE))
|
||||||
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
|
(std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
|
||||||
(string("SINGLE"), int(SIGHASH_SINGLE))
|
(std::string("SINGLE"), int(SIGHASH_SINGLE))
|
||||||
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
|
(std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
|
||||||
;
|
;
|
||||||
string strHashType = params[3].get_str();
|
std::string strHashType = params[3].get_str();
|
||||||
if (mapSigHashValues.count(strHashType))
|
if (mapSigHashValues.count(strHashType))
|
||||||
nHashType = mapSigHashValues[strHashType];
|
nHashType = mapSigHashValues[strHashType];
|
||||||
else
|
else
|
||||||
@ -479,26 +483,26 @@ Value signrawtransaction(const Array& params, bool fHelp)
|
|||||||
fComplete = false;
|
fComplete = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Object result;
|
json_spirit::Object result;
|
||||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||||
ssTx << mergedTx;
|
ssTx << mergedTx;
|
||||||
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
|
result.push_back(json_spirit::Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
|
||||||
result.push_back(Pair("complete", fComplete));
|
result.push_back(json_spirit::Pair("complete", fComplete));
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
Value sendrawtransaction(const Array& params, bool fHelp)
|
json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp)
|
||||||
{
|
{
|
||||||
if (fHelp || params.size() < 1 || params.size() > 1)
|
if (fHelp || params.size() < 1 || params.size() > 1)
|
||||||
throw runtime_error(
|
throw std::runtime_error(
|
||||||
"sendrawtransaction <hex string>\n"
|
"sendrawtransaction <hex string>\n"
|
||||||
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
|
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
|
||||||
|
|
||||||
RPCTypeCheck(params, list_of(str_type));
|
RPCTypeCheck(params, list_of(json_spirit::str_type));
|
||||||
|
|
||||||
// parse hex string from parameter
|
// parse hex string from parameter
|
||||||
vector<unsigned char> txData(ParseHex(params[0].get_str()));
|
std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
|
||||||
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
||||||
CTransaction tx;
|
CTransaction tx;
|
||||||
|
|
||||||
@ -518,7 +522,7 @@ Value sendrawtransaction(const Array& params, bool fHelp)
|
|||||||
if (GetTransaction(hashTx, existingTx, hashBlock))
|
if (GetTransaction(hashTx, existingTx, hashBlock))
|
||||||
{
|
{
|
||||||
if (hashBlock != 0)
|
if (hashBlock != 0)
|
||||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex());
|
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("transaction already in block ")+hashBlock.GetHex());
|
||||||
// Not in block, but already in the memory pool; will drop
|
// Not in block, but already in the memory pool; will drop
|
||||||
// through to re-relay it.
|
// through to re-relay it.
|
||||||
}
|
}
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -5,7 +5,6 @@
|
|||||||
#include <boost/foreach.hpp>
|
#include <boost/foreach.hpp>
|
||||||
#include <boost/tuple/tuple.hpp>
|
#include <boost/tuple/tuple.hpp>
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
using namespace boost;
|
using namespace boost;
|
||||||
|
|
||||||
#include "script.h"
|
#include "script.h"
|
||||||
@ -16,7 +15,12 @@ using namespace boost;
|
|||||||
#include "sync.h"
|
#include "sync.h"
|
||||||
#include "util.h"
|
#include "util.h"
|
||||||
|
|
||||||
bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
|
#include <map>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <set>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
bool CheckSig(std::vector<unsigned char> vchSig, std::vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
|
||||||
|
|
||||||
static const valtype vchFalse(0);
|
static const valtype vchFalse(0);
|
||||||
static const valtype vchZero(0);
|
static const valtype vchZero(0);
|
||||||
@ -31,7 +35,7 @@ static const size_t nMaxNumSize = 4;
|
|||||||
CBigNum CastToBigNum(const valtype& vch)
|
CBigNum CastToBigNum(const valtype& vch)
|
||||||
{
|
{
|
||||||
if (vch.size() > nMaxNumSize)
|
if (vch.size() > nMaxNumSize)
|
||||||
throw runtime_error("CastToBigNum() : overflow");
|
throw std::runtime_error("CastToBigNum() : overflow");
|
||||||
// Get rid of extra leading zeros
|
// Get rid of extra leading zeros
|
||||||
return CBigNum(CBigNum(vch).getvch());
|
return CBigNum(CBigNum(vch).getvch());
|
||||||
}
|
}
|
||||||
@ -85,10 +89,10 @@ void MakeSameSize(valtype& vch1, valtype& vch2)
|
|||||||
//
|
//
|
||||||
#define stacktop(i) (stack.at(stack.size()+(i)))
|
#define stacktop(i) (stack.at(stack.size()+(i)))
|
||||||
#define altstacktop(i) (altstack.at(altstack.size()+(i)))
|
#define altstacktop(i) (altstack.at(altstack.size()+(i)))
|
||||||
static inline void popstack(vector<valtype>& stack)
|
static inline void popstack(std::vector<valtype>& stack)
|
||||||
{
|
{
|
||||||
if (stack.empty())
|
if (stack.empty())
|
||||||
throw runtime_error("popstack() : stack empty");
|
throw std::runtime_error("popstack() : stack empty");
|
||||||
stack.pop_back();
|
stack.pop_back();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -250,7 +254,7 @@ const char* GetOpName(opcodetype opcode)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
|
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
|
||||||
{
|
{
|
||||||
CAutoBN_CTX pctx;
|
CAutoBN_CTX pctx;
|
||||||
CScript::const_iterator pc = script.begin();
|
CScript::const_iterator pc = script.begin();
|
||||||
@ -258,8 +262,8 @@ bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, co
|
|||||||
CScript::const_iterator pbegincodehash = script.begin();
|
CScript::const_iterator pbegincodehash = script.begin();
|
||||||
opcodetype opcode;
|
opcodetype opcode;
|
||||||
valtype vchPushValue;
|
valtype vchPushValue;
|
||||||
vector<bool> vfExec;
|
std::vector<bool> vfExec;
|
||||||
vector<valtype> altstack;
|
std::vector<valtype> altstack;
|
||||||
if (script.size() > 10000)
|
if (script.size() > 10000)
|
||||||
return false;
|
return false;
|
||||||
int nOpCount = 0;
|
int nOpCount = 0;
|
||||||
@ -1177,7 +1181,7 @@ public:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
|
bool CheckSig(std::vector<unsigned char> vchSig, std::vector<unsigned char> vchPubKey, CScript scriptCode,
|
||||||
const CTransaction& txTo, unsigned int nIn, int nHashType)
|
const CTransaction& txTo, unsigned int nIn, int nHashType)
|
||||||
{
|
{
|
||||||
static CSignatureCache signatureCache;
|
static CSignatureCache signatureCache;
|
||||||
@ -1218,10 +1222,10 @@ bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CSc
|
|||||||
//
|
//
|
||||||
// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
|
// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
|
||||||
//
|
//
|
||||||
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
|
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
|
||||||
{
|
{
|
||||||
// Templates
|
// Templates
|
||||||
static map<txnouttype, CScript> mTemplates;
|
static std::map<txnouttype, CScript> mTemplates;
|
||||||
if (mTemplates.empty())
|
if (mTemplates.empty())
|
||||||
{
|
{
|
||||||
// Standard tx, sender provides pubkey, receiver adds signature
|
// Standard tx, sender provides pubkey, receiver adds signature
|
||||||
@ -1239,7 +1243,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
|
|||||||
if (scriptPubKey.IsPayToScriptHash())
|
if (scriptPubKey.IsPayToScriptHash())
|
||||||
{
|
{
|
||||||
typeRet = TX_SCRIPTHASH;
|
typeRet = TX_SCRIPTHASH;
|
||||||
vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
|
std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
|
||||||
vSolutionsRet.push_back(hashBytes);
|
vSolutionsRet.push_back(hashBytes);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -1252,7 +1256,7 @@ bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsi
|
|||||||
vSolutionsRet.clear();
|
vSolutionsRet.clear();
|
||||||
|
|
||||||
opcodetype opcode1, opcode2;
|
opcodetype opcode1, opcode2;
|
||||||
vector<unsigned char> vch1, vch2;
|
std::vector<unsigned char> vch1, vch2;
|
||||||
|
|
||||||
// Compare
|
// Compare
|
||||||
CScript::const_iterator pc1 = script1.begin();
|
CScript::const_iterator pc1 = script1.begin();
|
||||||
@ -1336,7 +1340,7 @@ bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int n
|
|||||||
if (!keystore.GetKey(address, key))
|
if (!keystore.GetKey(address, key))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
vector<unsigned char> vchSig;
|
std::vector<unsigned char> vchSig;
|
||||||
if (!key.Sign(hash, vchSig))
|
if (!key.Sign(hash, vchSig))
|
||||||
return false;
|
return false;
|
||||||
vchSig.push_back((unsigned char)nHashType);
|
vchSig.push_back((unsigned char)nHashType);
|
||||||
@ -1345,7 +1349,7 @@ bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int n
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
|
bool SignN(const std::vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
|
||||||
{
|
{
|
||||||
int nSigned = 0;
|
int nSigned = 0;
|
||||||
int nRequired = multisigdata.front()[0];
|
int nRequired = multisigdata.front()[0];
|
||||||
@ -1370,7 +1374,7 @@ bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash
|
|||||||
{
|
{
|
||||||
scriptSigRet.clear();
|
scriptSigRet.clear();
|
||||||
|
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
|
if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -1425,7 +1429,7 @@ int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned c
|
|||||||
|
|
||||||
bool IsStandard(const CScript& scriptPubKey)
|
bool IsStandard(const CScript& scriptPubKey)
|
||||||
{
|
{
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
if (!Solver(scriptPubKey, whichType, vSolutions))
|
if (!Solver(scriptPubKey, whichType, vSolutions))
|
||||||
return false;
|
return false;
|
||||||
@ -1445,7 +1449,7 @@ bool IsStandard(const CScript& scriptPubKey)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
|
unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
|
||||||
{
|
{
|
||||||
unsigned int nResult = 0;
|
unsigned int nResult = 0;
|
||||||
BOOST_FOREACH(const valtype& pubkey, pubkeys)
|
BOOST_FOREACH(const valtype& pubkey, pubkeys)
|
||||||
@ -1476,7 +1480,7 @@ bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
|
|||||||
|
|
||||||
bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
|
bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
|
||||||
{
|
{
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
if (!Solver(scriptPubKey, whichType, vSolutions))
|
if (!Solver(scriptPubKey, whichType, vSolutions))
|
||||||
return false;
|
return false;
|
||||||
@ -1506,7 +1510,7 @@ bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
|
|||||||
// partially owned (somebody else has a key that can spend
|
// partially owned (somebody else has a key that can spend
|
||||||
// them) enable spend-out-from-under-you attacks, especially
|
// them) enable spend-out-from-under-you attacks, especially
|
||||||
// in shared-wallet situations.
|
// in shared-wallet situations.
|
||||||
vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
|
std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
|
||||||
return HaveKeys(keys, keystore) == keys.size();
|
return HaveKeys(keys, keystore) == keys.size();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1515,7 +1519,7 @@ bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
|
|||||||
|
|
||||||
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
|
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
|
||||||
{
|
{
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
if (!Solver(scriptPubKey, whichType, vSolutions))
|
if (!Solver(scriptPubKey, whichType, vSolutions))
|
||||||
return false;
|
return false;
|
||||||
@ -1539,11 +1543,11 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
|
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
|
||||||
{
|
{
|
||||||
addressRet.clear();
|
addressRet.clear();
|
||||||
typeRet = TX_NONSTANDARD;
|
typeRet = TX_NONSTANDARD;
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
if (!Solver(scriptPubKey, typeRet, vSolutions))
|
if (!Solver(scriptPubKey, typeRet, vSolutions))
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
@ -1571,7 +1575,7 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vecto
|
|||||||
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
|
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
|
||||||
bool fValidatePayToScriptHash, int nHashType)
|
bool fValidatePayToScriptHash, int nHashType)
|
||||||
{
|
{
|
||||||
vector<vector<unsigned char> > stack, stackCopy;
|
std::vector<std::vector<unsigned char> > stack, stackCopy;
|
||||||
if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
|
if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
|
||||||
return false;
|
return false;
|
||||||
if (fValidatePayToScriptHash)
|
if (fValidatePayToScriptHash)
|
||||||
@ -1665,7 +1669,7 @@ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsig
|
|||||||
return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
|
return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
|
||||||
}
|
}
|
||||||
|
|
||||||
static CScript PushAll(const vector<valtype>& values)
|
static CScript PushAll(const std::vector<valtype>& values)
|
||||||
{
|
{
|
||||||
CScript result;
|
CScript result;
|
||||||
BOOST_FOREACH(const valtype& v, values)
|
BOOST_FOREACH(const valtype& v, values)
|
||||||
@ -1674,11 +1678,11 @@ static CScript PushAll(const vector<valtype>& values)
|
|||||||
}
|
}
|
||||||
|
|
||||||
static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
|
static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
|
||||||
const vector<valtype>& vSolutions,
|
const std::vector<valtype>& vSolutions,
|
||||||
vector<valtype>& sigs1, vector<valtype>& sigs2)
|
std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
|
||||||
{
|
{
|
||||||
// Combine all the signatures we've got:
|
// Combine all the signatures we've got:
|
||||||
set<valtype> allsigs;
|
std::set<valtype> allsigs;
|
||||||
BOOST_FOREACH(const valtype& v, sigs1)
|
BOOST_FOREACH(const valtype& v, sigs1)
|
||||||
{
|
{
|
||||||
if (!v.empty())
|
if (!v.empty())
|
||||||
@ -1694,7 +1698,7 @@ static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, u
|
|||||||
assert(vSolutions.size() > 1);
|
assert(vSolutions.size() > 1);
|
||||||
unsigned int nSigsRequired = vSolutions.front()[0];
|
unsigned int nSigsRequired = vSolutions.front()[0];
|
||||||
unsigned int nPubKeys = vSolutions.size()-2;
|
unsigned int nPubKeys = vSolutions.size()-2;
|
||||||
map<valtype, valtype> sigs;
|
std::map<valtype, valtype> sigs;
|
||||||
BOOST_FOREACH(const valtype& sig, allsigs)
|
BOOST_FOREACH(const valtype& sig, allsigs)
|
||||||
{
|
{
|
||||||
for (unsigned int i = 0; i < nPubKeys; i++)
|
for (unsigned int i = 0; i < nPubKeys; i++)
|
||||||
@ -1729,8 +1733,8 @@ static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, u
|
|||||||
}
|
}
|
||||||
|
|
||||||
static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
|
static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
|
||||||
const txnouttype txType, const vector<valtype>& vSolutions,
|
const txnouttype txType, const std::vector<valtype>& vSolutions,
|
||||||
vector<valtype>& sigs1, vector<valtype>& sigs2)
|
std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
|
||||||
{
|
{
|
||||||
switch (txType)
|
switch (txType)
|
||||||
{
|
{
|
||||||
@ -1757,7 +1761,7 @@ static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo,
|
|||||||
CScript pubKey2(spk.begin(), spk.end());
|
CScript pubKey2(spk.begin(), spk.end());
|
||||||
|
|
||||||
txnouttype txType2;
|
txnouttype txType2;
|
||||||
vector<vector<unsigned char> > vSolutions2;
|
std::vector<std::vector<unsigned char> > vSolutions2;
|
||||||
Solver(pubKey2, txType2, vSolutions2);
|
Solver(pubKey2, txType2, vSolutions2);
|
||||||
sigs1.pop_back();
|
sigs1.pop_back();
|
||||||
sigs2.pop_back();
|
sigs2.pop_back();
|
||||||
@ -1776,12 +1780,12 @@ CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsign
|
|||||||
const CScript& scriptSig1, const CScript& scriptSig2)
|
const CScript& scriptSig1, const CScript& scriptSig2)
|
||||||
{
|
{
|
||||||
txnouttype txType;
|
txnouttype txType;
|
||||||
vector<vector<unsigned char> > vSolutions;
|
std::vector<std::vector<unsigned char> > vSolutions;
|
||||||
Solver(scriptPubKey, txType, vSolutions);
|
Solver(scriptPubKey, txType, vSolutions);
|
||||||
|
|
||||||
vector<valtype> stack1;
|
std::vector<valtype> stack1;
|
||||||
EvalScript(stack1, scriptSig1, CTransaction(), 0, 0);
|
EvalScript(stack1, scriptSig1, CTransaction(), 0, 0);
|
||||||
vector<valtype> stack2;
|
std::vector<valtype> stack2;
|
||||||
EvalScript(stack2, scriptSig2, CTransaction(), 0, 0);
|
EvalScript(stack2, scriptSig2, CTransaction(), 0, 0);
|
||||||
|
|
||||||
return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
|
return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
|
||||||
@ -1820,7 +1824,7 @@ unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
|
|||||||
// get the last item that the scriptSig
|
// get the last item that the scriptSig
|
||||||
// pushes onto the stack:
|
// pushes onto the stack:
|
||||||
const_iterator pc = scriptSig.begin();
|
const_iterator pc = scriptSig.begin();
|
||||||
vector<unsigned char> data;
|
std::vector<unsigned char> data;
|
||||||
while (pc < scriptSig.end())
|
while (pc < scriptSig.end())
|
||||||
{
|
{
|
||||||
opcodetype opcode;
|
opcodetype opcode;
|
||||||
|
@ -449,6 +449,12 @@ public:
|
|||||||
CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
|
CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
CScript& operator=(const CScript& b)
|
||||||
|
{
|
||||||
|
assign(b.begin(), b.end());
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
CScript& operator+=(const CScript& b)
|
CScript& operator+=(const CScript& b)
|
||||||
{
|
{
|
||||||
insert(end(), b.begin(), b.end());
|
insert(end(), b.begin(), b.end());
|
||||||
|
@ -818,7 +818,7 @@ public:
|
|||||||
{
|
{
|
||||||
// special case for inserting at the front when there's room
|
// special case for inserting at the front when there's room
|
||||||
nReadPos -= (last - first);
|
nReadPos -= (last - first);
|
||||||
memcpy(&vch[nReadPos], &first[0], last - first);
|
std::memcpy(&vch[nReadPos], &first[0], last - first);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
vch.insert(it, first, last);
|
vch.insert(it, first, last);
|
||||||
@ -831,7 +831,7 @@ public:
|
|||||||
{
|
{
|
||||||
// special case for inserting at the front when there's room
|
// special case for inserting at the front when there's room
|
||||||
nReadPos -= (last - first);
|
nReadPos -= (last - first);
|
||||||
memcpy(&vch[nReadPos], &first[0], last - first);
|
std::memcpy(&vch[nReadPos], &first[0], last - first);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
vch.insert(it, first, last);
|
vch.insert(it, first, last);
|
||||||
@ -845,7 +845,7 @@ public:
|
|||||||
{
|
{
|
||||||
// special case for inserting at the front when there's room
|
// special case for inserting at the front when there's room
|
||||||
nReadPos -= (last - first);
|
nReadPos -= (last - first);
|
||||||
memcpy(&vch[nReadPos], &first[0], last - first);
|
std::memcpy(&vch[nReadPos], &first[0], last - first);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
vch.insert(it, first, last);
|
vch.insert(it, first, last);
|
||||||
@ -941,15 +941,15 @@ public:
|
|||||||
if (nReadPosNext > vch.size())
|
if (nReadPosNext > vch.size())
|
||||||
{
|
{
|
||||||
setstate(std::ios::failbit, "CDataStream::read() : end of data");
|
setstate(std::ios::failbit, "CDataStream::read() : end of data");
|
||||||
memset(pch, 0, nSize);
|
std::memset(pch, 0, nSize);
|
||||||
nSize = vch.size() - nReadPos;
|
nSize = vch.size() - nReadPos;
|
||||||
}
|
}
|
||||||
memcpy(pch, &vch[nReadPos], nSize);
|
std::memcpy(pch, &vch[nReadPos], nSize);
|
||||||
nReadPos = 0;
|
nReadPos = 0;
|
||||||
vch.clear();
|
vch.clear();
|
||||||
return (*this);
|
return (*this);
|
||||||
}
|
}
|
||||||
memcpy(pch, &vch[nReadPos], nSize);
|
std::memcpy(pch, &vch[nReadPos], nSize);
|
||||||
nReadPos = nReadPosNext;
|
nReadPos = nReadPosNext;
|
||||||
return (*this);
|
return (*this);
|
||||||
}
|
}
|
||||||
|
118
src/util.cpp
118
src/util.cpp
@ -10,6 +10,13 @@
|
|||||||
#include "ui_interface.h"
|
#include "ui_interface.h"
|
||||||
#include <boost/algorithm/string/join.hpp>
|
#include <boost/algorithm/string/join.hpp>
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
// Work around clang compilation problem in Boost 1.46:
|
// Work around clang compilation problem in Boost 1.46:
|
||||||
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
|
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
|
||||||
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
|
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
|
||||||
@ -60,10 +67,9 @@ namespace boost {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
|
|
||||||
map<string, string> mapArgs;
|
std::map<std::string, std::string> mapArgs;
|
||||||
map<string, vector<string> > mapMultiArgs;
|
std::map<std::string, std::vector<std::string> > mapMultiArgs;
|
||||||
bool fDebug = false;
|
bool fDebug = false;
|
||||||
bool fDebugNet = false;
|
bool fDebugNet = false;
|
||||||
bool fPrintToConsole = false;
|
bool fPrintToConsole = false;
|
||||||
@ -73,7 +79,7 @@ bool fShutdown = false;
|
|||||||
bool fDaemon = false;
|
bool fDaemon = false;
|
||||||
bool fServer = false;
|
bool fServer = false;
|
||||||
bool fCommandLine = false;
|
bool fCommandLine = false;
|
||||||
string strMiscWarning;
|
std::string strMiscWarning;
|
||||||
bool fTestNet = false;
|
bool fTestNet = false;
|
||||||
bool fNoListen = false;
|
bool fNoListen = false;
|
||||||
bool fLogTimestamps = false;
|
bool fLogTimestamps = false;
|
||||||
@ -136,7 +142,7 @@ void RandAddSeed()
|
|||||||
// Seed with CPU performance counter
|
// Seed with CPU performance counter
|
||||||
int64 nCounter = GetPerformanceCounter();
|
int64 nCounter = GetPerformanceCounter();
|
||||||
RAND_add(&nCounter, sizeof(nCounter), 1.5);
|
RAND_add(&nCounter, sizeof(nCounter), 1.5);
|
||||||
memset(&nCounter, 0, sizeof(nCounter));
|
std::memset(&nCounter, 0, sizeof(nCounter));
|
||||||
}
|
}
|
||||||
|
|
||||||
void RandAddSeedPerfmon()
|
void RandAddSeedPerfmon()
|
||||||
@ -153,14 +159,14 @@ void RandAddSeedPerfmon()
|
|||||||
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
|
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
|
||||||
// Seed with the entire set of perfmon data
|
// Seed with the entire set of perfmon data
|
||||||
unsigned char pdata[250000];
|
unsigned char pdata[250000];
|
||||||
memset(pdata, 0, sizeof(pdata));
|
std::memset(pdata, 0, sizeof(pdata));
|
||||||
unsigned long nSize = sizeof(pdata);
|
unsigned long nSize = sizeof(pdata);
|
||||||
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
|
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
|
||||||
RegCloseKey(HKEY_PERFORMANCE_DATA);
|
RegCloseKey(HKEY_PERFORMANCE_DATA);
|
||||||
if (ret == ERROR_SUCCESS)
|
if (ret == ERROR_SUCCESS)
|
||||||
{
|
{
|
||||||
RAND_add(pdata, nSize, nSize/100.0);
|
RAND_add(pdata, nSize, nSize/100.0);
|
||||||
memset(pdata, 0, nSize);
|
std::memset(pdata, 0, nSize);
|
||||||
printf("RandAddSeed() %lu bytes\n", nSize);
|
printf("RandAddSeed() %lu bytes\n", nSize);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@ -284,7 +290,7 @@ inline int OutputDebugStringF(const char* pszFormat, ...)
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
string vstrprintf(const char *format, va_list ap)
|
std::string vstrprintf(const char *format, va_list ap)
|
||||||
{
|
{
|
||||||
char buffer[50000];
|
char buffer[50000];
|
||||||
char* p = buffer;
|
char* p = buffer;
|
||||||
@ -309,26 +315,26 @@ string vstrprintf(const char *format, va_list ap)
|
|||||||
if (p == NULL)
|
if (p == NULL)
|
||||||
throw std::bad_alloc();
|
throw std::bad_alloc();
|
||||||
}
|
}
|
||||||
string str(p, p+ret);
|
std::string str(p, p+ret);
|
||||||
if (p != buffer)
|
if (p != buffer)
|
||||||
delete[] p;
|
delete[] p;
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|
||||||
string real_strprintf(const char *format, int dummy, ...)
|
std::string real_strprintf(const char *format, int dummy, ...)
|
||||||
{
|
{
|
||||||
va_list arg_ptr;
|
va_list arg_ptr;
|
||||||
va_start(arg_ptr, dummy);
|
va_start(arg_ptr, dummy);
|
||||||
string str = vstrprintf(format, arg_ptr);
|
std::string str = vstrprintf(format, arg_ptr);
|
||||||
va_end(arg_ptr);
|
va_end(arg_ptr);
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|
||||||
string real_strprintf(const std::string &format, int dummy, ...)
|
std::string real_strprintf(const std::string &format, int dummy, ...)
|
||||||
{
|
{
|
||||||
va_list arg_ptr;
|
va_list arg_ptr;
|
||||||
va_start(arg_ptr, dummy);
|
va_start(arg_ptr, dummy);
|
||||||
string str = vstrprintf(format.c_str(), arg_ptr);
|
std::string str = vstrprintf(format.c_str(), arg_ptr);
|
||||||
va_end(arg_ptr);
|
va_end(arg_ptr);
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
@ -344,12 +350,12 @@ bool error(const char *format, ...)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void ParseString(const string& str, char c, vector<string>& v)
|
void ParseString(const std::string& str, char c, std::vector<std::string>& v)
|
||||||
{
|
{
|
||||||
if (str.empty())
|
if (str.empty())
|
||||||
return;
|
return;
|
||||||
string::size_type i1 = 0;
|
std::string::size_type i1 = 0;
|
||||||
string::size_type i2;
|
std::string::size_type i2;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
i2 = str.find(c, i1);
|
i2 = str.find(c, i1);
|
||||||
@ -364,14 +370,14 @@ void ParseString(const string& str, char c, vector<string>& v)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
string FormatMoney(int64 n, bool fPlus)
|
std::string FormatMoney(int64 n, bool fPlus)
|
||||||
{
|
{
|
||||||
// Note: not using straight sprintf here because we do NOT want
|
// Note: not using straight sprintf here because we do NOT want
|
||||||
// localized number formatting.
|
// localized number formatting.
|
||||||
int64 n_abs = (n > 0 ? n : -n);
|
int64 n_abs = (n > 0 ? n : -n);
|
||||||
int64 quotient = n_abs/COIN;
|
int64 quotient = n_abs/COIN;
|
||||||
int64 remainder = n_abs%COIN;
|
int64 remainder = n_abs%COIN;
|
||||||
string str = strprintf("%"PRI64d".%06"PRI64d, quotient, remainder);
|
std::string str = strprintf("%" PRI64d ".%06" PRI64d, quotient, remainder);
|
||||||
|
|
||||||
// Right-trim excess zeros before the decimal point:
|
// Right-trim excess zeros before the decimal point:
|
||||||
int nTrim = 0;
|
int nTrim = 0;
|
||||||
@ -388,14 +394,14 @@ string FormatMoney(int64 n, bool fPlus)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
bool ParseMoney(const string& str, int64& nRet)
|
bool ParseMoney(const std::string& str, int64& nRet)
|
||||||
{
|
{
|
||||||
return ParseMoney(str.c_str(), nRet);
|
return ParseMoney(str.c_str(), nRet);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool ParseMoney(const char* pszIn, int64& nRet)
|
bool ParseMoney(const char* pszIn, int64& nRet)
|
||||||
{
|
{
|
||||||
string strWhole;
|
std::string strWhole;
|
||||||
int64 nUnits = 0;
|
int64 nUnits = 0;
|
||||||
const char* p = pszIn;
|
const char* p = pszIn;
|
||||||
while (isspace(*p))
|
while (isspace(*p))
|
||||||
@ -452,7 +458,7 @@ static const signed char phexdigit[256] =
|
|||||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
|
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
|
||||||
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
|
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
|
||||||
|
|
||||||
bool IsHex(const string& str)
|
bool IsHex(const std::string& str)
|
||||||
{
|
{
|
||||||
BOOST_FOREACH(unsigned char c, str)
|
BOOST_FOREACH(unsigned char c, str)
|
||||||
{
|
{
|
||||||
@ -462,10 +468,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))
|
||||||
@ -483,12 +489,12 @@ 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());
|
||||||
}
|
}
|
||||||
|
|
||||||
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
|
static void InterpretNegativeSetting(std::string name, std::map<std::string, std::string>& mapSettingsRet)
|
||||||
{
|
{
|
||||||
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
|
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
|
||||||
if (name.find("-no") == 0)
|
if (name.find("-no") == 0)
|
||||||
@ -530,9 +536,9 @@ void ParseParameters(int argc, const char* const argv[])
|
|||||||
}
|
}
|
||||||
|
|
||||||
// New 0.6 features:
|
// New 0.6 features:
|
||||||
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
|
BOOST_FOREACH(const PAIRTYPE(std::string,std::string)& entry, mapArgs)
|
||||||
{
|
{
|
||||||
string name = entry.first;
|
std::string name = entry.first;
|
||||||
|
|
||||||
// interpret --foo as -foo (as long as both are not set)
|
// interpret --foo as -foo (as long as both are not set)
|
||||||
if (name.find("--") == 0)
|
if (name.find("--") == 0)
|
||||||
@ -590,11 +596,11 @@ bool SoftSetBoolArg(const std::string& strArg, bool fValue)
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
string EncodeBase64(const unsigned char* pch, size_t len)
|
std::string EncodeBase64(const unsigned char* pch, size_t len)
|
||||||
{
|
{
|
||||||
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
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;
|
||||||
@ -636,12 +642,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] =
|
||||||
{
|
{
|
||||||
@ -663,7 +669,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;
|
||||||
@ -724,17 +730,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 string((const char*)&vchRet[0], vchRet.size());
|
return std::string((const char*)&vchRet[0], vchRet.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
string EncodeBase32(const unsigned char* pch, size_t len)
|
std::string EncodeBase32(const unsigned char* pch, size_t len)
|
||||||
{
|
{
|
||||||
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
|
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;
|
||||||
@ -789,12 +795,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] =
|
||||||
{
|
{
|
||||||
@ -816,7 +822,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;
|
||||||
@ -911,10 +917,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 string((const char*)&vchRet[0], vchRet.size());
|
return std::string((const char*)&vchRet[0], vchRet.size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -942,7 +948,7 @@ bool WildcardMatch(const char* psz, const char* mask)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool WildcardMatch(const string& str, const string& mask)
|
bool WildcardMatch(const std::string& str, const std::string& mask)
|
||||||
{
|
{
|
||||||
return WildcardMatch(str.c_str(), mask.c_str());
|
return WildcardMatch(str.c_str(), mask.c_str());
|
||||||
}
|
}
|
||||||
@ -1077,20 +1083,20 @@ boost::filesystem::path GetConfigFile()
|
|||||||
return pathConfigFile;
|
return pathConfigFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
void ReadConfigFile(map<string, string>& mapSettingsRet,
|
void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet,
|
||||||
map<string, vector<string> >& mapMultiSettingsRet)
|
std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet)
|
||||||
{
|
{
|
||||||
boost::filesystem::ifstream streamConfig(GetConfigFile());
|
boost::filesystem::ifstream streamConfig(GetConfigFile());
|
||||||
if (!streamConfig.good())
|
if (!streamConfig.good())
|
||||||
return; // No curecoin.conf file is OK
|
return; // No curecoin.conf file is OK
|
||||||
|
|
||||||
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 curecoin.conf
|
// Don't overwrite existing settings so command line settings override curecoin.conf
|
||||||
string strKey = string("-") + it->string_key;
|
std::string strKey = std::string("-") + it->string_key;
|
||||||
if (mapSettingsRet.count(strKey) == 0)
|
if (mapSettingsRet.count(strKey) == 0)
|
||||||
{
|
{
|
||||||
mapSettingsRet[strKey] = it->value[0];
|
mapSettingsRet[strKey] = it->value[0];
|
||||||
@ -1211,13 +1217,13 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
|
|||||||
int64 nOffsetSample = nTime - GetTime();
|
int64 nOffsetSample = nTime - GetTime();
|
||||||
|
|
||||||
// Ignore duplicates
|
// Ignore duplicates
|
||||||
static set<CNetAddr> setKnown;
|
static std::set<CNetAddr> setKnown;
|
||||||
if (!setKnown.insert(ip).second)
|
if (!setKnown.insert(ip).second)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// Add data
|
// Add data
|
||||||
vTimeOffsets.input(nOffsetSample);
|
vTimeOffsets.input(nOffsetSample);
|
||||||
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
|
printf("Added time data, samples %d, offset %+" PRI64d " (%+" PRI64d " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
|
||||||
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
|
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
|
||||||
{
|
{
|
||||||
int64 nMedian = vTimeOffsets.median();
|
int64 nMedian = vTimeOffsets.median();
|
||||||
@ -1243,19 +1249,19 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
|
|||||||
if (!fMatch)
|
if (!fMatch)
|
||||||
{
|
{
|
||||||
fDone = true;
|
fDone = true;
|
||||||
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong curecoin will not work properly.");
|
std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong curecoin will not work properly.");
|
||||||
strMiscWarning = strMessage;
|
strMiscWarning = strMessage;
|
||||||
printf("*** %s\n", strMessage.c_str());
|
printf("*** %s\n", strMessage.c_str());
|
||||||
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
|
uiInterface.ThreadSafeMessageBox(strMessage+" ", std::string("curecoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (fDebug) {
|
if (fDebug) {
|
||||||
BOOST_FOREACH(int64 n, vSorted)
|
BOOST_FOREACH(int64 n, vSorted)
|
||||||
printf("%+"PRI64d" ", n);
|
printf("%+" PRI64d " ", n);
|
||||||
printf("| ");
|
printf("| ");
|
||||||
}
|
}
|
||||||
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
|
printf("nTimeOffset = %+" PRI64d " (%+" PRI64d " minutes)\n", nTimeOffset, nTimeOffset/60);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1266,7 +1272,7 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
string FormatVersion(int nVersion)
|
std::string FormatVersion(int nVersion)
|
||||||
{
|
{
|
||||||
if (nVersion%100 == 0)
|
if (nVersion%100 == 0)
|
||||||
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
|
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
|
||||||
@ -1274,7 +1280,7 @@ string FormatVersion(int nVersion)
|
|||||||
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
|
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
|
||||||
}
|
}
|
||||||
|
|
||||||
string FormatFullVersion()
|
std::string FormatFullVersion()
|
||||||
{
|
{
|
||||||
return CLIENT_BUILD;
|
return CLIENT_BUILD;
|
||||||
}
|
}
|
||||||
|
@ -242,7 +242,7 @@ void runCommand(std::string strCommand);
|
|||||||
|
|
||||||
inline std::string i64tostr(int64 n)
|
inline std::string i64tostr(int64 n)
|
||||||
{
|
{
|
||||||
return strprintf("%"PRI64d, n);
|
return strprintf("%" PRI64d, n);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline std::string itostr(int n)
|
inline std::string itostr(int n)
|
||||||
|
229
src/wallet.cpp
229
src/wallet.cpp
@ -10,7 +10,16 @@
|
|||||||
#include "base58.h"
|
#include "base58.h"
|
||||||
#include "kernel.h"
|
#include "kernel.h"
|
||||||
|
|
||||||
using namespace std;
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <list>
|
||||||
|
#include <map>
|
||||||
|
#include <set>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
extern int nStakeMaxAge;
|
extern int nStakeMaxAge;
|
||||||
|
|
||||||
|
|
||||||
@ -21,8 +30,8 @@ extern int nStakeMaxAge;
|
|||||||
|
|
||||||
struct CompareValueOnly
|
struct CompareValueOnly
|
||||||
{
|
{
|
||||||
bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
|
bool operator()(const std::pair<int64, std::pair<const CWalletTx*, unsigned int> >& t1,
|
||||||
const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
|
const std::pair<int64, std::pair<const CWalletTx*, unsigned int> >& t2) const
|
||||||
{
|
{
|
||||||
return t1.first < t2.first;
|
return t1.first < t2.first;
|
||||||
}
|
}
|
||||||
@ -56,7 +65,7 @@ bool CWallet::AddKey(const CKey& key)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
|
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
|
||||||
{
|
{
|
||||||
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
|
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
|
||||||
return false;
|
return false;
|
||||||
@ -317,16 +326,16 @@ CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries,
|
|||||||
|
|
||||||
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
|
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
|
||||||
// would make this much faster for applications that do this a lot.
|
// would make this much faster for applications that do this a lot.
|
||||||
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
CWalletTx* wtx = &((*it).second);
|
CWalletTx* wtx = &((*it).second);
|
||||||
txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
|
txOrdered.insert(std::make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
|
||||||
}
|
}
|
||||||
acentries.clear();
|
acentries.clear();
|
||||||
walletdb.ListAccountCreditDebit(strAccount, acentries);
|
walletdb.ListAccountCreditDebit(strAccount, acentries);
|
||||||
BOOST_FOREACH(CAccountingEntry& entry, acentries)
|
BOOST_FOREACH(CAccountingEntry& entry, acentries)
|
||||||
{
|
{
|
||||||
txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
|
txOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
|
||||||
}
|
}
|
||||||
|
|
||||||
return txOrdered;
|
return txOrdered;
|
||||||
@ -341,7 +350,7 @@ void CWallet::WalletUpdateSpent(const CTransaction &tx)
|
|||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||||
{
|
{
|
||||||
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
|
std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
|
||||||
if (mi != mapWallet.end())
|
if (mi != mapWallet.end())
|
||||||
{
|
{
|
||||||
CWalletTx& wtx = (*mi).second;
|
CWalletTx& wtx = (*mi).second;
|
||||||
@ -374,7 +383,7 @@ bool CWallet::AddToWallet(const CWalletTx& wtxIn)
|
|||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
// 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;
|
||||||
@ -527,7 +536,7 @@ bool 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;
|
||||||
@ -543,7 +552,7 @@ int64 CWallet::GetDebit(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;
|
||||||
@ -592,7 +601,7 @@ int CWalletTx::GetRequestCount() const
|
|||||||
// Generated block
|
// Generated block
|
||||||
if (hashBlock != 0)
|
if (hashBlock != 0)
|
||||||
{
|
{
|
||||||
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
|
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
|
||||||
if (mi != pwallet->mapRequestCount.end())
|
if (mi != pwallet->mapRequestCount.end())
|
||||||
nRequests = (*mi).second;
|
nRequests = (*mi).second;
|
||||||
}
|
}
|
||||||
@ -600,7 +609,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;
|
||||||
@ -608,7 +617,7 @@ int CWalletTx::GetRequestCount() const
|
|||||||
// How about the block it's in?
|
// How about the block it's in?
|
||||||
if (nRequests == 0 && hashBlock != 0)
|
if (nRequests == 0 && hashBlock != 0)
|
||||||
{
|
{
|
||||||
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
|
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
|
||||||
if (mi != pwallet->mapRequestCount.end())
|
if (mi != pwallet->mapRequestCount.end())
|
||||||
nRequests = (*mi).second;
|
nRequests = (*mi).second;
|
||||||
else
|
else
|
||||||
@ -620,8 +629,8 @@ int CWalletTx::GetRequestCount() const
|
|||||||
return nRequests;
|
return nRequests;
|
||||||
}
|
}
|
||||||
|
|
||||||
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
|
void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, std::list<std::pair<CTxDestination, int64> >& listReceived,
|
||||||
list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
|
std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const
|
||||||
{
|
{
|
||||||
nGeneratedImmature = nGeneratedMature = nFee = 0;
|
nGeneratedImmature = nGeneratedMature = nFee = 0;
|
||||||
listReceived.clear();
|
listReceived.clear();
|
||||||
@ -649,7 +658,7 @@ void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, l
|
|||||||
BOOST_FOREACH(const CTxOut& txout, vout)
|
BOOST_FOREACH(const CTxOut& txout, vout)
|
||||||
{
|
{
|
||||||
CTxDestination address;
|
CTxDestination address;
|
||||||
vector<unsigned char> vchPubKey;
|
std::vector<unsigned char> vchPubKey;
|
||||||
if (!ExtractDestination(txout.scriptPubKey, address))
|
if (!ExtractDestination(txout.scriptPubKey, address))
|
||||||
{
|
{
|
||||||
printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
|
printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
|
||||||
@ -661,23 +670,23 @@ void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, l
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
if (nDebit > 0)
|
if (nDebit > 0)
|
||||||
listSent.push_back(make_pair(address, txout.nValue));
|
listSent.push_back(std::make_pair(address, txout.nValue));
|
||||||
|
|
||||||
if (pwallet->IsMine(txout))
|
if (pwallet->IsMine(txout))
|
||||||
listReceived.push_back(make_pair(address, txout.nValue));
|
listReceived.push_back(std::make_pair(address, txout.nValue));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
|
void CWalletTx::GetAccountAmounts(const std::string& strAccount, int64& nGenerated, int64& nReceived,
|
||||||
int64& nSent, int64& nFee) const
|
int64& nSent, int64& nFee) const
|
||||||
{
|
{
|
||||||
nGenerated = nReceived = nSent = nFee = 0;
|
nGenerated = nReceived = nSent = nFee = 0;
|
||||||
|
|
||||||
int64 allGeneratedImmature, allGeneratedMature, allFee;
|
int64 allGeneratedImmature, allGeneratedMature, allFee;
|
||||||
string strSentAccount;
|
std::string strSentAccount;
|
||||||
list<pair<CTxDestination, int64> > listReceived;
|
std::list<std::pair<CTxDestination, int64> > listReceived;
|
||||||
list<pair<CTxDestination, int64> > listSent;
|
std::list<std::pair<CTxDestination, int64> > listSent;
|
||||||
GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
|
GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
|
||||||
|
|
||||||
if (strAccount == "")
|
if (strAccount == "")
|
||||||
@ -694,7 +703,7 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, i
|
|||||||
{
|
{
|
||||||
if (pwallet->mapAddressBook.count(r.first))
|
if (pwallet->mapAddressBook.count(r.first))
|
||||||
{
|
{
|
||||||
map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
|
std::map<CTxDestination, std::string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
|
||||||
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
|
if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
|
||||||
nReceived += r.second;
|
nReceived += r.second;
|
||||||
}
|
}
|
||||||
@ -713,15 +722,15 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
|
|||||||
const int COPY_DEPTH = 3;
|
const int COPY_DEPTH = 3;
|
||||||
if (SetMerkleBranch() < COPY_DEPTH)
|
if (SetMerkleBranch() < COPY_DEPTH)
|
||||||
{
|
{
|
||||||
vector<uint256> vWorkQueue;
|
std::vector<uint256> vWorkQueue;
|
||||||
BOOST_FOREACH(const CTxIn& txin, vin)
|
BOOST_FOREACH(const CTxIn& txin, vin)
|
||||||
vWorkQueue.push_back(txin.prevout.hash);
|
vWorkQueue.push_back(txin.prevout.hash);
|
||||||
|
|
||||||
// This critsect is OK because txdb is already open
|
// This critsect is OK because txdb is already open
|
||||||
{
|
{
|
||||||
LOCK(pwallet->cs_wallet);
|
LOCK(pwallet->cs_wallet);
|
||||||
map<uint256, const CMerkleTx*> mapWalletPrev;
|
std::map<uint256, const CMerkleTx*> mapWalletPrev;
|
||||||
set<uint256> setAlreadyDone;
|
std::set<uint256> setAlreadyDone;
|
||||||
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
||||||
{
|
{
|
||||||
uint256 hash = vWorkQueue[i];
|
uint256 hash = vWorkQueue[i];
|
||||||
@ -730,7 +739,7 @@ void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
|
|||||||
setAlreadyDone.insert(hash);
|
setAlreadyDone.insert(hash);
|
||||||
|
|
||||||
CMerkleTx tx;
|
CMerkleTx tx;
|
||||||
map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
|
std::map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
|
||||||
if (mi != pwallet->mapWallet.end())
|
if (mi != pwallet->mapWallet.end())
|
||||||
{
|
{
|
||||||
tx = (*mi).second;
|
tx = (*mi).second;
|
||||||
@ -813,7 +822,7 @@ void CWallet::ReacceptWalletTransactions()
|
|||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
fRepeat = false;
|
fRepeat = false;
|
||||||
vector<CDiskTxPos> vMissingTx;
|
std::vector<CDiskTxPos> vMissingTx;
|
||||||
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
|
BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
|
||||||
{
|
{
|
||||||
CWalletTx& wtx = item.second;
|
CWalletTx& wtx = item.second;
|
||||||
@ -827,7 +836,7 @@ void CWallet::ReacceptWalletTransactions()
|
|||||||
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
|
// Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
|
||||||
if (txindex.vSpent.size() != wtx.vout.size())
|
if (txindex.vSpent.size() != wtx.vout.size())
|
||||||
{
|
{
|
||||||
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
|
printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %" PRIszu " != wtx.vout.size() %" PRIszu "\n", txindex.vSpent.size(), wtx.vout.size());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
|
for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
|
||||||
@ -916,14 +925,14 @@ void CWallet::ResendWalletTransactions()
|
|||||||
{
|
{
|
||||||
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 until it's had plenty of time that
|
// Don't rebroadcast until it's had plenty of time that
|
||||||
// it should have gotten in already by now.
|
// it should have gotten in already by now.
|
||||||
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
|
if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
|
||||||
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
|
mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
|
||||||
}
|
}
|
||||||
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
|
BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
|
||||||
{
|
{
|
||||||
@ -952,7 +961,7 @@ int64 CWallet::GetBalance() const
|
|||||||
int64 nTotal = 0;
|
int64 nTotal = 0;
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx* pcoin = &(*it).second;
|
const CWalletTx* pcoin = &(*it).second;
|
||||||
if (pcoin->IsFinal() && pcoin->IsConfirmed())
|
if (pcoin->IsFinal() && pcoin->IsConfirmed())
|
||||||
@ -968,7 +977,7 @@ int64 CWallet::GetUnconfirmedBalance() const
|
|||||||
int64 nTotal = 0;
|
int64 nTotal = 0;
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx* pcoin = &(*it).second;
|
const CWalletTx* pcoin = &(*it).second;
|
||||||
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
|
if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
|
||||||
@ -983,7 +992,7 @@ int64 CWallet::GetImmatureBalance() const
|
|||||||
int64 nTotal = 0;
|
int64 nTotal = 0;
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx& pcoin = (*it).second;
|
const CWalletTx& pcoin = (*it).second;
|
||||||
if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
|
if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
|
||||||
@ -994,13 +1003,13 @@ int64 CWallet::GetImmatureBalance() const
|
|||||||
}
|
}
|
||||||
|
|
||||||
// populate vCoins with vector of spendable COutputs
|
// populate vCoins with vector of spendable COutputs
|
||||||
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
|
void CWallet::AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed) const
|
||||||
{
|
{
|
||||||
vCoins.clear();
|
vCoins.clear();
|
||||||
|
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx* pcoin = &(*it).second;
|
const CWalletTx* pcoin = &(*it).second;
|
||||||
|
|
||||||
@ -1023,13 +1032,13 @@ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed) const
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
|
void CWallet::AvailableCoinsMinConf(std::vector<COutput>& vCoins, int nConf) const
|
||||||
{
|
{
|
||||||
vCoins.clear();
|
vCoins.clear();
|
||||||
|
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx* pcoin = &(*it).second;
|
const CWalletTx* pcoin = &(*it).second;
|
||||||
|
|
||||||
@ -1046,10 +1055,10 @@ void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
|
static void ApproximateBestSubset(std::vector<std::pair<int64, std::pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
|
||||||
vector<char>& vfBest, int64& nBest, int iterations = 1000)
|
std::vector<char>& vfBest, int64& 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;
|
||||||
@ -1089,7 +1098,7 @@ int64 CWallet::GetStake() const
|
|||||||
{
|
{
|
||||||
int64 nTotal = 0;
|
int64 nTotal = 0;
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx* pcoin = &(*it).second;
|
const CWalletTx* pcoin = &(*it).second;
|
||||||
if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
|
if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
|
||||||
@ -1102,7 +1111,7 @@ int64 CWallet::GetNewMint() const
|
|||||||
{
|
{
|
||||||
int64 nTotal = 0;
|
int64 nTotal = 0;
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
const CWalletTx* pcoin = &(*it).second;
|
const CWalletTx* pcoin = &(*it).second;
|
||||||
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
|
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
|
||||||
@ -1111,16 +1120,16 @@ int64 CWallet::GetNewMint() const
|
|||||||
return nTotal;
|
return nTotal;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
|
bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
|
||||||
{
|
{
|
||||||
setCoinsRet.clear();
|
setCoinsRet.clear();
|
||||||
nValueRet = 0;
|
nValueRet = 0;
|
||||||
|
|
||||||
// List of values less than target
|
// List of values less than target
|
||||||
pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
|
std::pair<int64, std::pair<const CWalletTx*,unsigned int> > coinLowestLarger;
|
||||||
coinLowestLarger.first = std::numeric_limits<int64>::max();
|
coinLowestLarger.first = std::numeric_limits<int64>::max();
|
||||||
coinLowestLarger.second.first = NULL;
|
coinLowestLarger.second.first = NULL;
|
||||||
vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
|
std::vector<std::pair<int64, std::pair<const CWalletTx*,unsigned int> > > vValue;
|
||||||
int64 nTotalLower = 0;
|
int64 nTotalLower = 0;
|
||||||
|
|
||||||
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
|
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
|
||||||
@ -1139,7 +1148,7 @@ bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, in
|
|||||||
|
|
||||||
int64 n = pcoin->vout[i].nValue;
|
int64 n = pcoin->vout[i].nValue;
|
||||||
|
|
||||||
pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
|
std::pair<int64,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
|
||||||
|
|
||||||
if (n == nTargetValue)
|
if (n == nTargetValue)
|
||||||
{
|
{
|
||||||
@ -1179,7 +1188,7 @@ bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, in
|
|||||||
|
|
||||||
// Solve subset sum by stochastic approximation
|
// Solve subset sum by stochastic approximation
|
||||||
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
|
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
|
||||||
vector<char> vfBest;
|
std::vector<char> vfBest;
|
||||||
int64 nBest;
|
int64 nBest;
|
||||||
|
|
||||||
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
|
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
|
||||||
@ -1216,9 +1225,9 @@ bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, in
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
|
bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
|
||||||
{
|
{
|
||||||
vector<COutput> vCoins;
|
std::vector<COutput> vCoins;
|
||||||
AvailableCoins(vCoins);
|
AvailableCoins(vCoins);
|
||||||
|
|
||||||
return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
|
return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
|
||||||
@ -1227,9 +1236,9 @@ bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Select some coins without random shuffle or best subset approximation
|
// Select some coins without random shuffle or best subset approximation
|
||||||
bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
|
bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
|
||||||
{
|
{
|
||||||
vector<COutput> vCoins;
|
std::vector<COutput> vCoins;
|
||||||
AvailableCoinsMinConf(vCoins, nMinConf);
|
AvailableCoinsMinConf(vCoins, nMinConf);
|
||||||
|
|
||||||
setCoinsRet.clear();
|
setCoinsRet.clear();
|
||||||
@ -1250,7 +1259,7 @@ bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int
|
|||||||
|
|
||||||
int64_t n = pcoin->vout[i].nValue;
|
int64_t n = pcoin->vout[i].nValue;
|
||||||
|
|
||||||
pair<int64_t,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
|
std::pair<int64_t,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
|
||||||
|
|
||||||
if (n >= nTargetValue)
|
if (n >= nTargetValue)
|
||||||
{
|
{
|
||||||
@ -1271,7 +1280,7 @@ bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
|
bool CWallet::CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
|
||||||
{
|
{
|
||||||
int64 nValue = 0;
|
int64 nValue = 0;
|
||||||
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
|
BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
|
||||||
@ -1310,7 +1319,7 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
|
|||||||
wtxNew.vout.push_back(CTxOut(s.second, s.first));
|
wtxNew.vout.push_back(CTxOut(s.second, s.first));
|
||||||
|
|
||||||
// Choose coins to use
|
// Choose coins to use
|
||||||
set<pair<const CWalletTx*,unsigned int> > setCoins;
|
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
|
||||||
int64 nValueIn = 0;
|
int64 nValueIn = 0;
|
||||||
if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
|
if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn))
|
||||||
return false;
|
return false;
|
||||||
@ -1326,7 +1335,7 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
|
|||||||
// NOTE: this depends on the exact behaviour of GetMinFee
|
// NOTE: this depends on the exact behaviour of GetMinFee
|
||||||
if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
|
if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
|
||||||
{
|
{
|
||||||
int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
|
int64 nMoveToFee = std::min(nChange, MIN_TX_FEE - nFeeRet);
|
||||||
nChange -= nMoveToFee;
|
nChange -= nMoveToFee;
|
||||||
nFeeRet += nMoveToFee;
|
nFeeRet += nMoveToFee;
|
||||||
}
|
}
|
||||||
@ -1358,7 +1367,7 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
|
|||||||
scriptChange.SetDestination(vchPubKey.GetID());
|
scriptChange.SetDestination(vchPubKey.GetID());
|
||||||
|
|
||||||
// Insert change txn at random position:
|
// Insert change txn at random position:
|
||||||
vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
|
std::vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
|
||||||
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
|
wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@ -1384,9 +1393,9 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
|
|||||||
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
|
int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
|
||||||
int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
|
int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND);
|
||||||
|
|
||||||
if (nFeeRet < max(nPayFee, nMinFee))
|
if (nFeeRet < std::max(nPayFee, nMinFee))
|
||||||
{
|
{
|
||||||
nFeeRet = max(nPayFee, nMinFee);
|
nFeeRet = std::max(nPayFee, nMinFee);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1403,8 +1412,8 @@ bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CW
|
|||||||
|
|
||||||
bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
|
bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string strTxComment)
|
||||||
{
|
{
|
||||||
vector< pair<CScript, int64> > vecSend;
|
std::vector< std::pair<CScript, int64> > vecSend;
|
||||||
vecSend.push_back(make_pair(scriptPubKey, nValue));
|
vecSend.push_back(std::make_pair(scriptPubKey, nValue));
|
||||||
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strTxComment);
|
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strTxComment);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1419,9 +1428,9 @@ bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint
|
|||||||
if (nBalance <= nReserveBalance)
|
if (nBalance <= nReserveBalance)
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
vector<const CWalletTx*> vwtxPrev;
|
std::vector<const CWalletTx*> vwtxPrev;
|
||||||
|
|
||||||
set<pair<const CWalletTx*,unsigned int> > setCoins;
|
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
|
||||||
int64 nValueIn = 0;
|
int64 nValueIn = 0;
|
||||||
|
|
||||||
if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity + 10, setCoins, nValueIn))
|
if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity + 10, setCoins, nValueIn))
|
||||||
@ -1495,8 +1504,8 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int
|
|||||||
return error("CreateCoinStake : invalid reserve balance amount");
|
return error("CreateCoinStake : invalid reserve balance amount");
|
||||||
if (nBalance <= nReserveBalance)
|
if (nBalance <= nReserveBalance)
|
||||||
return false;
|
return false;
|
||||||
set<pair<const CWalletTx*,unsigned int> > setCoins;
|
std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
|
||||||
vector<const CWalletTx*> vwtxPrev;
|
std::vector<const CWalletTx*> vwtxPrev;
|
||||||
int64 nValueIn = 0;
|
int64 nValueIn = 0;
|
||||||
if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
|
if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn))
|
||||||
return false;
|
return false;
|
||||||
@ -1520,7 +1529,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int
|
|||||||
continue; // only count coins meeting min age requirement
|
continue; // only count coins meeting min age requirement
|
||||||
|
|
||||||
bool fKernelFound = false;
|
bool fKernelFound = false;
|
||||||
for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
|
for (unsigned int n=0; n<std::min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
|
||||||
{
|
{
|
||||||
// Search backward in time from the given txNew timestamp
|
// Search backward in time from the given txNew timestamp
|
||||||
// Search nSearchInterval seconds back up to nMaxStakeSearchInterval
|
// Search nSearchInterval seconds back up to nMaxStakeSearchInterval
|
||||||
@ -1531,7 +1540,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int
|
|||||||
// Found a kernel
|
// Found a kernel
|
||||||
if (fDebug && GetBoolArg("-printcoinstake"))
|
if (fDebug && GetBoolArg("-printcoinstake"))
|
||||||
printf("CreateCoinStake : kernel found\n");
|
printf("CreateCoinStake : kernel found\n");
|
||||||
vector<valtype> vSolutions;
|
std::vector<valtype> vSolutions;
|
||||||
txnouttype whichType;
|
txnouttype whichType;
|
||||||
CScript scriptPubKeyOut;
|
CScript scriptPubKeyOut;
|
||||||
scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
|
scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
|
||||||
@ -1685,7 +1694,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
|
|||||||
AddToWallet(wtxNew);
|
AddToWallet(wtxNew);
|
||||||
|
|
||||||
// Mark old coins as spent
|
// Mark old coins as spent
|
||||||
set<CWalletTx*> setCoins;
|
std::set<CWalletTx*> setCoins;
|
||||||
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
|
BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
|
||||||
{
|
{
|
||||||
CWalletTx &coin = mapWallet[txin.prevout.hash];
|
CWalletTx &coin = mapWallet[txin.prevout.hash];
|
||||||
@ -1717,26 +1726,26 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
|
std::string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
|
||||||
{
|
{
|
||||||
CReserveKey reservekey(this);
|
CReserveKey reservekey(this);
|
||||||
int64 nFeeRequired;
|
int64 nFeeRequired;
|
||||||
|
|
||||||
if (IsLocked())
|
if (IsLocked())
|
||||||
{
|
{
|
||||||
string strError = _("Error: Wallet locked, unable to create transaction ");
|
std::string strError = _("Error: Wallet locked, unable to create transaction ");
|
||||||
printf("SendMoney() : %s", strError.c_str());
|
printf("SendMoney() : %s", strError.c_str());
|
||||||
return strError;
|
return strError;
|
||||||
}
|
}
|
||||||
if (fWalletUnlockMintOnly)
|
if (fWalletUnlockMintOnly)
|
||||||
{
|
{
|
||||||
string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
|
std::string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
|
||||||
printf("SendMoney() : %s", strError.c_str());
|
printf("SendMoney() : %s", strError.c_str());
|
||||||
return strError;
|
return strError;
|
||||||
}
|
}
|
||||||
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strTxComment))
|
if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strTxComment))
|
||||||
{
|
{
|
||||||
string strError;
|
std::string strError;
|
||||||
if (nValue + nFeeRequired > GetBalance())
|
if (nValue + nFeeRequired > GetBalance())
|
||||||
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
|
strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str());
|
||||||
else
|
else
|
||||||
@ -1756,7 +1765,7 @@ string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew,
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
|
std::string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee, std::string strTxComment)
|
||||||
{
|
{
|
||||||
// Check amount
|
// Check amount
|
||||||
if (nValue <= 0)
|
if (nValue <= 0)
|
||||||
@ -1822,7 +1831,7 @@ DBErrors CWallet::ZapWalletTx()
|
|||||||
return DB_LOAD_OK;
|
return DB_LOAD_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
|
bool CWallet::SetAddressBookName(const CTxDestination& address, const std::string& strName)
|
||||||
{
|
{
|
||||||
std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
|
std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
|
||||||
mapAddressBook[address] = strName;
|
mapAddressBook[address] = strName;
|
||||||
@ -1849,12 +1858,12 @@ void CWallet::PrintWallet(const CBlock& block)
|
|||||||
if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
|
if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
|
||||||
{
|
{
|
||||||
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
|
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
|
||||||
printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
|
printf(" mine: %d %d %" PRI64d "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
|
||||||
}
|
}
|
||||||
if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
|
if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
|
||||||
{
|
{
|
||||||
CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
|
CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
|
||||||
printf(" stake: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
|
printf(" stake: %d %d %" PRI64d "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -1865,7 +1874,7 @@ bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
|
|||||||
{
|
{
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
|
std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
|
||||||
if (mi != mapWallet.end())
|
if (mi != mapWallet.end())
|
||||||
{
|
{
|
||||||
wtx = (*mi).second;
|
wtx = (*mi).second;
|
||||||
@ -1886,7 +1895,7 @@ bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
|
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut)
|
||||||
{
|
{
|
||||||
if (!pwallet->fFileBacked)
|
if (!pwallet->fFileBacked)
|
||||||
return false;
|
return false;
|
||||||
@ -1910,14 +1919,14 @@ bool CWallet::NewKeyPool()
|
|||||||
if (IsLocked())
|
if (IsLocked())
|
||||||
return false;
|
return false;
|
||||||
|
|
||||||
int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
|
int64 nKeys = std::max(GetArg("-keypool", 100), (int64)0);
|
||||||
for (int i = 0; i < nKeys; i++)
|
for (int i = 0; i < nKeys; i++)
|
||||||
{
|
{
|
||||||
int64 nIndex = i+1;
|
int64 nIndex = i+1;
|
||||||
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
|
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
|
||||||
setKeyPool.insert(nIndex);
|
setKeyPool.insert(nIndex);
|
||||||
}
|
}
|
||||||
printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
|
printf("CWallet::NewKeyPool wrote %" PRI64d " new keys\n", nKeys);
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@ -1933,16 +1942,16 @@ bool CWallet::TopUpKeyPool()
|
|||||||
CWalletDB walletdb(strWalletFile);
|
CWalletDB walletdb(strWalletFile);
|
||||||
|
|
||||||
// Top up key pool
|
// Top up key pool
|
||||||
unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL);
|
unsigned int nTargetSize = std::max(GetArg("-keypool", 100), 0LL);
|
||||||
while (setKeyPool.size() < (nTargetSize + 1))
|
while (setKeyPool.size() < (nTargetSize + 1))
|
||||||
{
|
{
|
||||||
int64 nEnd = 1;
|
int64 nEnd = 1;
|
||||||
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("TopUpKeyPool() : writing generated key failed");
|
throw std::runtime_error("TopUpKeyPool() : writing generated key failed");
|
||||||
setKeyPool.insert(nEnd);
|
setKeyPool.insert(nEnd);
|
||||||
printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
|
printf("keypool added key %" PRI64d ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@ -1967,12 +1976,12 @@ void CWallet::ReserveKeyFromKeyPool(int64& 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("ReserveKeyFromKeyPool() : read failed");
|
throw std::runtime_error("ReserveKeyFromKeyPool() : read failed");
|
||||||
if (!HaveKey(keypool.vchPubKey.GetID()))
|
if (!HaveKey(keypool.vchPubKey.GetID()))
|
||||||
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
|
throw std::runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
|
||||||
assert(keypool.vchPubKey.IsValid());
|
assert(keypool.vchPubKey.IsValid());
|
||||||
if (fDebug && GetBoolArg("-printkeypool"))
|
if (fDebug && GetBoolArg("-printkeypool"))
|
||||||
printf("keypool reserve %"PRI64d"\n", nIndex);
|
printf("keypool reserve %" PRI64d "\n", nIndex);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1984,7 +1993,7 @@ int64 CWallet::AddReserveKey(const CKeyPool& keypool)
|
|||||||
|
|
||||||
int64 nIndex = 1 + *(--setKeyPool.end());
|
int64 nIndex = 1 + *(--setKeyPool.end());
|
||||||
if (!walletdb.WritePool(nIndex, keypool))
|
if (!walletdb.WritePool(nIndex, keypool))
|
||||||
throw runtime_error("AddReserveKey() : writing added key failed");
|
throw std::runtime_error("AddReserveKey() : writing added key failed");
|
||||||
setKeyPool.insert(nIndex);
|
setKeyPool.insert(nIndex);
|
||||||
return nIndex;
|
return nIndex;
|
||||||
}
|
}
|
||||||
@ -2000,7 +2009,7 @@ void CWallet::KeepKey(int64 nIndex)
|
|||||||
walletdb.ErasePool(nIndex);
|
walletdb.ErasePool(nIndex);
|
||||||
}
|
}
|
||||||
if(fDebug)
|
if(fDebug)
|
||||||
printf("keypool keep %"PRI64d"\n", nIndex);
|
printf("keypool keep %" PRI64d "\n", nIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
void CWallet::ReturnKey(int64 nIndex)
|
void CWallet::ReturnKey(int64 nIndex)
|
||||||
@ -2011,7 +2020,7 @@ void CWallet::ReturnKey(int64 nIndex)
|
|||||||
setKeyPool.insert(nIndex);
|
setKeyPool.insert(nIndex);
|
||||||
}
|
}
|
||||||
if(fDebug)
|
if(fDebug)
|
||||||
printf("keypool return %"PRI64d"\n", nIndex);
|
printf("keypool return %" PRI64d "\n", nIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
|
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
|
||||||
@ -2051,7 +2060,7 @@ int64 CWallet::GetOldestKeyPoolTime()
|
|||||||
|
|
||||||
std::map<CTxDestination, int64> CWallet::GetAddressBalances()
|
std::map<CTxDestination, int64> CWallet::GetAddressBalances()
|
||||||
{
|
{
|
||||||
map<CTxDestination, int64> balances;
|
std::map<CTxDestination, int64> balances;
|
||||||
|
|
||||||
{
|
{
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
@ -2089,10 +2098,10 @@ std::map<CTxDestination, int64> CWallet::GetAddressBalances()
|
|||||||
return balances;
|
return balances;
|
||||||
}
|
}
|
||||||
|
|
||||||
set< set<CTxDestination> > CWallet::GetAddressGroupings()
|
std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
|
||||||
{
|
{
|
||||||
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)
|
||||||
{
|
{
|
||||||
@ -2136,20 +2145,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);
|
||||||
@ -2162,8 +2171,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;
|
||||||
@ -2180,9 +2189,9 @@ void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool
|
|||||||
nBalanceInQuestion = 0;
|
nBalanceInQuestion = 0;
|
||||||
|
|
||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
vector<CWalletTx*> vCoins;
|
std::vector<CWalletTx*> vCoins;
|
||||||
vCoins.reserve(mapWallet.size());
|
vCoins.reserve(mapWallet.size());
|
||||||
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
|
||||||
vCoins.push_back(&(*it).second);
|
vCoins.push_back(&(*it).second);
|
||||||
|
|
||||||
CTxDB txdb("r");
|
CTxDB txdb("r");
|
||||||
@ -2231,7 +2240,7 @@ void CWallet::DisableTransaction(const CTransaction &tx)
|
|||||||
LOCK(cs_wallet);
|
LOCK(cs_wallet);
|
||||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||||
{
|
{
|
||||||
map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
|
std::map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
|
||||||
if (mi != mapWallet.end())
|
if (mi != mapWallet.end())
|
||||||
{
|
{
|
||||||
CWalletTx& prev = (*mi).second;
|
CWalletTx& prev = (*mi).second;
|
||||||
@ -2278,7 +2287,7 @@ void CReserveKey::ReturnKey()
|
|||||||
vchPubKey = CPubKey();
|
vchPubKey = CPubKey();
|
||||||
}
|
}
|
||||||
|
|
||||||
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
|
void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress)
|
||||||
{
|
{
|
||||||
setAddress.clear();
|
setAddress.clear();
|
||||||
|
|
||||||
@ -2289,11 +2298,11 @@ void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress)
|
|||||||
{
|
{
|
||||||
CKeyPool keypool;
|
CKeyPool keypool;
|
||||||
if (!walletdb.ReadPool(id, keypool))
|
if (!walletdb.ReadPool(id, keypool))
|
||||||
throw runtime_error("GetAllReserveKeyHashes() : read failed");
|
throw std::runtime_error("GetAllReserveKeyHashes() : 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("GetAllReserveKeyHashes() : unknown key in key pool");
|
throw std::runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
|
||||||
setAddress.insert(keyID);
|
setAddress.insert(keyID);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -2303,7 +2312,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);
|
||||||
}
|
}
|
||||||
|
102
src/walletdb.cpp
102
src/walletdb.cpp
@ -7,9 +7,12 @@
|
|||||||
#include "wallet.h"
|
#include "wallet.h"
|
||||||
#include <boost/filesystem.hpp>
|
#include <boost/filesystem.hpp>
|
||||||
|
|
||||||
using namespace std;
|
#include <list>
|
||||||
using namespace boost;
|
#include <map>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
static uint64 nAccountingEntryNumber = 0;
|
static uint64 nAccountingEntryNumber = 0;
|
||||||
extern bool fWalletUnlockMintOnly;
|
extern bool fWalletUnlockMintOnly;
|
||||||
@ -18,34 +21,34 @@ extern bool fWalletUnlockMintOnly;
|
|||||||
// CWalletDB
|
// CWalletDB
|
||||||
//
|
//
|
||||||
|
|
||||||
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
|
bool CWalletDB::WriteName(const std::string& strAddress, const std::string& strName)
|
||||||
{
|
{
|
||||||
nWalletDBUpdated++;
|
nWalletDBUpdated++;
|
||||||
return Write(make_pair(string("name"), strAddress), strName);
|
return Write(std::make_pair(std::string("name"), strAddress), strName);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWalletDB::EraseName(const string& strAddress)
|
bool CWalletDB::EraseName(const std::string& strAddress)
|
||||||
{
|
{
|
||||||
// This should only be used for sending addresses, never for receiving addresses,
|
// 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.
|
||||||
nWalletDBUpdated++;
|
nWalletDBUpdated++;
|
||||||
return Erase(make_pair(string("name"), strAddress));
|
return Erase(std::make_pair(std::string("name"), strAddress));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
|
bool CWalletDB::ReadAccount(const std::string& strAccount, CAccount& account)
|
||||||
{
|
{
|
||||||
account.SetNull();
|
account.SetNull();
|
||||||
return Read(make_pair(string("acc"), strAccount), account);
|
return Read(std::make_pair(std::string("acc"), strAccount), account);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
|
bool CWalletDB::WriteAccount(const std::string& strAccount, const CAccount& account)
|
||||||
{
|
{
|
||||||
return Write(make_pair(string("acc"), strAccount), account);
|
return Write(std::make_pair(std::string("acc"), strAccount), account);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWalletDB::WriteAccountingEntry(const uint64 nAccEntryNum, const CAccountingEntry& acentry)
|
bool CWalletDB::WriteAccountingEntry(const uint64 nAccEntryNum, const CAccountingEntry& acentry)
|
||||||
{
|
{
|
||||||
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
|
return Write(boost::make_tuple(std::string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
|
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
|
||||||
@ -53,9 +56,9 @@ bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
|
|||||||
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
|
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
|
||||||
}
|
}
|
||||||
|
|
||||||
int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
|
int64 CWalletDB::GetAccountCreditDebit(const std::string& strAccount)
|
||||||
{
|
{
|
||||||
list<CAccountingEntry> entries;
|
std::list<CAccountingEntry> entries;
|
||||||
ListAccountCreditDebit(strAccount, entries);
|
ListAccountCreditDebit(strAccount, entries);
|
||||||
|
|
||||||
int64 nCreditDebit = 0;
|
int64 nCreditDebit = 0;
|
||||||
@ -65,20 +68,20 @@ int64 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("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
|
throw std::runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
|
||||||
unsigned int fFlags = DB_SET_RANGE;
|
unsigned int fFlags = DB_SET_RANGE;
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
// Read next record
|
// Read next record
|
||||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||||
if (fFlags == DB_SET_RANGE)
|
if (fFlags == DB_SET_RANGE)
|
||||||
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
|
ssKey << boost::make_tuple(std::string("acentry"), (fAllAccounts? std::string("") : strAccount), uint64(0));
|
||||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||||
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
|
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
|
||||||
fFlags = DB_NEXT;
|
fFlags = DB_NEXT;
|
||||||
@ -87,11 +90,11 @@ void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountin
|
|||||||
else if (ret != 0)
|
else if (ret != 0)
|
||||||
{
|
{
|
||||||
pcursor->close();
|
pcursor->close();
|
||||||
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
|
throw std::runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unserialize
|
// Unserialize
|
||||||
string strType;
|
std::string strType;
|
||||||
ssKey >> strType;
|
ssKey >> strType;
|
||||||
if (strType != "acentry")
|
if (strType != "acentry")
|
||||||
break;
|
break;
|
||||||
@ -117,20 +120,20 @@ CWalletDB::ReorderTransactions(CWallet* pwallet)
|
|||||||
// 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, TxPair > TxItems;
|
typedef std::multimap<int64, TxPair > TxItems;
|
||||||
TxItems txByTime;
|
TxItems txByTime;
|
||||||
|
|
||||||
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
|
for (std::map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
|
||||||
{
|
{
|
||||||
CWalletTx* wtx = &((*it).second);
|
CWalletTx* wtx = &((*it).second);
|
||||||
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
|
txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
|
||||||
}
|
}
|
||||||
list<CAccountingEntry> acentries;
|
std::list<CAccountingEntry> acentries;
|
||||||
ListAccountCreditDebit("", acentries);
|
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)));
|
||||||
}
|
}
|
||||||
|
|
||||||
int64& nOrderPosNext = pwallet->nOrderPosNext;
|
int64& nOrderPosNext = pwallet->nOrderPosNext;
|
||||||
@ -184,8 +187,8 @@ CWalletDB::ReorderTransactions(CWallet* pwallet)
|
|||||||
|
|
||||||
bool
|
bool
|
||||||
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
|
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
|
||||||
int& nFileVersion, vector<uint256>& vWalletUpgrade,
|
int& nFileVersion, std::vector<uint256>& vWalletUpgrade,
|
||||||
bool& fIsEncrypted, bool& fAnyUnordered, string& strType, string& strErr)
|
bool& fIsEncrypted, bool& fAnyUnordered, std::string& strType, std::string& strErr)
|
||||||
{
|
{
|
||||||
try {
|
try {
|
||||||
// Unserialize
|
// Unserialize
|
||||||
@ -194,7 +197,7 @@ 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[CcurecoinAddress(strAddress).Get()];
|
ssValue >> pwallet->mapAddressBook[CcurecoinAddress(strAddress).Get()];
|
||||||
}
|
}
|
||||||
@ -245,7 +248,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 nNumber;
|
uint64 nNumber;
|
||||||
ssKey >> nNumber;
|
ssKey >> nNumber;
|
||||||
@ -262,7 +265,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
|
|||||||
}
|
}
|
||||||
else if (strType == "key" || strType == "wkey")
|
else if (strType == "key" || strType == "wkey")
|
||||||
{
|
{
|
||||||
vector<unsigned char> vchPubKey;
|
std::vector<unsigned char> vchPubKey;
|
||||||
ssKey >> vchPubKey;
|
ssKey >> vchPubKey;
|
||||||
CKey key;
|
CKey key;
|
||||||
if (strType == "key")
|
if (strType == "key")
|
||||||
@ -330,9 +333,9 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
|
|||||||
}
|
}
|
||||||
else if (strType == "ckey")
|
else if (strType == "ckey")
|
||||||
{
|
{
|
||||||
vector<unsigned char> vchPubKey;
|
std::vector<unsigned char> vchPubKey;
|
||||||
ssKey >> vchPubKey;
|
ssKey >> vchPubKey;
|
||||||
vector<unsigned char> vchPrivKey;
|
std::vector<unsigned char> vchPrivKey;
|
||||||
ssValue >> vchPrivKey;
|
ssValue >> vchPrivKey;
|
||||||
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
|
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
|
||||||
{
|
{
|
||||||
@ -380,7 +383,7 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
static bool IsKeyType(string strType)
|
static bool IsKeyType(std::string strType)
|
||||||
{
|
{
|
||||||
return (strType== "key" || strType == "wkey" ||
|
return (strType== "key" || strType == "wkey" ||
|
||||||
strType == "mkey" || strType == "ckey");
|
strType == "mkey" || strType == "ckey");
|
||||||
@ -390,7 +393,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
|
|||||||
{
|
{
|
||||||
pwallet->vchDefaultKey = CPubKey();
|
pwallet->vchDefaultKey = CPubKey();
|
||||||
int nFileVersion = 0;
|
int nFileVersion = 0;
|
||||||
vector<uint256> vWalletUpgrade;
|
std::vector<uint256> vWalletUpgrade;
|
||||||
bool fIsEncrypted = false;
|
bool fIsEncrypted = false;
|
||||||
bool fAnyUnordered = false;
|
bool fAnyUnordered = false;
|
||||||
bool fNoncriticalErrors = false;
|
bool fNoncriticalErrors = false;
|
||||||
@ -399,7 +402,7 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
|
|||||||
try {
|
try {
|
||||||
LOCK(pwallet->cs_wallet);
|
LOCK(pwallet->cs_wallet);
|
||||||
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;
|
||||||
@ -429,7 +432,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, nFileVersion,
|
if (!ReadKeyValue(pwallet, ssKey, ssValue, nFileVersion,
|
||||||
vWalletUpgrade, fIsEncrypted, fAnyUnordered, strType, strErr))
|
vWalletUpgrade, fIsEncrypted, fAnyUnordered, strType, strErr))
|
||||||
{
|
{
|
||||||
@ -482,17 +485,16 @@ DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
|
DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, std::vector<uint256>& vTxHash)
|
||||||
{
|
{
|
||||||
pwallet->vchDefaultKey = CPubKey();
|
pwallet->vchDefaultKey = CPubKey();
|
||||||
// CWalletScanState wss;
|
// CWalletScanState wss;
|
||||||
bool fNoncriticalErrors = false;
|
|
||||||
DBErrors result = DB_LOAD_OK;
|
DBErrors result = DB_LOAD_OK;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
LOCK(pwallet->cs_wallet);
|
LOCK(pwallet->cs_wallet);
|
||||||
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;
|
||||||
@ -521,7 +523,7 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
|
|||||||
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;
|
||||||
@ -545,7 +547,7 @@ DBErrors CWalletDB::FindWalletTx(CWallet* pwallet, vector<uint256>& vTxHash)
|
|||||||
DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet)
|
DBErrors CWalletDB::ZapWalletTx(CWallet* pwallet)
|
||||||
{
|
{
|
||||||
// build list of wallet TXs
|
// build list of wallet TXs
|
||||||
vector<uint256> vTxHash;
|
std::vector<uint256> vTxHash;
|
||||||
DBErrors err = FindWalletTx(pwallet, vTxHash);
|
DBErrors err = FindWalletTx(pwallet, vTxHash);
|
||||||
if (err != DB_LOAD_OK)
|
if (err != DB_LOAD_OK)
|
||||||
return err;
|
return err;
|
||||||
@ -564,7 +566,7 @@ void ThreadFlushWalletDB(void* parg)
|
|||||||
// Make this thread recognisable as the wallet flushing thread
|
// Make this thread recognisable as the wallet flushing thread
|
||||||
RenameThread("curecoin-wallet");
|
RenameThread("curecoin-wallet");
|
||||||
|
|
||||||
const string& strFile = ((const string*)parg)[0];
|
const std::string& strFile = ((const std::string*)parg)[0];
|
||||||
static bool fOneThread;
|
static bool fOneThread;
|
||||||
if (fOneThread)
|
if (fOneThread)
|
||||||
return;
|
return;
|
||||||
@ -592,7 +594,7 @@ void ThreadFlushWalletDB(void* parg)
|
|||||||
{
|
{
|
||||||
// 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;
|
||||||
@ -601,7 +603,7 @@ void ThreadFlushWalletDB(void* parg)
|
|||||||
|
|
||||||
if (nRefCount == 0 && !fShutdown)
|
if (nRefCount == 0 && !fShutdown)
|
||||||
{
|
{
|
||||||
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
|
std::map<std::string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
|
||||||
if (mi != bitdb.mapFileUseCount.end())
|
if (mi != bitdb.mapFileUseCount.end())
|
||||||
{
|
{
|
||||||
printf("Flushing wallet.dat\n");
|
printf("Flushing wallet.dat\n");
|
||||||
@ -613,7 +615,7 @@ void ThreadFlushWalletDB(void* parg)
|
|||||||
bitdb.CheckpointLSN(strFile);
|
bitdb.CheckpointLSN(strFile);
|
||||||
|
|
||||||
bitdb.mapFileUseCount.erase(mi++);
|
bitdb.mapFileUseCount.erase(mi++);
|
||||||
printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
|
printf("Flushed wallet.dat %" PRI64d "ms\n", GetTimeMillis() - nStart);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -621,7 +623,7 @@ void ThreadFlushWalletDB(void* parg)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool BackupWallet(const CWallet& wallet, const string& strDest)
|
bool BackupWallet(const CWallet& wallet, const std::string& strDest)
|
||||||
{
|
{
|
||||||
if (!wallet.fFileBacked)
|
if (!wallet.fFileBacked)
|
||||||
return false;
|
return false;
|
||||||
@ -674,7 +676,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
|
|||||||
// Set -rescan so any missing transactions will be
|
// Set -rescan so any missing transactions will be
|
||||||
// found.
|
// found.
|
||||||
int64 now = GetTime();
|
int64 now = GetTime();
|
||||||
std::string newFilename = strprintf("wallet.%"PRI64d".bak", now);
|
std::string newFilename = strprintf("wallet.%" PRI64d ".bak", now);
|
||||||
|
|
||||||
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
|
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
|
||||||
newFilename.c_str(), DB_AUTO_COMMIT);
|
newFilename.c_str(), DB_AUTO_COMMIT);
|
||||||
@ -693,7 +695,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
|
|||||||
printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
|
printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
|
printf("Salvage(aggressive) found %" PRIszu " records\n", salvagedData.size());
|
||||||
|
|
||||||
bool fSuccess = allOK;
|
bool fSuccess = allOK;
|
||||||
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
|
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
|
||||||
@ -710,7 +712,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
|
|||||||
}
|
}
|
||||||
CWallet dummyWallet;
|
CWallet dummyWallet;
|
||||||
int nFileVersion = 0;
|
int nFileVersion = 0;
|
||||||
vector<uint256> vWalletUpgrade;
|
std::vector<uint256> vWalletUpgrade;
|
||||||
bool fIsEncrypted = false;
|
bool fIsEncrypted = false;
|
||||||
bool fAnyUnordered = false;
|
bool fAnyUnordered = false;
|
||||||
|
|
||||||
@ -721,7 +723,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
|
|||||||
{
|
{
|
||||||
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
|
CDataStream 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;
|
||||||
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
|
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
|
||||||
nFileVersion, vWalletUpgrade,
|
nFileVersion, vWalletUpgrade,
|
||||||
fIsEncrypted, fAnyUnordered,
|
fIsEncrypted, fAnyUnordered,
|
||||||
|
Loading…
x
Reference in New Issue
Block a user