Deleted a whole bunch of unused crap
parent
6300009a6e
commit
85ff644d40
528
src/addrman.cpp
528
src/addrman.cpp
|
@ -1,528 +0,0 @@
|
|||
// Copyright (c) 2012 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "addrman.h"
|
||||
#include "hash.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
|
||||
{
|
||||
CDataStream ss1(SER_GETHASH, 0);
|
||||
std::vector<unsigned char> vchKey = GetKey();
|
||||
ss1 << nKey << vchKey;
|
||||
uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
|
||||
|
||||
CDataStream ss2(SER_GETHASH, 0);
|
||||
std::vector<unsigned char> vchGroupKey = GetGroup();
|
||||
ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP);
|
||||
uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
|
||||
return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
|
||||
}
|
||||
|
||||
int CAddrInfo::GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const
|
||||
{
|
||||
CDataStream ss1(SER_GETHASH, 0);
|
||||
std::vector<unsigned char> vchGroupKey = GetGroup();
|
||||
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
|
||||
ss1 << nKey << vchGroupKey << vchSourceGroupKey;
|
||||
uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
|
||||
|
||||
CDataStream ss2(SER_GETHASH, 0);
|
||||
ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP);
|
||||
uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
|
||||
return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
|
||||
}
|
||||
|
||||
bool CAddrInfo::IsTerrible(int64 nNow) const
|
||||
{
|
||||
if (nLastTry && nLastTry >= nNow-60) // never remove things tried the last minute
|
||||
return false;
|
||||
|
||||
if (nTime > nNow + 10*60) // came in a flying DeLorean
|
||||
return true;
|
||||
|
||||
if (nTime==0 || nNow-nTime > ADDRMAN_HORIZON_DAYS*86400) // not seen in over a month
|
||||
return true;
|
||||
|
||||
if (nLastSuccess==0 && nAttempts>=ADDRMAN_RETRIES) // tried three times and never a success
|
||||
return true;
|
||||
|
||||
if (nNow-nLastSuccess > ADDRMAN_MIN_FAIL_DAYS*86400 && nAttempts>=ADDRMAN_MAX_FAILURES) // 10 successive failures in the last week
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
double CAddrInfo::GetChance(int64 nNow) const
|
||||
{
|
||||
double fChance = 1.0;
|
||||
|
||||
int64 nSinceLastSeen = nNow - nTime;
|
||||
int64 nSinceLastTry = nNow - nLastTry;
|
||||
|
||||
if (nSinceLastSeen < 0) nSinceLastSeen = 0;
|
||||
if (nSinceLastTry < 0) nSinceLastTry = 0;
|
||||
|
||||
fChance *= 600.0 / (600.0 + nSinceLastSeen);
|
||||
|
||||
// deprioritize very recent attempts away
|
||||
if (nSinceLastTry < 60*10)
|
||||
fChance *= 0.01;
|
||||
|
||||
// deprioritize 50% after each failed attempt
|
||||
for (int n=0; n<nAttempts; n++)
|
||||
fChance /= 1.5;
|
||||
|
||||
return fChance;
|
||||
}
|
||||
|
||||
CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int *pnId)
|
||||
{
|
||||
std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
|
||||
if (it == mapAddr.end())
|
||||
return NULL;
|
||||
if (pnId)
|
||||
*pnId = (*it).second;
|
||||
std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
|
||||
if (it2 != mapInfo.end())
|
||||
return &(*it2).second;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
CAddrInfo* CAddrMan::Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId)
|
||||
{
|
||||
int nId = nIdCount++;
|
||||
mapInfo[nId] = CAddrInfo(addr, addrSource);
|
||||
mapAddr[addr] = nId;
|
||||
mapInfo[nId].nRandomPos = vRandom.size();
|
||||
vRandom.push_back(nId);
|
||||
if (pnId)
|
||||
*pnId = nId;
|
||||
return &mapInfo[nId];
|
||||
}
|
||||
|
||||
void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2)
|
||||
{
|
||||
if (nRndPos1 == nRndPos2)
|
||||
return;
|
||||
|
||||
assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
|
||||
|
||||
int nId1 = vRandom[nRndPos1];
|
||||
int nId2 = vRandom[nRndPos2];
|
||||
|
||||
assert(mapInfo.count(nId1) == 1);
|
||||
assert(mapInfo.count(nId2) == 1);
|
||||
|
||||
mapInfo[nId1].nRandomPos = nRndPos2;
|
||||
mapInfo[nId2].nRandomPos = nRndPos1;
|
||||
|
||||
vRandom[nRndPos1] = nId2;
|
||||
vRandom[nRndPos2] = nId1;
|
||||
}
|
||||
|
||||
int CAddrMan::SelectTried(int nKBucket)
|
||||
{
|
||||
std::vector<int> &vTried = vvTried[nKBucket];
|
||||
|
||||
// random shuffle the first few elements (using the entire list)
|
||||
// find the least recently tried among them
|
||||
int64 nOldest = -1;
|
||||
int nOldestPos = -1;
|
||||
for (unsigned int i = 0; i < ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT && i < vTried.size(); i++)
|
||||
{
|
||||
int nPos = GetRandInt(vTried.size() - i) + i;
|
||||
int nTemp = vTried[nPos];
|
||||
vTried[nPos] = vTried[i];
|
||||
vTried[i] = nTemp;
|
||||
assert(nOldest == -1 || mapInfo.count(nTemp) == 1);
|
||||
if (nOldest == -1 || mapInfo[nTemp].nLastSuccess < mapInfo[nOldest].nLastSuccess) {
|
||||
nOldest = nTemp;
|
||||
nOldestPos = nPos;
|
||||
}
|
||||
}
|
||||
|
||||
return nOldestPos;
|
||||
}
|
||||
|
||||
int CAddrMan::ShrinkNew(int nUBucket)
|
||||
{
|
||||
assert(nUBucket >= 0 && (unsigned int)nUBucket < vvNew.size());
|
||||
std::set<int> &vNew = vvNew[nUBucket];
|
||||
|
||||
// first look for deletable items
|
||||
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
|
||||
{
|
||||
assert(mapInfo.count(*it));
|
||||
CAddrInfo &info = mapInfo[*it];
|
||||
if (info.IsTerrible())
|
||||
{
|
||||
if (--info.nRefCount == 0)
|
||||
{
|
||||
SwapRandom(info.nRandomPos, vRandom.size()-1);
|
||||
vRandom.pop_back();
|
||||
mapAddr.erase(info);
|
||||
mapInfo.erase(*it);
|
||||
nNew--;
|
||||
}
|
||||
vNew.erase(it);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// otherwise, select four randomly, and pick the oldest of those to replace
|
||||
int n[4] = {GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size())};
|
||||
int nI = 0;
|
||||
int nOldest = -1;
|
||||
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
|
||||
{
|
||||
if (nI == n[0] || nI == n[1] || nI == n[2] || nI == n[3])
|
||||
{
|
||||
assert(nOldest == -1 || mapInfo.count(*it) == 1);
|
||||
if (nOldest == -1 || mapInfo[*it].nTime < mapInfo[nOldest].nTime)
|
||||
nOldest = *it;
|
||||
}
|
||||
nI++;
|
||||
}
|
||||
assert(mapInfo.count(nOldest) == 1);
|
||||
CAddrInfo &info = mapInfo[nOldest];
|
||||
if (--info.nRefCount == 0)
|
||||
{
|
||||
SwapRandom(info.nRandomPos, vRandom.size()-1);
|
||||
vRandom.pop_back();
|
||||
mapAddr.erase(info);
|
||||
mapInfo.erase(nOldest);
|
||||
nNew--;
|
||||
}
|
||||
vNew.erase(nOldest);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
void CAddrMan::MakeTried(CAddrInfo& info, int nId, int nOrigin)
|
||||
{
|
||||
assert(vvNew[nOrigin].count(nId) == 1);
|
||||
|
||||
// remove the entry from all new buckets
|
||||
for (std::vector<std::set<int> >::iterator it = vvNew.begin(); it != vvNew.end(); it++)
|
||||
{
|
||||
if ((*it).erase(nId))
|
||||
info.nRefCount--;
|
||||
}
|
||||
nNew--;
|
||||
|
||||
assert(info.nRefCount == 0);
|
||||
|
||||
// what tried bucket to move the entry to
|
||||
int nKBucket = info.GetTriedBucket(nKey);
|
||||
std::vector<int> &vTried = vvTried[nKBucket];
|
||||
|
||||
// first check whether there is place to just add it
|
||||
if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
|
||||
{
|
||||
vTried.push_back(nId);
|
||||
nTried++;
|
||||
info.fInTried = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// otherwise, find an item to evict
|
||||
int nPos = SelectTried(nKBucket);
|
||||
|
||||
// find which new bucket it belongs to
|
||||
assert(mapInfo.count(vTried[nPos]) == 1);
|
||||
int nUBucket = mapInfo[vTried[nPos]].GetNewBucket(nKey);
|
||||
std::set<int> &vNew = vvNew[nUBucket];
|
||||
|
||||
// remove the to-be-replaced tried entry from the tried set
|
||||
CAddrInfo& infoOld = mapInfo[vTried[nPos]];
|
||||
infoOld.fInTried = false;
|
||||
infoOld.nRefCount = 1;
|
||||
// do not update nTried, as we are going to move something else there immediately
|
||||
|
||||
// check whether there is place in that one,
|
||||
if (vNew.size() < ADDRMAN_NEW_BUCKET_SIZE)
|
||||
{
|
||||
// if so, move it back there
|
||||
vNew.insert(vTried[nPos]);
|
||||
} else {
|
||||
// otherwise, move it to the new bucket nId came from (there is certainly place there)
|
||||
vvNew[nOrigin].insert(vTried[nPos]);
|
||||
}
|
||||
nNew++;
|
||||
|
||||
vTried[nPos] = nId;
|
||||
// we just overwrote an entry in vTried; no need to update nTried
|
||||
info.fInTried = true;
|
||||
return;
|
||||
}
|
||||
|
||||
void CAddrMan::Good_(const CService &addr, int64 nTime)
|
||||
{
|
||||
// printf("Good: addr=%s\n", addr.ToString().c_str());
|
||||
|
||||
int nId;
|
||||
CAddrInfo *pinfo = Find(addr, &nId);
|
||||
|
||||
// if not found, bail out
|
||||
if (!pinfo)
|
||||
return;
|
||||
|
||||
CAddrInfo &info = *pinfo;
|
||||
|
||||
// check whether we are talking about the exact same CService (including same port)
|
||||
if (info != addr)
|
||||
return;
|
||||
|
||||
// update info
|
||||
info.nLastSuccess = nTime;
|
||||
info.nLastTry = nTime;
|
||||
info.nTime = nTime;
|
||||
info.nAttempts = 0;
|
||||
|
||||
// if it is already in the tried set, don't do anything else
|
||||
if (info.fInTried)
|
||||
return;
|
||||
|
||||
// find a bucket it is in now
|
||||
int nRnd = GetRandInt(vvNew.size());
|
||||
int nUBucket = -1;
|
||||
for (unsigned int n = 0; n < vvNew.size(); n++)
|
||||
{
|
||||
int nB = (n+nRnd) % vvNew.size();
|
||||
std::set<int> &vNew = vvNew[nB];
|
||||
if (vNew.count(nId))
|
||||
{
|
||||
nUBucket = nB;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// if no bucket is found, something bad happened;
|
||||
// TODO: maybe re-add the node, but for now, just bail out
|
||||
if (nUBucket == -1) return;
|
||||
|
||||
printf("Moving %s to tried\n", addr.ToString().c_str());
|
||||
|
||||
// move nId to the tried tables
|
||||
MakeTried(info, nId, nUBucket);
|
||||
}
|
||||
|
||||
bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty)
|
||||
{
|
||||
if (!addr.IsRoutable())
|
||||
return false;
|
||||
|
||||
bool fNew = false;
|
||||
int nId;
|
||||
CAddrInfo *pinfo = Find(addr, &nId);
|
||||
|
||||
if (pinfo)
|
||||
{
|
||||
// periodically update nTime
|
||||
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
|
||||
int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
|
||||
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
|
||||
pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
|
||||
|
||||
// add services
|
||||
pinfo->nServices |= addr.nServices;
|
||||
|
||||
// do not update if no new information is present
|
||||
if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
|
||||
return false;
|
||||
|
||||
// do not update if the entry was already in the "tried" table
|
||||
if (pinfo->fInTried)
|
||||
return false;
|
||||
|
||||
// do not update if the max reference count is reached
|
||||
if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
|
||||
return false;
|
||||
|
||||
// stochastic test: previous nRefCount == N: 2^N times harder to increase it
|
||||
int nFactor = 1;
|
||||
for (int n=0; n<pinfo->nRefCount; n++)
|
||||
nFactor *= 2;
|
||||
if (nFactor > 1 && (GetRandInt(nFactor) != 0))
|
||||
return false;
|
||||
} else {
|
||||
pinfo = Create(addr, source, &nId);
|
||||
pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
|
||||
// printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
|
||||
nNew++;
|
||||
fNew = true;
|
||||
}
|
||||
|
||||
int nUBucket = pinfo->GetNewBucket(nKey, source);
|
||||
std::set<int> &vNew = vvNew[nUBucket];
|
||||
if (!vNew.count(nId))
|
||||
{
|
||||
pinfo->nRefCount++;
|
||||
if (vNew.size() == ADDRMAN_NEW_BUCKET_SIZE)
|
||||
ShrinkNew(nUBucket);
|
||||
vvNew[nUBucket].insert(nId);
|
||||
}
|
||||
return fNew;
|
||||
}
|
||||
|
||||
void CAddrMan::Attempt_(const CService &addr, int64 nTime)
|
||||
{
|
||||
CAddrInfo *pinfo = Find(addr);
|
||||
|
||||
// if not found, bail out
|
||||
if (!pinfo)
|
||||
return;
|
||||
|
||||
CAddrInfo &info = *pinfo;
|
||||
|
||||
// check whether we are talking about the exact same CService (including same port)
|
||||
if (info != addr)
|
||||
return;
|
||||
|
||||
// update info
|
||||
info.nLastTry = nTime;
|
||||
info.nAttempts++;
|
||||
}
|
||||
|
||||
CAddress CAddrMan::Select_(int nUnkBias)
|
||||
{
|
||||
if (size() == 0)
|
||||
return CAddress();
|
||||
|
||||
double nCorTried = sqrt(nTried) * (100.0 - nUnkBias);
|
||||
double nCorNew = sqrt(nNew) * nUnkBias;
|
||||
if ((nCorTried + nCorNew)*GetRandInt(1<<30)/(1<<30) < nCorTried)
|
||||
{
|
||||
// use a tried node
|
||||
double fChanceFactor = 1.0;
|
||||
while(1)
|
||||
{
|
||||
int nKBucket = GetRandInt(vvTried.size());
|
||||
std::vector<int> &vTried = vvTried[nKBucket];
|
||||
if (vTried.size() == 0) continue;
|
||||
int nPos = GetRandInt(vTried.size());
|
||||
assert(mapInfo.count(vTried[nPos]) == 1);
|
||||
CAddrInfo &info = mapInfo[vTried[nPos]];
|
||||
if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
|
||||
return info;
|
||||
fChanceFactor *= 1.2;
|
||||
}
|
||||
} else {
|
||||
// use a new node
|
||||
double fChanceFactor = 1.0;
|
||||
while(1)
|
||||
{
|
||||
int nUBucket = GetRandInt(vvNew.size());
|
||||
std::set<int> &vNew = vvNew[nUBucket];
|
||||
if (vNew.size() == 0) continue;
|
||||
int nPos = GetRandInt(vNew.size());
|
||||
std::set<int>::iterator it = vNew.begin();
|
||||
while (nPos--)
|
||||
it++;
|
||||
assert(mapInfo.count(*it) == 1);
|
||||
CAddrInfo &info = mapInfo[*it];
|
||||
if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
|
||||
return info;
|
||||
fChanceFactor *= 1.2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_ADDRMAN
|
||||
int CAddrMan::Check_()
|
||||
{
|
||||
std::set<int> setTried;
|
||||
std::map<int, int> mapNew;
|
||||
|
||||
if (vRandom.size() != nTried + nNew) return -7;
|
||||
|
||||
for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
|
||||
{
|
||||
int n = (*it).first;
|
||||
CAddrInfo &info = (*it).second;
|
||||
if (info.fInTried)
|
||||
{
|
||||
|
||||
if (!info.nLastSuccess) return -1;
|
||||
if (info.nRefCount) return -2;
|
||||
setTried.insert(n);
|
||||
} else {
|
||||
if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3;
|
||||
if (!info.nRefCount) return -4;
|
||||
mapNew[n] = info.nRefCount;
|
||||
}
|
||||
if (mapAddr[info] != n) return -5;
|
||||
if (info.nRandomPos<0 || info.nRandomPos>=vRandom.size() || vRandom[info.nRandomPos] != n) return -14;
|
||||
if (info.nLastTry < 0) return -6;
|
||||
if (info.nLastSuccess < 0) return -8;
|
||||
}
|
||||
|
||||
if (setTried.size() != nTried) return -9;
|
||||
if (mapNew.size() != nNew) return -10;
|
||||
|
||||
for (int n=0; n<vvTried.size(); n++)
|
||||
{
|
||||
std::vector<int> &vTried = vvTried[n];
|
||||
for (std::vector<int>::iterator it = vTried.begin(); it != vTried.end(); it++)
|
||||
{
|
||||
if (!setTried.count(*it)) return -11;
|
||||
setTried.erase(*it);
|
||||
}
|
||||
}
|
||||
|
||||
for (int n=0; n<vvNew.size(); n++)
|
||||
{
|
||||
std::set<int> &vNew = vvNew[n];
|
||||
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
|
||||
{
|
||||
if (!mapNew.count(*it)) return -12;
|
||||
if (--mapNew[*it] == 0)
|
||||
mapNew.erase(*it);
|
||||
}
|
||||
}
|
||||
|
||||
if (setTried.size()) return -13;
|
||||
if (mapNew.size()) return -15;
|
||||
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
void CAddrMan::GetAddr_(std::vector<CAddress> &vAddr)
|
||||
{
|
||||
int nNodes = ADDRMAN_GETADDR_MAX_PCT*vRandom.size()/100;
|
||||
if (nNodes > ADDRMAN_GETADDR_MAX)
|
||||
nNodes = ADDRMAN_GETADDR_MAX;
|
||||
|
||||
// perform a random shuffle over the first nNodes elements of vRandom (selecting from all)
|
||||
for (int n = 0; n<nNodes; n++)
|
||||
{
|
||||
int nRndPos = GetRandInt(vRandom.size() - n) + n;
|
||||
SwapRandom(n, nRndPos);
|
||||
assert(mapInfo.count(vRandom[n]) == 1);
|
||||
vAddr.push_back(mapInfo[vRandom[n]]);
|
||||
}
|
||||
}
|
||||
|
||||
void CAddrMan::Connected_(const CService &addr, int64 nTime)
|
||||
{
|
||||
CAddrInfo *pinfo = Find(addr);
|
||||
|
||||
// if not found, bail out
|
||||
if (!pinfo)
|
||||
return;
|
||||
|
||||
CAddrInfo &info = *pinfo;
|
||||
|
||||
// check whether we are talking about the exact same CService (including same port)
|
||||
if (info != addr)
|
||||
return;
|
||||
|
||||
// update info
|
||||
int64 nUpdateInterval = 20 * 60;
|
||||
if (nTime - info.nTime > nUpdateInterval)
|
||||
info.nTime = nTime;
|
||||
}
|
503
src/addrman.h
503
src/addrman.h
|
@ -1,503 +0,0 @@
|
|||
// Copyright (c) 2012 Pieter Wuille
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef _BITCOIN_ADDRMAN
|
||||
#define _BITCOIN_ADDRMAN 1
|
||||
|
||||
#include "netbase.h"
|
||||
#include "protocol.h"
|
||||
#include "util.h"
|
||||
#include "sync.h"
|
||||
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
#include <openssl/rand.h>
|
||||
|
||||
|
||||
/** Extended statistics about a CAddress */
|
||||
class CAddrInfo : public CAddress
|
||||
{
|
||||
private:
|
||||
// where knowledge about this address first came from
|
||||
CNetAddr source;
|
||||
|
||||
// last successful connection by us
|
||||
int64 nLastSuccess;
|
||||
|
||||
// last try whatsoever by us:
|
||||
// int64 CAddress::nLastTry
|
||||
|
||||
// connection attempts since last successful attempt
|
||||
int nAttempts;
|
||||
|
||||
// reference count in new sets (memory only)
|
||||
int nRefCount;
|
||||
|
||||
// in tried set? (memory only)
|
||||
bool fInTried;
|
||||
|
||||
// position in vRandom
|
||||
int nRandomPos;
|
||||
|
||||
friend class CAddrMan;
|
||||
|
||||
public:
|
||||
|
||||
IMPLEMENT_SERIALIZE(
|
||||
CAddress* pthis = (CAddress*)(this);
|
||||
READWRITE(*pthis);
|
||||
READWRITE(source);
|
||||
READWRITE(nLastSuccess);
|
||||
READWRITE(nAttempts);
|
||||
)
|
||||
|
||||
void Init()
|
||||
{
|
||||
nLastSuccess = 0;
|
||||
nLastTry = 0;
|
||||
nAttempts = 0;
|
||||
nRefCount = 0;
|
||||
fInTried = false;
|
||||
nRandomPos = -1;
|
||||
}
|
||||
|
||||
CAddrInfo(const CAddress &addrIn, const CNetAddr &addrSource) : CAddress(addrIn), source(addrSource)
|
||||
{
|
||||
Init();
|
||||
}
|
||||
|
||||
CAddrInfo() : CAddress(), source()
|
||||
{
|
||||
Init();
|
||||
}
|
||||
|
||||
// Calculate in which "tried" bucket this entry belongs
|
||||
int GetTriedBucket(const std::vector<unsigned char> &nKey) const;
|
||||
|
||||
// Calculate in which "new" bucket this entry belongs, given a certain source
|
||||
int GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const;
|
||||
|
||||
// Calculate in which "new" bucket this entry belongs, using its default source
|
||||
int GetNewBucket(const std::vector<unsigned char> &nKey) const
|
||||
{
|
||||
return GetNewBucket(nKey, source);
|
||||
}
|
||||
|
||||
// Determine whether the statistics about this entry are bad enough so that it can just be deleted
|
||||
bool IsTerrible(int64 nNow = GetAdjustedTime()) const;
|
||||
|
||||
// Calculate the relative chance this entry should be given when selecting nodes to connect to
|
||||
double GetChance(int64 nNow = GetAdjustedTime()) const;
|
||||
|
||||
};
|
||||
|
||||
// Stochastic address manager
|
||||
//
|
||||
// Design goals:
|
||||
// * Only keep a limited number of addresses around, so that addr.dat and memory requirements do not grow without bound.
|
||||
// * Keep the address tables in-memory, and asynchronously dump the entire to able in addr.dat.
|
||||
// * Make sure no (localized) attacker can fill the entire table with his nodes/addresses.
|
||||
//
|
||||
// To that end:
|
||||
// * Addresses are organized into buckets.
|
||||
// * Address that have not yet been tried go into 256 "new" buckets.
|
||||
// * Based on the address range (/16 for IPv4) of source of the information, 32 buckets are selected at random
|
||||
// * The actual bucket is chosen from one of these, based on the range the address itself is located.
|
||||
// * One single address can occur in up to 4 different buckets, to increase selection chances for addresses that
|
||||
// are seen frequently. The chance for increasing this multiplicity decreases exponentially.
|
||||
// * When adding a new address to a full bucket, a randomly chosen entry (with a bias favoring less recently seen
|
||||
// ones) is removed from it first.
|
||||
// * Addresses of nodes that are known to be accessible go into 64 "tried" buckets.
|
||||
// * Each address range selects at random 4 of these buckets.
|
||||
// * The actual bucket is chosen from one of these, based on the full address.
|
||||
// * When adding a new good address to a full bucket, a randomly chosen entry (with a bias favoring less recently
|
||||
// tried ones) is evicted from it, back to the "new" buckets.
|
||||
// * Bucket selection is based on cryptographic hashing, using a randomly-generated 256-bit key, which should not
|
||||
// be observable by adversaries.
|
||||
// * Several indexes are kept for high performance. Defining DEBUG_ADDRMAN will introduce frequent (and expensive)
|
||||
// consistency checks for the entire data structure.
|
||||
|
||||
// total number of buckets for tried addresses
|
||||
#define ADDRMAN_TRIED_BUCKET_COUNT 64
|
||||
|
||||
// maximum allowed number of entries in buckets for tried addresses
|
||||
#define ADDRMAN_TRIED_BUCKET_SIZE 64
|
||||
|
||||
// total number of buckets for new addresses
|
||||
#define ADDRMAN_NEW_BUCKET_COUNT 256
|
||||
|
||||
// maximum allowed number of entries in buckets for new addresses
|
||||
#define ADDRMAN_NEW_BUCKET_SIZE 64
|
||||
|
||||
// over how many buckets entries with tried addresses from a single group (/16 for IPv4) are spread
|
||||
#define ADDRMAN_TRIED_BUCKETS_PER_GROUP 4
|
||||
|
||||
// over how many buckets entries with new addresses originating from a single group are spread
|
||||
#define ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP 32
|
||||
|
||||
// in how many buckets for entries with new addresses a single address may occur
|
||||
#define ADDRMAN_NEW_BUCKETS_PER_ADDRESS 4
|
||||
|
||||
// how many entries in a bucket with tried addresses are inspected, when selecting one to replace
|
||||
#define ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT 4
|
||||
|
||||
// how old addresses can maximally be
|
||||
#define ADDRMAN_HORIZON_DAYS 30
|
||||
|
||||
// after how many failed attempts we give up on a new node
|
||||
#define ADDRMAN_RETRIES 3
|
||||
|
||||
// how many successive failures are allowed ...
|
||||
#define ADDRMAN_MAX_FAILURES 10
|
||||
|
||||
// ... in at least this many days
|
||||
#define ADDRMAN_MIN_FAIL_DAYS 7
|
||||
|
||||
// the maximum percentage of nodes to return in a getaddr call
|
||||
#define ADDRMAN_GETADDR_MAX_PCT 23
|
||||
|
||||
// the maximum number of nodes to return in a getaddr call
|
||||
#define ADDRMAN_GETADDR_MAX 2500
|
||||
|
||||
/** Stochastical (IP) address manager */
|
||||
class CAddrMan
|
||||
{
|
||||
private:
|
||||
// critical section to protect the inner data structures
|
||||
mutable CCriticalSection cs;
|
||||
|
||||
// secret key to randomize bucket select with
|
||||
std::vector<unsigned char> nKey;
|
||||
|
||||
// last used nId
|
||||
int nIdCount;
|
||||
|
||||
// table with information about all nIds
|
||||
std::map<int, CAddrInfo> mapInfo;
|
||||
|
||||
// find an nId based on its network address
|
||||
std::map<CNetAddr, int> mapAddr;
|
||||
|
||||
// randomly-ordered vector of all nIds
|
||||
std::vector<int> vRandom;
|
||||
|
||||
// number of "tried" entries
|
||||
int nTried;
|
||||
|
||||
// list of "tried" buckets
|
||||
std::vector<std::vector<int> > vvTried;
|
||||
|
||||
// number of (unique) "new" entries
|
||||
int nNew;
|
||||
|
||||
// list of "new" buckets
|
||||
std::vector<std::set<int> > vvNew;
|
||||
|
||||
protected:
|
||||
|
||||
// Find an entry.
|
||||
CAddrInfo* Find(const CNetAddr& addr, int *pnId = NULL);
|
||||
|
||||
// find an entry, creating it if necessary.
|
||||
// nTime and nServices of found node is updated, if necessary.
|
||||
CAddrInfo* Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId = NULL);
|
||||
|
||||
// Swap two elements in vRandom.
|
||||
void SwapRandom(unsigned int nRandomPos1, unsigned int nRandomPos2);
|
||||
|
||||
// Return position in given bucket to replace.
|
||||
int SelectTried(int nKBucket);
|
||||
|
||||
// Remove an element from a "new" bucket.
|
||||
// This is the only place where actual deletes occur.
|
||||
// They are never deleted while in the "tried" table, only possibly evicted back to the "new" table.
|
||||
int ShrinkNew(int nUBucket);
|
||||
|
||||
// Move an entry from the "new" table(s) to the "tried" table
|
||||
// @pre vvUnkown[nOrigin].count(nId) != 0
|
||||
void MakeTried(CAddrInfo& info, int nId, int nOrigin);
|
||||
|
||||
// Mark an entry "good", possibly moving it from "new" to "tried".
|
||||
void Good_(const CService &addr, int64 nTime);
|
||||
|
||||
// Add an entry to the "new" table.
|
||||
bool Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty);
|
||||
|
||||
// Mark an entry as attempted to connect.
|
||||
void Attempt_(const CService &addr, int64 nTime);
|
||||
|
||||
// Select an address to connect to.
|
||||
// nUnkBias determines how much to favor new addresses over tried ones (min=0, max=100)
|
||||
CAddress Select_(int nUnkBias);
|
||||
|
||||
#ifdef DEBUG_ADDRMAN
|
||||
// Perform consistency check. Returns an error code or zero.
|
||||
int Check_();
|
||||
#endif
|
||||
|
||||
// Select several addresses at once.
|
||||
void GetAddr_(std::vector<CAddress> &vAddr);
|
||||
|
||||
// Mark an entry as currently-connected-to.
|
||||
void Connected_(const CService &addr, int64 nTime);
|
||||
|
||||
public:
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(({
|
||||
// serialized format:
|
||||
// * version byte (currently 0)
|
||||
// * nKey
|
||||
// * nNew
|
||||
// * nTried
|
||||
// * number of "new" buckets
|
||||
// * all nNew addrinfos in vvNew
|
||||
// * all nTried addrinfos in vvTried
|
||||
// * for each bucket:
|
||||
// * number of elements
|
||||
// * for each element: index
|
||||
//
|
||||
// Notice that vvTried, mapAddr and vVector are never encoded explicitly;
|
||||
// they are instead reconstructed from the other information.
|
||||
//
|
||||
// vvNew is serialized, but only used if ADDRMAN_UNKOWN_BUCKET_COUNT didn't change,
|
||||
// otherwise it is reconstructed as well.
|
||||
//
|
||||
// This format is more complex, but significantly smaller (at most 1.5 MiB), and supports
|
||||
// changes to the ADDRMAN_ parameters without breaking the on-disk structure.
|
||||
{
|
||||
LOCK(cs);
|
||||
unsigned char nVersion = 0;
|
||||
READWRITE(nVersion);
|
||||
READWRITE(nKey);
|
||||
READWRITE(nNew);
|
||||
READWRITE(nTried);
|
||||
|
||||
CAddrMan *am = const_cast<CAddrMan*>(this);
|
||||
if (fWrite)
|
||||
{
|
||||
int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT;
|
||||
READWRITE(nUBuckets);
|
||||
std::map<int, int> mapUnkIds;
|
||||
int nIds = 0;
|
||||
for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
|
||||
{
|
||||
if (nIds == nNew) break; // this means nNew was wrong, oh ow
|
||||
mapUnkIds[(*it).first] = nIds;
|
||||
CAddrInfo &info = (*it).second;
|
||||
if (info.nRefCount)
|
||||
{
|
||||
READWRITE(info);
|
||||
nIds++;
|
||||
}
|
||||
}
|
||||
nIds = 0;
|
||||
for (std::map<int, CAddrInfo>::iterator it = am->mapInfo.begin(); it != am->mapInfo.end(); it++)
|
||||
{
|
||||
if (nIds == nTried) break; // this means nTried was wrong, oh ow
|
||||
CAddrInfo &info = (*it).second;
|
||||
if (info.fInTried)
|
||||
{
|
||||
READWRITE(info);
|
||||
nIds++;
|
||||
}
|
||||
}
|
||||
for (std::vector<std::set<int> >::iterator it = am->vvNew.begin(); it != am->vvNew.end(); it++)
|
||||
{
|
||||
const std::set<int> &vNew = (*it);
|
||||
int nSize = vNew.size();
|
||||
READWRITE(nSize);
|
||||
for (std::set<int>::iterator it2 = vNew.begin(); it2 != vNew.end(); it2++)
|
||||
{
|
||||
int nIndex = mapUnkIds[*it2];
|
||||
READWRITE(nIndex);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int nUBuckets = 0;
|
||||
READWRITE(nUBuckets);
|
||||
am->nIdCount = 0;
|
||||
am->mapInfo.clear();
|
||||
am->mapAddr.clear();
|
||||
am->vRandom.clear();
|
||||
am->vvTried = std::vector<std::vector<int> >(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0));
|
||||
am->vvNew = std::vector<std::set<int> >(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>());
|
||||
for (int n = 0; n < am->nNew; n++)
|
||||
{
|
||||
CAddrInfo &info = am->mapInfo[n];
|
||||
READWRITE(info);
|
||||
am->mapAddr[info] = n;
|
||||
info.nRandomPos = vRandom.size();
|
||||
am->vRandom.push_back(n);
|
||||
if (nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
|
||||
{
|
||||
am->vvNew[info.GetNewBucket(am->nKey)].insert(n);
|
||||
info.nRefCount++;
|
||||
}
|
||||
}
|
||||
am->nIdCount = am->nNew;
|
||||
int nLost = 0;
|
||||
for (int n = 0; n < am->nTried; n++)
|
||||
{
|
||||
CAddrInfo info;
|
||||
READWRITE(info);
|
||||
std::vector<int> &vTried = am->vvTried[info.GetTriedBucket(am->nKey)];
|
||||
if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
|
||||
{
|
||||
info.nRandomPos = vRandom.size();
|
||||
info.fInTried = true;
|
||||
am->vRandom.push_back(am->nIdCount);
|
||||
am->mapInfo[am->nIdCount] = info;
|
||||
am->mapAddr[info] = am->nIdCount;
|
||||
vTried.push_back(am->nIdCount);
|
||||
am->nIdCount++;
|
||||
} else {
|
||||
nLost++;
|
||||
}
|
||||
}
|
||||
am->nTried -= nLost;
|
||||
for (int b = 0; b < nUBuckets; b++)
|
||||
{
|
||||
std::set<int> &vNew = am->vvNew[b];
|
||||
int nSize = 0;
|
||||
READWRITE(nSize);
|
||||
for (int n = 0; n < nSize; n++)
|
||||
{
|
||||
int nIndex = 0;
|
||||
READWRITE(nIndex);
|
||||
CAddrInfo &info = am->mapInfo[nIndex];
|
||||
if (nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
|
||||
{
|
||||
info.nRefCount++;
|
||||
vNew.insert(nIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});)
|
||||
|
||||
CAddrMan() : vRandom(0), vvTried(ADDRMAN_TRIED_BUCKET_COUNT, std::vector<int>(0)), vvNew(ADDRMAN_NEW_BUCKET_COUNT, std::set<int>())
|
||||
{
|
||||
nKey.resize(32);
|
||||
RAND_bytes(&nKey[0], 32);
|
||||
|
||||
nIdCount = 0;
|
||||
nTried = 0;
|
||||
nNew = 0;
|
||||
}
|
||||
|
||||
// Return the number of (unique) addresses in all tables.
|
||||
int size()
|
||||
{
|
||||
return vRandom.size();
|
||||
}
|
||||
|
||||
// Consistency check
|
||||
void Check()
|
||||
{
|
||||
#ifdef DEBUG_ADDRMAN
|
||||
{
|
||||
LOCK(cs);
|
||||
int err;
|
||||
if ((err=Check_()))
|
||||
printf("ADDRMAN CONSISTENCY CHECK FAILED!!! err=%i\n", err);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Add a single address.
|
||||
bool Add(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty = 0)
|
||||
{
|
||||
bool fRet = false;
|
||||
{
|
||||
LOCK(cs);
|
||||
Check();
|
||||
fRet |= Add_(addr, source, nTimePenalty);
|
||||
Check();
|
||||
}
|
||||
if (fRet)
|
||||
printf("Added %s from %s: %i tried, %i new\n", addr.ToStringIPPort().c_str(), source.ToString().c_str(), nTried, nNew);
|
||||
return fRet;
|
||||
}
|
||||
|
||||
// Add multiple addresses.
|
||||
bool Add(const std::vector<CAddress> &vAddr, const CNetAddr& source, int64 nTimePenalty = 0)
|
||||
{
|
||||
int nAdd = 0;
|
||||
{
|
||||
LOCK(cs);
|
||||
Check();
|
||||
for (std::vector<CAddress>::const_iterator it = vAddr.begin(); it != vAddr.end(); it++)
|
||||
nAdd += Add_(*it, source, nTimePenalty) ? 1 : 0;
|
||||
Check();
|
||||
}
|
||||
if (nAdd)
|
||||
printf("Added %i addresses from %s: %i tried, %i new\n", nAdd, source.ToString().c_str(), nTried, nNew);
|
||||
return nAdd > 0;
|
||||
}
|
||||
|
||||
// Mark an entry as accessible.
|
||||
void Good(const CService &addr, int64 nTime = GetAdjustedTime())
|
||||
{
|
||||
{
|
||||
LOCK(cs);
|
||||
Check();
|
||||
Good_(addr, nTime);
|
||||
Check();
|
||||
}
|
||||
}
|
||||
|
||||
// Mark an entry as connection attempted to.
|
||||
void Attempt(const CService &addr, int64 nTime = GetAdjustedTime())
|
||||
{
|
||||
{
|
||||
LOCK(cs);
|
||||
Check();
|
||||
Attempt_(addr, nTime);
|
||||
Check();
|
||||
}
|
||||
}
|
||||
|
||||
// Choose an address to connect to.
|
||||
// nUnkBias determines how much "new" entries are favored over "tried" ones (0-100).
|
||||
CAddress Select(int nUnkBias = 50)
|
||||
{
|
||||
CAddress addrRet;
|
||||
{
|
||||
LOCK(cs);
|
||||
Check();
|
||||
addrRet = Select_(nUnkBias);
|
||||
Check();
|
||||
}
|
||||
return addrRet;
|
||||
}
|
||||
|
||||
// Return a bunch of addresses, selected at random.
|
||||
std::vector<CAddress> GetAddr()
|
||||
{
|
||||
Check();
|
||||
std::vector<CAddress> vAddr;
|
||||
{
|
||||
LOCK(cs);
|
||||
GetAddr_(vAddr);
|
||||
}
|
||||
Check();
|
||||
return vAddr;
|
||||
}
|
||||
|
||||
// Mark an entry as currently-connected-to.
|
||||
void Connected(const CService &addr, int64 nTime = GetAdjustedTime())
|
||||
{
|
||||
{
|
||||
LOCK(cs);
|
||||
Check();
|
||||
Connected_(addr, nTime);
|
||||
Check();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
268
src/alert.cpp
268
src/alert.cpp
|
@ -1,268 +0,0 @@
|
|||
//
|
||||
// Alert system
|
||||
//
|
||||
|
||||
#include <algorithm>
|
||||
#include <boost/algorithm/string/classification.hpp>
|
||||
#include <boost/algorithm/string/replace.hpp>
|
||||
#include <boost/foreach.hpp>
|
||||
#include <map>
|
||||
|
||||
#include "alert.h"
|
||||
#include "key.h"
|
||||
#include "net.h"
|
||||
#include "sync.h"
|
||||
#include "ui_interface.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
map<uint256, CAlert> mapAlerts;
|
||||
CCriticalSection cs_mapAlerts;
|
||||
|
||||
static const char* pszMainKey = "04a0a5a88b2cebf0d6a7d20214e6bd51c903645505f72d05d536c9f3b996ec428150931cc6e9943f8603f756907b8793d715cb3b4fcca2735110c324c98158f456";
|
||||
static const char* pszTestKey = "0400a665daf19bf39db0d2072ea4edd5ca7a9070b81001934bfd4fa0d12561b105be22ea92c4608555f97819ffeb1c80cd701fcc43cd6a38ceefb128699e593aa3";
|
||||
|
||||
void CUnsignedAlert::SetNull()
|
||||
{
|
||||
nVersion = 1;
|
||||
nRelayUntil = 0;
|
||||
nExpiration = 0;
|
||||
nID = 0;
|
||||
nCancel = 0;
|
||||
setCancel.clear();
|
||||
nMinVer = 0;
|
||||
nMaxVer = 0;
|
||||
setSubVer.clear();
|
||||
nPriority = 0;
|
||||
|
||||
strComment.clear();
|
||||
strStatusBar.clear();
|
||||
strReserved.clear();
|
||||
}
|
||||
|
||||
std::string CUnsignedAlert::ToString() const
|
||||
{
|
||||
std::string strSetCancel;
|
||||
BOOST_FOREACH(int n, setCancel)
|
||||
strSetCancel += strprintf("%d ", n);
|
||||
std::string strSetSubVer;
|
||||
BOOST_FOREACH(std::string str, setSubVer)
|
||||
strSetSubVer += "\"" + str + "\" ";
|
||||
return strprintf(
|
||||
"CAlert(\n"
|
||||
" nVersion = %d\n"
|
||||
" nRelayUntil = %"PRI64d"\n"
|
||||
" nExpiration = %"PRI64d"\n"
|
||||
" nID = %d\n"
|
||||
" nCancel = %d\n"
|
||||
" setCancel = %s\n"
|
||||
" nMinVer = %d\n"
|
||||
" nMaxVer = %d\n"
|
||||
" setSubVer = %s\n"
|
||||
" nPriority = %d\n"
|
||||
" strComment = \"%s\"\n"
|
||||
" strStatusBar = \"%s\"\n"
|
||||
")\n",
|
||||
nVersion,
|
||||
nRelayUntil,
|
||||
nExpiration,
|
||||
nID,
|
||||
nCancel,
|
||||
strSetCancel.c_str(),
|
||||
nMinVer,
|
||||
nMaxVer,
|
||||
strSetSubVer.c_str(),
|
||||
nPriority,
|
||||
strComment.c_str(),
|
||||
strStatusBar.c_str());
|
||||
}
|
||||
|
||||
void CUnsignedAlert::print() const
|
||||
{
|
||||
printf("%s", ToString().c_str());
|
||||
}
|
||||
|
||||
void CAlert::SetNull()
|
||||
{
|
||||
CUnsignedAlert::SetNull();
|
||||
vchMsg.clear();
|
||||
vchSig.clear();
|
||||
}
|
||||
|
||||
bool CAlert::IsNull() const
|
||||
{
|
||||
return (nExpiration == 0);
|
||||
}
|
||||
|
||||
uint256 CAlert::GetHash() const
|
||||
{
|
||||
return Hash(this->vchMsg.begin(), this->vchMsg.end());
|
||||
}
|
||||
|
||||
bool CAlert::IsInEffect() const
|
||||
{
|
||||
return (GetAdjustedTime() < nExpiration);
|
||||
}
|
||||
|
||||
bool CAlert::Cancels(const CAlert& alert) const
|
||||
{
|
||||
if (!IsInEffect())
|
||||
return false; // this was a no-op before 31403
|
||||
return (alert.nID <= nCancel || setCancel.count(alert.nID));
|
||||
}
|
||||
|
||||
bool CAlert::AppliesTo(int nVersion, std::string strSubVerIn) const
|
||||
{
|
||||
// TODO: rework for client-version-embedded-in-strSubVer ?
|
||||
return (IsInEffect() &&
|
||||
nMinVer <= nVersion && nVersion <= nMaxVer &&
|
||||
(setSubVer.empty() || setSubVer.count(strSubVerIn)));
|
||||
}
|
||||
|
||||
bool CAlert::AppliesToMe() const
|
||||
{
|
||||
return AppliesTo(PROTOCOL_VERSION, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>()));
|
||||
}
|
||||
|
||||
bool CAlert::RelayTo(CNode* pnode) const
|
||||
{
|
||||
if (!IsInEffect())
|
||||
return false;
|
||||
// returns true if wasn't already contained in the set
|
||||
if (pnode->setKnown.insert(GetHash()).second)
|
||||
{
|
||||
if (AppliesTo(pnode->nVersion, pnode->strSubVer) ||
|
||||
AppliesToMe() ||
|
||||
GetAdjustedTime() < nRelayUntil)
|
||||
{
|
||||
pnode->PushMessage("alert", *this);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CAlert::CheckSignature() const
|
||||
{
|
||||
CKey key;
|
||||
if (!key.SetPubKey(ParseHex(fTestNet ? pszTestKey : pszMainKey)))
|
||||
return error("CAlert::CheckSignature() : SetPubKey failed");
|
||||
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
|
||||
return error("CAlert::CheckSignature() : verify signature failed");
|
||||
|
||||
// Now unserialize the data
|
||||
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
|
||||
sMsg >> *(CUnsignedAlert*)this;
|
||||
return true;
|
||||
}
|
||||
|
||||
CAlert CAlert::getAlertByHash(const uint256 &hash)
|
||||
{
|
||||
CAlert retval;
|
||||
{
|
||||
LOCK(cs_mapAlerts);
|
||||
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
|
||||
if(mi != mapAlerts.end())
|
||||
retval = mi->second;
|
||||
}
|
||||
return retval;
|
||||
}
|
||||
|
||||
bool CAlert::ProcessAlert(bool fThread)
|
||||
{
|
||||
if (!CheckSignature())
|
||||
return false;
|
||||
if (!IsInEffect())
|
||||
return false;
|
||||
|
||||
// alert.nID=max is reserved for if the alert key is
|
||||
// compromised. It must have a pre-defined message,
|
||||
// must never expire, must apply to all versions,
|
||||
// and must cancel all previous
|
||||
// alerts or it will be ignored (so an attacker can't
|
||||
// send an "everything is OK, don't panic" version that
|
||||
// cannot be overridden):
|
||||
int maxInt = std::numeric_limits<int>::max();
|
||||
if (nID == maxInt)
|
||||
{
|
||||
if (!(
|
||||
nExpiration == maxInt &&
|
||||
nCancel == (maxInt-1) &&
|
||||
nMinVer == 0 &&
|
||||
nMaxVer == maxInt &&
|
||||
setSubVer.empty() &&
|
||||
nPriority == maxInt &&
|
||||
strStatusBar == "URGENT: Alert key compromised, upgrade required"
|
||||
))
|
||||
return false;
|
||||
}
|
||||
|
||||
{
|
||||
LOCK(cs_mapAlerts);
|
||||
// Cancel previous alerts
|
||||
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
|
||||
{
|
||||
const CAlert& alert = (*mi).second;
|
||||
if (Cancels(alert))
|
||||
{
|
||||
printf("cancelling alert %d\n", alert.nID);
|
||||
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
|
||||
mapAlerts.erase(mi++);
|
||||
}
|
||||
else if (!alert.IsInEffect())
|
||||
{
|
||||
printf("expiring alert %d\n", alert.nID);
|
||||
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
|
||||
mapAlerts.erase(mi++);
|
||||
}
|
||||
else
|
||||
mi++;
|
||||
}
|
||||
|
||||
// Check if this alert has been cancelled
|
||||
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
|
||||
{
|
||||
const CAlert& alert = item.second;
|
||||
if (alert.Cancels(*this))
|
||||
{
|
||||
printf("alert already cancelled by %d\n", alert.nID);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Add to mapAlerts
|
||||
mapAlerts.insert(make_pair(GetHash(), *this));
|
||||
// Notify UI and -alertnotify if it applies to me
|
||||
if(AppliesToMe())
|
||||
{
|
||||
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
|
||||
std::string strCmd = GetArg("-alertnotify", "");
|
||||
if (!strCmd.empty())
|
||||
{
|
||||
// Alert text should be plain ascii coming from a trusted source, but to
|
||||
// be safe we first strip anything not in safeChars, then add single quotes around
|
||||
// the whole string before passing it to the shell:
|
||||
std::string singleQuote("'");
|
||||
// safeChars chosen to allow simple messages/URLs/email addresses, but avoid anything
|
||||
// even possibly remotely dangerous like & or >
|
||||
std::string safeChars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 .,;_/:?@");
|
||||
std::string safeStatus;
|
||||
for (std::string::size_type i = 0; i < strStatusBar.size(); i++)
|
||||
{
|
||||
if (safeChars.find(strStatusBar[i]) != std::string::npos)
|
||||
safeStatus.push_back(strStatusBar[i]);
|
||||
}
|
||||
safeStatus = singleQuote+safeStatus+singleQuote;
|
||||
boost::replace_all(strCmd, "%s", safeStatus);
|
||||
|
||||
if (fThread)
|
||||
boost::thread t(runCommand, strCmd); // thread runs free
|
||||
else
|
||||
runCommand(strCmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
|
||||
return true;
|
||||
}
|
102
src/alert.h
102
src/alert.h
|
@ -1,102 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef _BITCOINALERT_H_
|
||||
#define _BITCOINALERT_H_ 1
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
#include "uint256.h"
|
||||
#include "util.h"
|
||||
|
||||
class CNode;
|
||||
|
||||
/** Alerts are for notifying old versions if they become too obsolete and
|
||||
* need to upgrade. The message is displayed in the status bar.
|
||||
* Alert messages are broadcast as a vector of signed data. Unserializing may
|
||||
* not read the entire buffer if the alert is for a newer version, but older
|
||||
* versions can still relay the original data.
|
||||
*/
|
||||
class CUnsignedAlert
|
||||
{
|
||||
public:
|
||||
int nVersion;
|
||||
int64 nRelayUntil; // when newer nodes stop relaying to newer nodes
|
||||
int64 nExpiration;
|
||||
int nID;
|
||||
int nCancel;
|
||||
std::set<int> setCancel;
|
||||
int nMinVer; // lowest version inclusive
|
||||
int nMaxVer; // highest version inclusive
|
||||
std::set<std::string> setSubVer; // empty matches all
|
||||
int nPriority;
|
||||
|
||||
// Actions
|
||||
std::string strComment;
|
||||
std::string strStatusBar;
|
||||
std::string strReserved;
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(this->nVersion);
|
||||
nVersion = this->nVersion;
|
||||
READWRITE(nRelayUntil);
|
||||
READWRITE(nExpiration);
|
||||
READWRITE(nID);
|
||||
READWRITE(nCancel);
|
||||
READWRITE(setCancel);
|
||||
READWRITE(nMinVer);
|
||||
READWRITE(nMaxVer);
|
||||
READWRITE(setSubVer);
|
||||
READWRITE(nPriority);
|
||||
|
||||
READWRITE(strComment);
|
||||
READWRITE(strStatusBar);
|
||||
READWRITE(strReserved);
|
||||
)
|
||||
|
||||
void SetNull();
|
||||
|
||||
std::string ToString() const;
|
||||
void print() const;
|
||||
};
|
||||
|
||||
/** An alert is a combination of a serialized CUnsignedAlert and a signature. */
|
||||
class CAlert : public CUnsignedAlert
|
||||
{
|
||||
public:
|
||||
std::vector<unsigned char> vchMsg;
|
||||
std::vector<unsigned char> vchSig;
|
||||
|
||||
CAlert()
|
||||
{
|
||||
SetNull();
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(vchMsg);
|
||||
READWRITE(vchSig);
|
||||
)
|
||||
|
||||
void SetNull();
|
||||
bool IsNull() const;
|
||||
uint256 GetHash() const;
|
||||
bool IsInEffect() const;
|
||||
bool Cancels(const CAlert& alert) const;
|
||||
bool AppliesTo(int nVersion, std::string strSubVerIn) const;
|
||||
bool AppliesToMe() const;
|
||||
bool RelayTo(CNode* pnode) const;
|
||||
bool CheckSignature() const;
|
||||
bool ProcessAlert(bool fThread = true);
|
||||
|
||||
/*
|
||||
* Get copy of (active) alert object by hash. Returns a null alert if it is not found.
|
||||
*/
|
||||
static CAlert getAlertByHash(const uint256 &hash);
|
||||
};
|
||||
|
||||
#endif
|
20
src/bignum.h
20
src/bignum.h
|
@ -390,26 +390,6 @@ public:
|
|||
return ToString(16);
|
||||
}
|
||||
|
||||
unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const
|
||||
{
|
||||
return ::GetSerializeSize(getvch(), nType, nVersion);
|
||||
}
|
||||
|
||||
template<typename Stream>
|
||||
void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
|
||||
{
|
||||
::Serialize(s, getvch(), nType, nVersion);
|
||||
}
|
||||
|
||||
template<typename Stream>
|
||||
void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)
|
||||
{
|
||||
std::vector<unsigned char> vch;
|
||||
::Unserialize(s, vch, nType, nVersion);
|
||||
setvch(vch);
|
||||
}
|
||||
|
||||
|
||||
bool operator!() const
|
||||
{
|
||||
return BN_is_zero(this);
|
||||
|
|
|
@ -23,9 +23,6 @@ void BitcoinMiner(CBlockProvider *block_provider, unsigned int thread_id)
|
|||
SetThreadPriority(THREAD_PRIORITY_LOWEST);
|
||||
RenameThread("primecoin-miner");
|
||||
|
||||
// Each thread has its own kcd ey and counter
|
||||
unsigned int nExtraNonce = 0; //^
|
||||
|
||||
unsigned int nPrimorialMultiplier = nPrimorialHashFactor;
|
||||
double dTimeExpected = 0; // time expected to prime chain (micro-second)
|
||||
int64 nSieveGenTime = 0; // how many milliseconds sieve generation took
|
||||
|
@ -41,7 +38,6 @@ void BitcoinMiner(CBlockProvider *block_provider, unsigned int thread_id)
|
|||
//
|
||||
CBlockIndex* pindexPrev = pindexBest;
|
||||
|
||||
auto_ptr<CBlockTemplate> pblocktemplate;
|
||||
if ((pblock = block_provider->getBlock(thread_id, pblock == NULL ? 0 : pblock->nTime)) == NULL) { //server not reachable?
|
||||
MilliSleep(20000);
|
||||
continue;
|
||||
|
@ -59,11 +55,6 @@ void BitcoinMiner(CBlockProvider *block_provider, unsigned int thread_id)
|
|||
old_nonce = 0;
|
||||
}
|
||||
|
||||
if (fDebug && GetBoolArg("-printmining"))
|
||||
printf("Running PrimecoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
|
||||
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
|
||||
|
||||
//
|
||||
// Search
|
||||
//
|
||||
int64 nStart = GetTime();
|
||||
|
|
1381
src/bitcoinrpc.cpp
1381
src/bitcoinrpc.cpp
File diff suppressed because it is too large
Load Diff
215
src/bitcoinrpc.h
215
src/bitcoinrpc.h
|
@ -1,215 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under conditional MIT/X11 software license,
|
||||
// see the accompanying file COPYING
|
||||
|
||||
#ifndef _BITCOINRPC_H_
|
||||
#define _BITCOINRPC_H_ 1
|
||||
|
||||
#include <string>
|
||||
#include <list>
|
||||
#include <map>
|
||||
|
||||
class CBlockIndex;
|
||||
class CReserveKey;
|
||||
|
||||
#include "json/json_spirit_reader_template.h"
|
||||
#include "json/json_spirit_writer_template.h"
|
||||
#include "json/json_spirit_utils.h"
|
||||
|
||||
#include "util.h"
|
||||
|
||||
// HTTP status codes
|
||||
enum HTTPStatusCode
|
||||
{
|
||||
HTTP_OK = 200,
|
||||
HTTP_BAD_REQUEST = 400,
|
||||
HTTP_UNAUTHORIZED = 401,
|
||||
HTTP_FORBIDDEN = 403,
|
||||
HTTP_NOT_FOUND = 404,
|
||||
HTTP_INTERNAL_SERVER_ERROR = 500,
|
||||
};
|
||||
|
||||
// Bitcoin RPC error codes
|
||||
enum RPCErrorCode
|
||||
{
|
||||
// Standard JSON-RPC 2.0 errors
|
||||
RPC_INVALID_REQUEST = -32600,
|
||||
RPC_METHOD_NOT_FOUND = -32601,
|
||||
RPC_INVALID_PARAMS = -32602,
|
||||
RPC_INTERNAL_ERROR = -32603,
|
||||
RPC_PARSE_ERROR = -32700,
|
||||
|
||||
// General application defined errors
|
||||
RPC_MISC_ERROR = -1, // std::exception thrown in command handling
|
||||
RPC_FORBIDDEN_BY_SAFE_MODE = -2, // Server is in safe mode, and command is not allowed in safe mode
|
||||
RPC_TYPE_ERROR = -3, // Unexpected type was passed as parameter
|
||||
RPC_INVALID_ADDRESS_OR_KEY = -5, // Invalid address or key
|
||||
RPC_OUT_OF_MEMORY = -7, // Ran out of memory during operation
|
||||
RPC_INVALID_PARAMETER = -8, // Invalid, missing or duplicate parameter
|
||||
RPC_DATABASE_ERROR = -20, // Database error
|
||||
RPC_DESERIALIZATION_ERROR = -22, // Error parsing or validating structure in raw format
|
||||
|
||||
// P2P client errors
|
||||
RPC_CLIENT_NOT_CONNECTED = -9, // Bitcoin is not connected
|
||||
RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, // Still downloading initial blocks
|
||||
|
||||
// Wallet errors
|
||||
RPC_WALLET_ERROR = -4, // Unspecified problem with wallet (key not found etc.)
|
||||
RPC_WALLET_INSUFFICIENT_FUNDS = -6, // Not enough funds in wallet or account
|
||||
RPC_WALLET_INVALID_ACCOUNT_NAME = -11, // Invalid account name
|
||||
RPC_WALLET_KEYPOOL_RAN_OUT = -12, // Keypool ran out, call keypoolrefill first
|
||||
RPC_WALLET_UNLOCK_NEEDED = -13, // Enter the wallet passphrase with walletpassphrase first
|
||||
RPC_WALLET_PASSPHRASE_INCORRECT = -14, // The wallet passphrase entered was incorrect
|
||||
RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
|
||||
RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet
|
||||
RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked
|
||||
};
|
||||
|
||||
json_spirit::Object JSONRPCError(int code, const std::string& message);
|
||||
|
||||
void StartRPCThreads();
|
||||
void StopRPCThreads();
|
||||
int CommandLineRPC(int argc, char *argv[]);
|
||||
|
||||
/** Convert parameter values for RPC call from strings to command-specific JSON objects. */
|
||||
json_spirit::Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams);
|
||||
|
||||
/*
|
||||
Type-check arguments; throws JSONRPCError if wrong type given. Does not check that
|
||||
the right number of arguments are passed, just that any passed are the correct type.
|
||||
Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type));
|
||||
*/
|
||||
void RPCTypeCheck(const json_spirit::Array& params,
|
||||
const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false);
|
||||
/*
|
||||
Check for expected keys/value types in an Object.
|
||||
Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type));
|
||||
*/
|
||||
void RPCTypeCheck(const json_spirit::Object& o,
|
||||
const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false);
|
||||
|
||||
typedef json_spirit::Value(*rpcfn_type)(const json_spirit::Array& params, bool fHelp);
|
||||
|
||||
class CRPCCommand
|
||||
{
|
||||
public:
|
||||
std::string name;
|
||||
rpcfn_type actor;
|
||||
bool okSafeMode;
|
||||
bool threadSafe;
|
||||
};
|
||||
|
||||
/**
|
||||
* Bitcoin RPC command dispatcher.
|
||||
*/
|
||||
class CRPCTable
|
||||
{
|
||||
private:
|
||||
std::map<std::string, const CRPCCommand*> mapCommands;
|
||||
public:
|
||||
CRPCTable();
|
||||
const CRPCCommand* operator[](std::string name) const;
|
||||
std::string help(std::string name) const;
|
||||
|
||||
/**
|
||||
* Execute a method.
|
||||
* @param method Method to execute
|
||||
* @param params Array of arguments (JSON objects)
|
||||
* @returns Result of the call.
|
||||
* @throws an exception (json_spirit::Value) when an error happens.
|
||||
*/
|
||||
json_spirit::Value execute(const std::string &method, const json_spirit::Array ¶ms) const;
|
||||
};
|
||||
|
||||
extern const CRPCTable tableRPC;
|
||||
extern CReserveKey* pMiningKey;
|
||||
|
||||
extern int64 nWalletUnlockTime;
|
||||
extern int64 AmountFromValue(const json_spirit::Value& value);
|
||||
extern json_spirit::Value ValueFromAmount(int64 amount);
|
||||
extern double GetDifficulty(const CBlockIndex* blockindex = NULL);
|
||||
extern double GetHashDifficulty(unsigned int nProofOfWorkType, const CBlockIndex* blockindex);
|
||||
extern std::string HexBits(unsigned int nBits);
|
||||
extern std::string HelpRequiringPassphrase();
|
||||
extern void EnsureWalletIsUnlocked();
|
||||
|
||||
extern json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp); // in rpcnet.cpp
|
||||
extern json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value addnode(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getaddednodeinfo(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value makekeypair(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value sendalert(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp); // in checkpointsync.cpp
|
||||
extern json_spirit::Value sendcheckpoint(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value enforcecheckpoint(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp); // in rpcdump.cpp
|
||||
extern json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp);
|
||||
|
||||
extern json_spirit::Value getgenerate(const json_spirit::Array& params, bool fHelp); // in rpcmining.cpp
|
||||
extern json_spirit::Value setgenerate(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getsievepercentage(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value setsievepercentage(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getsieveextensions(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value setsieveextensions(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getprimespersec(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getchainspermin(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp);
|
||||
|
||||
extern json_spirit::Value getnewaddress(const json_spirit::Array& params, bool fHelp); // in rpcwallet.cpp
|
||||
extern json_spirit::Value getaccountaddress(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value setaccount(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getaccount(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getaddressesbyaccount(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value sendtoaddress(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value signmessage(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value verifymessage(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getreceivedbyaddress(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getreceivedbyaccount(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getbalance(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value movecmd(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value sendfrom(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value sendmany(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value addmultisigaddress(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value createmultisig(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listreceivedbyaddress(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listreceivedbyaccount(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listtransactions(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listaddressgroupings(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listaccounts(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listsinceblock(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value gettransaction(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value backupwallet(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value keypoolrefill(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value walletpassphrase(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value walletpassphrasechange(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value walletlock(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value encryptwallet(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value validateaddress(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getinfo(const json_spirit::Array& params, bool fHelp);
|
||||
|
||||
extern json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp); // in rcprawtransaction.cpp
|
||||
extern json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value lockunspent(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listlockunspent(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp);
|
||||
|
||||
extern json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp
|
||||
extern json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value gettxoutsetinfo(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value gettxout(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listprimerecords(const json_spirit::Array& params, bool fHelp);
|
||||
extern json_spirit::Value listtopprimes(const json_spirit::Array& params, bool fHelp);
|
||||
|
||||
#endif
|
160
src/bloom.cpp
160
src/bloom.cpp
|
@ -1,160 +0,0 @@
|
|||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "bloom.h"
|
||||
#include "main.h"
|
||||
#include "script.h"
|
||||
|
||||
#define LN2SQUARED 0.4804530139182014246671025263266649717305529515945455
|
||||
#define LN2 0.6931471805599453094172321214581765680755001343602552
|
||||
|
||||
using namespace std;
|
||||
|
||||
static const unsigned char bit_mask[8] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
|
||||
|
||||
CBloomFilter::CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweakIn, unsigned char nFlagsIn) :
|
||||
// The ideal size for a bloom filter with a given number of elements and false positive rate is:
|
||||
// - nElements * log(fp rate) / ln(2)^2
|
||||
// We ignore filter parameters which will create a bloom filter larger than the protocol limits
|
||||
vData(min((unsigned int)(-1 / LN2SQUARED * nElements * log(nFPRate)), MAX_BLOOM_FILTER_SIZE * 8) / 8),
|
||||
// The ideal number of hash functions is filter size * ln(2) / number of elements
|
||||
// Again, we ignore filter parameters which will create a bloom filter with more hash functions than the protocol limits
|
||||
// See http://en.wikipedia.org/wiki/Bloom_filter for an explanation of these formulas
|
||||
nHashFuncs(min((unsigned int)(vData.size() * 8 / nElements * LN2), MAX_HASH_FUNCS)),
|
||||
nTweak(nTweakIn),
|
||||
nFlags(nFlagsIn)
|
||||
{
|
||||
}
|
||||
|
||||
inline unsigned int CBloomFilter::Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const
|
||||
{
|
||||
// 0xFBA4C795 chosen as it guarantees a reasonable bit difference between nHashNum values.
|
||||
return MurmurHash3(nHashNum * 0xFBA4C795 + nTweak, vDataToHash) % (vData.size() * 8);
|
||||
}
|
||||
|
||||
void CBloomFilter::insert(const vector<unsigned char>& vKey)
|
||||
{
|
||||
if (vData.size() == 1 && vData[0] == 0xff)
|
||||
return;
|
||||
for (unsigned int i = 0; i < nHashFuncs; i++)
|
||||
{
|
||||
unsigned int nIndex = Hash(i, vKey);
|
||||
// Sets bit nIndex of vData
|
||||
vData[nIndex >> 3] |= bit_mask[7 & nIndex];
|
||||
}
|
||||
}
|
||||
|
||||
void CBloomFilter::insert(const COutPoint& outpoint)
|
||||
{
|
||||
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
|
||||
stream << outpoint;
|
||||
vector<unsigned char> data(stream.begin(), stream.end());
|
||||
insert(data);
|
||||
}
|
||||
|
||||
void CBloomFilter::insert(const uint256& hash)
|
||||
{
|
||||
vector<unsigned char> data(hash.begin(), hash.end());
|
||||
insert(data);
|
||||
}
|
||||
|
||||
bool CBloomFilter::contains(const vector<unsigned char>& vKey) const
|
||||
{
|
||||
if (vData.size() == 1 && vData[0] == 0xff)
|
||||
return true;
|
||||
for (unsigned int i = 0; i < nHashFuncs; i++)
|
||||
{
|
||||
unsigned int nIndex = Hash(i, vKey);
|
||||
// Checks bit nIndex of vData
|
||||
if (!(vData[nIndex >> 3] & bit_mask[7 & nIndex]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBloomFilter::contains(const COutPoint& outpoint) const
|
||||
{
|
||||
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
|
||||
stream << outpoint;
|
||||
vector<unsigned char> data(stream.begin(), stream.end());
|
||||
return contains(data);
|
||||
}
|
||||
|
||||
bool CBloomFilter::contains(const uint256& hash) const
|
||||
{
|
||||
vector<unsigned char> data(hash.begin(), hash.end());
|
||||
return contains(data);
|
||||
}
|
||||
|
||||
bool CBloomFilter::IsWithinSizeConstraints() const
|
||||
{
|
||||
return vData.size() <= MAX_BLOOM_FILTER_SIZE && nHashFuncs <= MAX_HASH_FUNCS;
|
||||
}
|
||||
|
||||
bool CBloomFilter::IsRelevantAndUpdate(const CTransaction& tx, const uint256& hash)
|
||||
{
|
||||
bool fFound = false;
|
||||
// Match if the filter contains the hash of tx
|
||||
// for finding tx when they appear in a block
|
||||
if (contains(hash))
|
||||
fFound = true;
|
||||
|
||||
for (unsigned int i = 0; i < tx.vout.size(); i++)
|
||||
{
|
||||
const CTxOut& txout = tx.vout[i];
|
||||
// Match if the filter contains any arbitrary script data element in any scriptPubKey in tx
|
||||
// If this matches, also add the specific output that was matched.
|
||||
// This means clients don't have to update the filter themselves when a new relevant tx
|
||||
// is discovered in order to find spending transactions, which avoids round-tripping and race conditions.
|
||||
CScript::const_iterator pc = txout.scriptPubKey.begin();
|
||||
vector<unsigned char> data;
|
||||
while (pc < txout.scriptPubKey.end())
|
||||
{
|
||||
opcodetype opcode;
|
||||
if (!txout.scriptPubKey.GetOp(pc, opcode, data))
|
||||
break;
|
||||
if (data.size() != 0 && contains(data))
|
||||
{
|
||||
fFound = true;
|
||||
if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_ALL)
|
||||
insert(COutPoint(hash, i));
|
||||
else if ((nFlags & BLOOM_UPDATE_MASK) == BLOOM_UPDATE_P2PUBKEY_ONLY)
|
||||
{
|
||||
txnouttype type;
|
||||
vector<vector<unsigned char> > vSolutions;
|
||||
if (Solver(txout.scriptPubKey, type, vSolutions) &&
|
||||
(type == TX_PUBKEY || type == TX_MULTISIG))
|
||||
insert(COutPoint(hash, i));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fFound)
|
||||
return true;
|
||||
|
||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||
{
|
||||
// Match if the filter contains an outpoint tx spends
|
||||
if (contains(txin.prevout))
|
||||
return true;
|
||||
|
||||
// Match if the filter contains any arbitrary script data element in any scriptSig in tx
|
||||
CScript::const_iterator pc = txin.scriptSig.begin();
|
||||
vector<unsigned char> data;
|
||||
while (pc < txin.scriptSig.end())
|
||||
{
|
||||
opcodetype opcode;
|
||||
if (!txin.scriptSig.GetOp(pc, opcode, data))
|
||||
break;
|
||||
if (data.size() != 0 && contains(data))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
88
src/bloom.h
88
src/bloom.h
|
@ -1,88 +0,0 @@
|
|||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_BLOOM_H
|
||||
#define BITCOIN_BLOOM_H
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "uint256.h"
|
||||
#include "serialize.h"
|
||||
|
||||
class COutPoint;
|
||||
class CTransaction;
|
||||
|
||||
// 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001%
|
||||
static const unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes
|
||||
static const unsigned int MAX_HASH_FUNCS = 50;
|
||||
|
||||
// First two bits of nFlags control how much IsRelevantAndUpdate actually updates
|
||||
// The remaining bits are reserved
|
||||
enum bloomflags
|
||||
{
|
||||
BLOOM_UPDATE_NONE = 0,
|
||||
BLOOM_UPDATE_ALL = 1,
|
||||
// Only adds outpoints to the filter if the output is a pay-to-pubkey/pay-to-multisig script
|
||||
BLOOM_UPDATE_P2PUBKEY_ONLY = 2,
|
||||
BLOOM_UPDATE_MASK = 3,
|
||||
};
|
||||
|
||||
/**
|
||||
* BloomFilter is a probabilistic filter which SPV clients provide
|
||||
* so that we can filter the transactions we sends them.
|
||||
*
|
||||
* This allows for significantly more efficient transaction and block downloads.
|
||||
*
|
||||
* Because bloom filters are probabilistic, an SPV node can increase the false-
|
||||
* positive rate, making us send them transactions which aren't actually theirs,
|
||||
* allowing clients to trade more bandwidth for more privacy by obfuscating which
|
||||
* keys are owned by them.
|
||||
*/
|
||||
class CBloomFilter
|
||||
{
|
||||
private:
|
||||
std::vector<unsigned char> vData;
|
||||
unsigned int nHashFuncs;
|
||||
unsigned int nTweak;
|
||||
unsigned char nFlags;
|
||||
|
||||
unsigned int Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const;
|
||||
|
||||
public:
|
||||
// Creates a new bloom filter which will provide the given fp rate when filled with the given number of elements
|
||||
// Note that if the given parameters will result in a filter outside the bounds of the protocol limits,
|
||||
// the filter created will be as close to the given parameters as possible within the protocol limits.
|
||||
// This will apply if nFPRate is very low or nElements is unreasonably high.
|
||||
// nTweak is a constant which is added to the seed value passed to the hash function
|
||||
// It should generally always be a random value (and is largely only exposed for unit testing)
|
||||
// nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK)
|
||||
CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweak, unsigned char nFlagsIn);
|
||||
// Using a filter initialized with this results in undefined behavior
|
||||
// Should only be used for deserialization
|
||||
CBloomFilter() {}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(vData);
|
||||
READWRITE(nHashFuncs);
|
||||
READWRITE(nTweak);
|
||||
READWRITE(nFlags);
|
||||
)
|
||||
|
||||
void insert(const std::vector<unsigned char>& vKey);
|
||||
void insert(const COutPoint& outpoint);
|
||||
void insert(const uint256& hash);
|
||||
|
||||
bool contains(const std::vector<unsigned char>& vKey) const;
|
||||
bool contains(const COutPoint& outpoint) const;
|
||||
bool contains(const uint256& hash) const;
|
||||
|
||||
// True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS
|
||||
// (catch a filter which was just deserialized which was too big)
|
||||
bool IsWithinSizeConstraints() const;
|
||||
|
||||
// Also adds any outputs which match the filter to the filter (to match their spending txes)
|
||||
bool IsRelevantAndUpdate(const CTransaction& tx, const uint256& hash);
|
||||
};
|
||||
|
||||
#endif /* BITCOIN_BLOOM_H */
|
|
@ -1,145 +0,0 @@
|
|||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under conditional MIT/X11 software license,
|
||||
// see the accompanying file COPYING
|
||||
|
||||
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
|
||||
#include <boost/foreach.hpp>
|
||||
|
||||
#include "checkpoints.h"
|
||||
|
||||
#include "main.h"
|
||||
#include "uint256.h"
|
||||
|
||||
namespace Checkpoints
|
||||
{
|
||||
typedef std::map<int, uint256> MapCheckpoints;
|
||||
|
||||
// How many times we expect transactions after the last checkpoint to
|
||||
// be slower. This number is a compromise, as it can't be accurate for
|
||||
// every system. When reindexing from a fast disk with a slow CPU, it
|
||||
// can be up to 20, while when downloading from a slow network with a
|
||||
// fast multicore CPU, it won't be much higher than 1.
|
||||
static const double fSigcheckVerificationFactor = 5.0;
|
||||
|
||||
struct CCheckpointData {
|
||||
const MapCheckpoints *mapCheckpoints;
|
||||
int64 nTimeLastCheckpoint;
|
||||
int64 nTransactionsLastCheckpoint;
|
||||
double fTransactionsPerDay;
|
||||
};
|
||||
|
||||
// What makes a good checkpoint block?
|
||||
// + Is surrounded by blocks with reasonable timestamps
|
||||
// (no blocks before with a timestamp after, none after with
|
||||
// timestamp before)
|
||||
// + Contains no strange transactions
|
||||
static MapCheckpoints mapCheckpoints =
|
||||
boost::assign::map_list_of
|
||||
( 0, hashGenesisBlockOfficial )
|
||||
( 74722, uint256("0x74778cd8a5f2fbacca95dc4de02771e24e365c3f28412189f349355096826afe"))
|
||||
( 84106, uint256("0xbb081d595e948203a67a7501c30d6a8c413db97deb1234185c4929f66be945ef"))
|
||||
( 85429, uint256("0xa2bd26fbebcfa02f4e291806f0214e17c2dfb250c3443bbb1778c0cd532776f4"))
|
||||
;
|
||||
static const CCheckpointData data = {
|
||||
&mapCheckpoints,
|
||||
1374921070, // * UNIX timestamp of last checkpoint block
|
||||
14264869, // * total number of transactions between genesis and last checkpoint
|
||||
// (the tx=... number in the SetBestChain debug.log lines)
|
||||
60000.0 // * estimated number of transactions per day after checkpoint
|
||||
};
|
||||
|
||||
static MapCheckpoints mapCheckpointsTestnet =
|
||||
boost::assign::map_list_of
|
||||
( 0, hashGenesisBlockTestNet )
|
||||
;
|
||||
static const CCheckpointData dataTestnet = {
|
||||
&mapCheckpointsTestnet,
|
||||
1338180505,
|
||||
16341,
|
||||
300
|
||||
};
|
||||
|
||||
const CCheckpointData &Checkpoints() {
|
||||
if (fTestNet)
|
||||
return dataTestnet;
|
||||
else
|
||||
return data;
|
||||
}
|
||||
|
||||
bool CheckBlock(int nHeight, const uint256& hash)
|
||||
{
|
||||
if (!GetBoolArg("-checkpoints", true))
|
||||
return true;
|
||||
|
||||
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
|
||||
|
||||
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
|
||||
if (i == checkpoints.end()) return true;
|
||||
return hash == i->second;
|
||||
}
|
||||
|
||||
// Guess how far we are in the verification process at the given block index
|
||||
double GuessVerificationProgress(CBlockIndex *pindex) {
|
||||
if (pindex==NULL)
|
||||
return 0.0;
|
||||
|
||||
int64 nNow = time(NULL);
|
||||
|
||||
double fWorkBefore = 0.0; // Amount of work done before pindex
|
||||
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
|
||||
// Work is defined as: 1.0 per transaction before the last checkoint, and
|
||||
// fSigcheckVerificationFactor per transaction after.
|
||||
|
||||
const CCheckpointData &data = Checkpoints();
|
||||
|
||||
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
|
||||
double nCheapBefore = pindex->nChainTx;
|
||||
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
|
||||
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
|
||||
fWorkBefore = nCheapBefore;
|
||||
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
|
||||
} else {
|
||||
double nCheapBefore = data.nTransactionsLastCheckpoint;
|
||||
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
|
||||
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
|
||||
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
|
||||
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
|
||||
}
|
||||
|
||||
return fWorkBefore / (fWorkBefore + fWorkAfter);
|
||||
}
|
||||
|
||||
int GetTotalBlocksEstimate()
|
||||
{
|
||||
if (!GetBoolArg("-checkpoints", true))
|
||||
return 0;
|
||||
|
||||
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
|
||||
|
||||
return checkpoints.rbegin()->first;
|
||||
}
|
||||
|
||||
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
|
||||
{
|
||||
if (!GetBoolArg("-checkpoints", true))
|
||||
return NULL;
|
||||
|
||||
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
|
||||
|
||||
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
|
||||
{
|
||||
const uint256& hash = i.second;
|
||||
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
|
||||
if (t != mapBlockIndex.end())
|
||||
return t->second;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
uint256 GetLatestHardenedCheckpoint()
|
||||
{
|
||||
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
|
||||
return (checkpoints.rbegin()->second);
|
||||
}
|
||||
}
|
|
@ -1,32 +0,0 @@
|
|||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_CHECKPOINT_H
|
||||
#define BITCOIN_CHECKPOINT_H
|
||||
|
||||
#include <map>
|
||||
|
||||
class uint256;
|
||||
class CBlockIndex;
|
||||
|
||||
/** Block-chain checkpoints are compiled-in sanity checks.
|
||||
* They are updated every release or three.
|
||||
*/
|
||||
namespace Checkpoints
|
||||
{
|
||||
// Returns true if block passes checkpoint checks
|
||||
bool CheckBlock(int nHeight, const uint256& hash);
|
||||
|
||||
// Return conservative estimate of total number of blocks, 0 if unknown
|
||||
int GetTotalBlocksEstimate();
|
||||
|
||||
// Returns last CBlockIndex* in mapBlockIndex that is a checkpoint
|
||||
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex);
|
||||
|
||||
// Returns the block hash of latest hardened checkpoint
|
||||
uint256 GetLatestHardenedCheckpoint();
|
||||
|
||||
double GuessVerificationProgress(CBlockIndex *pindex);
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,538 +0,0 @@
|
|||
// Copyright (c) 2012-2013 PPCoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under conditional MIT/X11 software license,
|
||||
// see the accompanying file COPYING
|
||||
//
|
||||
// The synchronized checkpoint system is first developed by Sunny King for
|
||||
// ppcoin network in 2012, giving cryptocurrency developers a tool to gain
|
||||
// additional network protection against 51% attack.
|
||||
//
|
||||
// Primecoin also adopts this security mechanism, and the enforcement of
|
||||
// checkpoints is explicitly granted by user, thus granting only temporary
|
||||
// consensual central control to developer at the threats of 51% attack.
|
||||
//
|
||||
// Concepts
|
||||
//
|
||||
// In the network there can be a privileged node known as 'checkpoint master'.
|
||||
// This node can send out checkpoint messages signed by the checkpoint master
|
||||
// key. Each checkpoint is a block hash, representing a block on the blockchain
|
||||
// that the network should reach consensus on.
|
||||
//
|
||||
// Besides verifying signatures of checkpoint messages, each node also verifies
|
||||
// the consistency of the checkpoints. If a conflicting checkpoint is received,
|
||||
// it means either the checkpoint master key is compromised, or there is an
|
||||
// operator mistake. In this situation the node would discard the conflicting
|
||||
// checkpoint message and display a warning message. This precaution controls
|
||||
// the damage to network caused by operator mistake or compromised key.
|
||||
//
|
||||
// Operations
|
||||
//
|
||||
// Checkpoint master key can be established by using the 'makekeypair' command
|
||||
// The public key in source code should then be updated and private key kept
|
||||
// in a safe place.
|
||||
//
|
||||
// Any node can be turned into checkpoint master by setting the 'checkpointkey'
|
||||
// configuration parameter with the private key of the checkpoint master key.
|
||||
// Operator should exercise caution such that at any moment there is at most
|
||||
// one node operating as checkpoint master. When switching master node, the
|
||||
// recommended procedure is to shutdown the master node and restart as
|
||||
// regular node, note down the current checkpoint by 'getcheckpoint', then
|
||||
// compare to the checkpoint at the new node to be upgraded to master node.
|
||||
// When the checkpoint on both nodes match then it is safe to switch the new
|
||||
// node to checkpoint master.
|
||||
//
|
||||
// The configuration parameter 'checkpointdepth' specifies how many blocks
|
||||
// should the checkpoints lag behind the latest block in auto checkpoint mode.
|
||||
// A depth of 0 is the strongest auto checkpoint policy and offers the greatest
|
||||
// protection against 51% attack. A negative depth means that the checkpoints
|
||||
// should not be automatically generated by the checkpoint master, but instead
|
||||
// be manually entered by operator via the 'sendcheckpoint' command. The manual
|
||||
// mode is also the default mode (default value -1 for checkpointdepth).
|
||||
//
|
||||
// Command 'enforcecheckpoint' and configuration parameter 'checkpointenforce'
|
||||
// are for the users to explicitly consent to enforce the checkpoints issued
|
||||
// from checkpoint master. To enforce checkpoint, user needs to either issue
|
||||
// command 'enforcecheckpoint true', or set configuration parameter
|
||||
// checkpointenforce=1. The current enforcement setting can be queried via
|
||||
// command 'getcheckpoint', where 'subscribemode' displays either 'enforce'
|
||||
// or 'advisory'. The 'enforce' mode of subscribemode means checkpoints are
|
||||
// enforced. The 'advisory' mode of subscribemode means checkpoints are not
|
||||
// enforced but a warning message would be displayed if the node is on a
|
||||
// different blockchain fork from the checkpoint, and this is the default mode.
|
||||
//
|
||||
|
||||
#include <boost/foreach.hpp>
|
||||
|
||||
#include "checkpoints.h"
|
||||
#include "checkpointsync.h"
|
||||
|
||||
#include "base58.h"
|
||||
#include "bitcoinrpc.h"
|
||||
#include "main.h"
|
||||
#include "txdb.h"
|
||||
#include "uint256.h"
|
||||
|
||||
using namespace json_spirit;
|
||||
using namespace std;
|
||||
|
||||
|
||||
// ppcoin: sync-checkpoint master key
|
||||
const std::string CSyncCheckpoint::strMainPubKey = "04c0c44f7e3bc58c734e65bb0e97860b2f5e53d12a5e1ea30ec6d73df821349f83ff0a061221dfcab3f1235d5b2fff85587a72f8f74f4c56d9e17087a1e8c28b04";
|
||||
const std::string CSyncCheckpoint::strTestPubKey = "0400c9611d333d6ddfc5dbfcb6ab3a7c00d56959cfda1ff2d94a8dc4c88050be18d0aa4b6c547ff4db33d708866c85616926278b05bcb80b66974280774720303b";
|
||||
std::string CSyncCheckpoint::strMasterPrivKey = "";
|
||||
|
||||
|
||||
// ppcoin: synchronized checkpoint (centrally broadcasted)
|
||||
uint256 hashSyncCheckpoint = 0;
|
||||
uint256 hashPendingCheckpoint = 0;
|
||||
CSyncCheckpoint checkpointMessage;
|
||||
CSyncCheckpoint checkpointMessagePending;
|
||||
uint256 hashInvalidCheckpoint = 0;
|
||||
CCriticalSection cs_hashSyncCheckpoint;
|
||||
std::string strCheckpointWarning;
|
||||
|
||||
// ppcoin: get last synchronized checkpoint
|
||||
CBlockIndex* GetLastSyncCheckpoint()
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
if (!mapBlockIndex.count(hashSyncCheckpoint))
|
||||
error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
|
||||
else
|
||||
return mapBlockIndex[hashSyncCheckpoint];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// ppcoin: only descendant of current sync-checkpoint is allowed
|
||||
bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
|
||||
{
|
||||
if (!mapBlockIndex.count(hashSyncCheckpoint))
|
||||
return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
|
||||
if (!mapBlockIndex.count(hashCheckpoint))
|
||||
return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
|
||||
|
||||
CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
|
||||
CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
|
||||
|
||||
if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
|
||||
{
|
||||
// Received an older checkpoint, trace back from current checkpoint
|
||||
// to the same height of the received checkpoint to verify
|
||||
// that current checkpoint should be a descendant block
|
||||
CBlockIndex* pindex = pindexSyncCheckpoint;
|
||||
while (pindex->nHeight > pindexCheckpointRecv->nHeight)
|
||||
if (!(pindex = pindex->pprev))
|
||||
return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
|
||||
if (pindex->GetBlockHash() != hashCheckpoint)
|
||||
{
|
||||
hashInvalidCheckpoint = hashCheckpoint;
|
||||
return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
|
||||
}
|
||||
return false; // ignore older checkpoint
|
||||
}
|
||||
|
||||
// Received checkpoint should be a descendant block of the current
|
||||
// checkpoint. Trace back to the same height of current checkpoint
|
||||
// to verify.
|
||||
CBlockIndex* pindex = pindexCheckpointRecv;
|
||||
while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
|
||||
if (!(pindex = pindex->pprev))
|
||||
return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
|
||||
if (pindex->GetBlockHash() != hashSyncCheckpoint)
|
||||
{
|
||||
hashInvalidCheckpoint = hashCheckpoint;
|
||||
return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
|
||||
{
|
||||
if (!pblocktree->WriteSyncCheckpoint(hashCheckpoint))
|
||||
{
|
||||
return error("WriteSyncCheckpoint(): failed to write to txdb sync checkpoint %s", hashCheckpoint.ToString().c_str());
|
||||
}
|
||||
if (!pblocktree->Sync())
|
||||
return error("WriteSyncCheckpoint(): failed to commit to txdb sync checkpoint %s", hashCheckpoint.ToString().c_str());
|
||||
|
||||
hashSyncCheckpoint = hashCheckpoint;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IsSyncCheckpointEnforced()
|
||||
{
|
||||
return (GetBoolArg("-checkpointenforce", false) || mapArgs.count("-checkpointkey")); // checkpoint master node is always enforced
|
||||
}
|
||||
|
||||
bool AcceptPendingSyncCheckpoint()
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
|
||||
{
|
||||
if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
|
||||
{
|
||||
hashPendingCheckpoint = 0;
|
||||
checkpointMessagePending.SetNull();
|
||||
return false;
|
||||
}
|
||||
|
||||
CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
|
||||
if (IsSyncCheckpointEnforced() && !pindexCheckpoint->IsInMainChain())
|
||||
{
|
||||
CValidationState state;
|
||||
if (!SetBestChain(state, pindexCheckpoint))
|
||||
{
|
||||
hashInvalidCheckpoint = hashPendingCheckpoint;
|
||||
return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (!WriteSyncCheckpoint(hashPendingCheckpoint))
|
||||
return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
|
||||
hashPendingCheckpoint = 0;
|
||||
checkpointMessage = checkpointMessagePending;
|
||||
checkpointMessagePending.SetNull();
|
||||
printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
|
||||
// relay the checkpoint
|
||||
if (!checkpointMessage.IsNull())
|
||||
{
|
||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||
checkpointMessage.RelayTo(pnode);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Automatically select a suitable sync-checkpoint
|
||||
uint256 AutoSelectSyncCheckpoint()
|
||||
{
|
||||
// Search backward for a block with specified depth policy
|
||||
const CBlockIndex *pindex = pindexBest;
|
||||
while (pindex->pprev && pindex->nHeight + (int)GetArg("-checkpointdepth", -1) > pindexBest->nHeight)
|
||||
pindex = pindex->pprev;
|
||||
return pindex->GetBlockHash();
|
||||
}
|
||||
|
||||
// Check against synchronized checkpoint
|
||||
bool CheckSyncCheckpoint(const uint256& hashBlock, const CBlockIndex* pindexPrev)
|
||||
{
|
||||
int nHeight = pindexPrev->nHeight + 1;
|
||||
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
// sync-checkpoint should always be accepted block
|
||||
assert(mapBlockIndex.count(hashSyncCheckpoint));
|
||||
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
|
||||
|
||||
if (nHeight > pindexSync->nHeight)
|
||||
{
|
||||
// trace back to same height as sync-checkpoint
|
||||
const CBlockIndex* pindex = pindexPrev;
|
||||
while (pindex->nHeight > pindexSync->nHeight)
|
||||
if (!(pindex = pindex->pprev))
|
||||
return error("CheckSyncCheckpoint: pprev null - block index structure failure");
|
||||
if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
|
||||
return false; // only descendant of sync-checkpoint can pass check
|
||||
}
|
||||
if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
|
||||
return false; // same height with sync-checkpoint
|
||||
if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
|
||||
return false; // lower height than sync-checkpoint
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
if (hashPendingCheckpoint == 0)
|
||||
return false;
|
||||
if (hashBlock == hashPendingCheckpoint)
|
||||
return true;
|
||||
if (mapOrphanBlocks.count(hashPendingCheckpoint)
|
||||
&& hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// ppcoin: reset synchronized checkpoint to last hardened checkpoint
|
||||
bool ResetSyncCheckpoint()
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
const uint256& hash = Checkpoints::GetLatestHardenedCheckpoint();
|
||||
if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
|
||||
{
|
||||
// checkpoint block accepted but not yet in main chain
|
||||
printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
|
||||
CValidationState state;
|
||||
if (!SetBestChain(state, mapBlockIndex[hash]))
|
||||
{
|
||||
return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
|
||||
}
|
||||
}
|
||||
else if(!mapBlockIndex.count(hash))
|
||||
{
|
||||
// checkpoint block not yet accepted
|
||||
hashPendingCheckpoint = hash;
|
||||
checkpointMessagePending.SetNull();
|
||||
printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
|
||||
}
|
||||
|
||||
if (!WriteSyncCheckpoint((mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())? hash : hashGenesisBlock))
|
||||
return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
|
||||
printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
void AskForPendingSyncCheckpoint(CNode* pfrom)
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
|
||||
pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
|
||||
}
|
||||
|
||||
// Verify sync checkpoint master pubkey and reset sync checkpoint if changed
|
||||
bool CheckCheckpointPubKey()
|
||||
{
|
||||
std::string strPubKey = "";
|
||||
std::string strMasterPubKey = fTestNet? CSyncCheckpoint::strTestPubKey : CSyncCheckpoint::strMainPubKey;
|
||||
if (!pblocktree->ReadCheckpointPubKey(strPubKey) || strPubKey != strMasterPubKey)
|
||||
{
|
||||
// write checkpoint master key to db
|
||||
if (!pblocktree->WriteCheckpointPubKey(strMasterPubKey))
|
||||
return error("CheckCheckpointPubKey() : failed to write new checkpoint master key to db");
|
||||
if (!pblocktree->Sync())
|
||||
return error("CheckCheckpointPubKey() : failed to commit new checkpoint master key to db");
|
||||
if (!ResetSyncCheckpoint())
|
||||
return error("CheckCheckpointPubKey() : failed to reset sync-checkpoint");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SetCheckpointPrivKey(std::string strPrivKey)
|
||||
{
|
||||
// Test signing a sync-checkpoint with genesis block
|
||||
CSyncCheckpoint checkpoint;
|
||||
checkpoint.hashCheckpoint = hashGenesisBlock;
|
||||
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
|
||||
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
|
||||
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
|
||||
|
||||
CBitcoinSecret vchSecret;
|
||||
if (!vchSecret.SetString(strPrivKey))
|
||||
return error("SendSyncCheckpoint: Checkpoint master key invalid");
|
||||
CKey key;
|
||||
bool fCompressed;
|
||||
CSecret secret = vchSecret.GetSecret(fCompressed);
|
||||
key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash
|
||||
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
|
||||
return false;
|
||||
|
||||
// Test signing successful, proceed
|
||||
CSyncCheckpoint::strMasterPrivKey = strPrivKey;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SendSyncCheckpoint(uint256 hashCheckpoint)
|
||||
{
|
||||
CSyncCheckpoint checkpoint;
|
||||
checkpoint.hashCheckpoint = hashCheckpoint;
|
||||
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
|
||||
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
|
||||
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
|
||||
|
||||
if (CSyncCheckpoint::strMasterPrivKey.empty())
|
||||
return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
|
||||
CBitcoinSecret vchSecret;
|
||||
if (!vchSecret.SetString(CSyncCheckpoint::strMasterPrivKey))
|
||||
return error("SendSyncCheckpoint: Checkpoint master key invalid");
|
||||
CKey key;
|
||||
bool fCompressed;
|
||||
CSecret secret = vchSecret.GetSecret(fCompressed);
|
||||
key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash
|
||||
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
|
||||
return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
|
||||
|
||||
if(!checkpoint.ProcessSyncCheckpoint(NULL))
|
||||
{
|
||||
printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Relay checkpoint
|
||||
{
|
||||
LOCK(cs_vNodes);
|
||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||
checkpoint.RelayTo(pnode);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Is the sync-checkpoint outside maturity window?
|
||||
bool IsMatureSyncCheckpoint()
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
// sync-checkpoint should always be accepted block
|
||||
assert(mapBlockIndex.count(hashSyncCheckpoint));
|
||||
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
|
||||
return (nBestHeight >= pindexSync->nHeight + COINBASE_MATURITY);
|
||||
}
|
||||
|
||||
// Is the sync-checkpoint too old?
|
||||
bool IsSyncCheckpointTooOld(unsigned int nSeconds)
|
||||
{
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
// sync-checkpoint should always be accepted block
|
||||
assert(mapBlockIndex.count(hashSyncCheckpoint));
|
||||
const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
|
||||
return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
|
||||
}
|
||||
|
||||
// ppcoin: find block wanted by given orphan block
|
||||
uint256 WantedByOrphan(const CBlock* pblockOrphan)
|
||||
{
|
||||
// Work back to the first block in the orphan chain
|
||||
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
|
||||
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
|
||||
return pblockOrphan->hashPrevBlock;
|
||||
}
|
||||
|
||||
// ppcoin: verify signature of sync-checkpoint message
|
||||
bool CSyncCheckpoint::CheckSignature()
|
||||
{
|
||||
CKey key;
|
||||
std::string strMasterPubKey = fTestNet? CSyncCheckpoint::strTestPubKey : CSyncCheckpoint::strMainPubKey;
|
||||
if (!key.SetPubKey(ParseHex(strMasterPubKey)))
|
||||
return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
|
||||
if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
|
||||
return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
|
||||
|
||||
// Now unserialize the data
|
||||
CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
|
||||
sMsg >> *(CUnsignedSyncCheckpoint*)this;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ppcoin: process synchronized checkpoint
|
||||
bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
|
||||
{
|
||||
if (!CheckSignature())
|
||||
return false;
|
||||
|
||||
LOCK(cs_hashSyncCheckpoint);
|
||||
if (!mapBlockIndex.count(hashCheckpoint))
|
||||
{
|
||||
// We haven't received the checkpoint chain, keep the checkpoint as pending
|
||||
hashPendingCheckpoint = hashCheckpoint;
|
||||
checkpointMessagePending = *this;
|
||||
printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
|
||||
// Ask this guy to fill in what we're missing
|
||||
if (pfrom)
|
||||
{
|
||||
pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
|
||||
// ask directly as well in case rejected earlier by duplicate
|
||||
// proof-of-stake because getblocks may not get it this time
|
||||
pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!ValidateSyncCheckpoint(hashCheckpoint))
|
||||
return false;
|
||||
|
||||
CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
|
||||
if (IsSyncCheckpointEnforced() && !pindexCheckpoint->IsInMainChain())
|
||||
{
|
||||
// checkpoint chain received but not yet main chain
|
||||
CValidationState state;
|
||||
if (!SetBestChain(state, pindexCheckpoint))
|
||||
{
|
||||
hashInvalidCheckpoint = hashCheckpoint;
|
||||
return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (!WriteSyncCheckpoint(hashCheckpoint))
|
||||
return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
|
||||
checkpointMessage = *this;
|
||||
hashPendingCheckpoint = 0;
|
||||
checkpointMessagePending.SetNull();
|
||||
printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
// RPC commands related to sync checkpoints
|
||||
// get information of sync-checkpoint (first introduced in ppcoin)
|
||||
Value getcheckpoint(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getcheckpoint\n"
|
||||
"Show info of synchronized checkpoint.\n");
|
||||
|
||||
Object result;
|
||||
CBlockIndex* pindexCheckpoint;
|
||||
|
||||
result.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str()));
|
||||
if (mapBlockIndex.count(hashSyncCheckpoint))
|
||||
{
|
||||
pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint];
|
||||
result.push_back(Pair("height", pindexCheckpoint->nHeight));
|
||||
result.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime()));
|
||||
}
|
||||
result.push_back(Pair("subscribemode", IsSyncCheckpointEnforced()? "enforce" : "advisory"));
|
||||
if (mapArgs.count("-checkpointkey"))
|
||||
result.push_back(Pair("checkpointmaster", true));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Value sendcheckpoint(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"sendcheckpoint <blockhash>\n"
|
||||
"Send a synchronized checkpoint.\n");
|
||||
|
||||
if (!mapArgs.count("-checkpointkey") || CSyncCheckpoint::strMasterPrivKey.empty())
|
||||
throw runtime_error("Not a checkpointmaster node, first set checkpointkey in configuration and restart client. ");
|
||||
|
||||
std::string strHash = params[0].get_str();
|
||||
uint256 hash(strHash);
|
||||
|
||||
if (!SendSyncCheckpoint(hash))
|
||||
throw runtime_error("Failed to send checkpoint, check log. ");
|
||||
|
||||
Object result;
|
||||
CBlockIndex* pindexCheckpoint;
|
||||
|
||||
result.push_back(Pair("synccheckpoint", hashSyncCheckpoint.ToString().c_str()));
|
||||
if (mapBlockIndex.count(hashSyncCheckpoint))
|
||||
{
|
||||
pindexCheckpoint = mapBlockIndex[hashSyncCheckpoint];
|
||||
result.push_back(Pair("height", pindexCheckpoint->nHeight));
|
||||
result.push_back(Pair("timestamp", (boost::int64_t) pindexCheckpoint->GetBlockTime()));
|
||||
}
|
||||
result.push_back(Pair("subscribemode", IsSyncCheckpointEnforced()? "enforce" : "advisory"));
|
||||
if (mapArgs.count("-checkpointkey"))
|
||||
result.push_back(Pair("checkpointmaster", true));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Value enforcecheckpoint(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"enforcecheckpoint <enforce>\n"
|
||||
"<enforce> is true or false to enable or disable enforcement of broadcasted checkpoints by developer.");
|
||||
|
||||
bool fEnforceCheckpoint = params[0].get_bool();
|
||||
if (mapArgs.count("-checkpointkey") && !fEnforceCheckpoint)
|
||||
throw runtime_error(
|
||||
"checkpoint master node must enforce synchronized checkpoints.");
|
||||
if (fEnforceCheckpoint)
|
||||
strCheckpointWarning = "";
|
||||
mapArgs["-checkpointenforce"] = (fEnforceCheckpoint ? "1" : "0");
|
||||
return Value::null;
|
||||
}
|
||||
|
|
@ -1,131 +0,0 @@
|
|||
// Copyright (c) 2011-2013 PPCoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under conditional MIT/X11 open source software license
|
||||
// see the accompanying file COPYING
|
||||
#ifndef PRIMECOIN_CHECKPOINTSYNC_H
|
||||
#define PRIMECOIN_CHECKPOINTSYNC_H
|
||||
|
||||
#include "net.h"
|
||||
#include "util.h"
|
||||
|
||||
#define CHECKPOINT_MAX_SPAN (60 * 60 * 4) // max 4 hours before latest block
|
||||
|
||||
class uint256;
|
||||
class CBlock;
|
||||
class CBlockIndex;
|
||||
class CSyncCheckpoint;
|
||||
|
||||
extern uint256 hashSyncCheckpoint;
|
||||
extern CSyncCheckpoint checkpointMessage;
|
||||
extern uint256 hashInvalidCheckpoint;
|
||||
extern CCriticalSection cs_hashSyncCheckpoint;
|
||||
extern std::string strCheckpointWarning;
|
||||
|
||||
CBlockIndex* GetLastSyncCheckpoint();
|
||||
bool WriteSyncCheckpoint(const uint256& hashCheckpoint);
|
||||
bool IsSyncCheckpointEnforced();
|
||||
bool AcceptPendingSyncCheckpoint();
|
||||
uint256 AutoSelectSyncCheckpoint();
|
||||
bool CheckSyncCheckpoint(const uint256& hashBlock, const CBlockIndex* pindexPrev);
|
||||
bool WantedByPendingSyncCheckpoint(uint256 hashBlock);
|
||||
bool ResetSyncCheckpoint();
|
||||
void AskForPendingSyncCheckpoint(CNode* pfrom);
|
||||
bool CheckCheckpointPubKey();
|
||||
bool SetCheckpointPrivKey(std::string strPrivKey);
|
||||
bool SendSyncCheckpoint(uint256 hashCheckpoint);
|
||||
bool IsMatureSyncCheckpoint();
|
||||
bool IsSyncCheckpointTooOld(unsigned int nSeconds);
|
||||
uint256 WantedByOrphan(const CBlock* pblockOrphan);
|
||||
|
||||
// Synchronized checkpoint (introduced first in ppcoin)
|
||||
class CUnsignedSyncCheckpoint
|
||||
{
|
||||
public:
|
||||
int nVersion;
|
||||
uint256 hashCheckpoint; // checkpoint block
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(this->nVersion);
|
||||
nVersion = this->nVersion;
|
||||
READWRITE(hashCheckpoint);
|
||||
)
|
||||
|
||||
void SetNull()
|
||||
{
|
||||
nVersion = 1;
|
||||
hashCheckpoint = 0;
|
||||
}
|
||||
|
||||
std::string ToString() const
|
||||
{
|
||||
return strprintf(
|
||||
"CSyncCheckpoint(\n"
|
||||
" nVersion = %d\n"
|
||||
" hashCheckpoint = %s\n"
|
||||
")\n",
|
||||
nVersion,
|
||||
hashCheckpoint.ToString().c_str());
|
||||
}
|
||||
|
||||
void print() const
|
||||
{
|
||||
printf("%s", ToString().c_str());
|
||||
}
|
||||
};
|
||||
|
||||
class CSyncCheckpoint : public CUnsignedSyncCheckpoint
|
||||
{
|
||||
public:
|
||||
static const std::string strMainPubKey;
|
||||
static const std::string strTestPubKey;
|
||||
static std::string strMasterPrivKey;
|
||||
|
||||
std::vector<unsigned char> vchMsg;
|
||||
std::vector<unsigned char> vchSig;
|
||||
|
||||
CSyncCheckpoint()
|
||||
{
|
||||
SetNull();
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(vchMsg);
|
||||
READWRITE(vchSig);
|
||||
)
|
||||
|
||||
void SetNull()
|
||||
{
|
||||
CUnsignedSyncCheckpoint::SetNull();
|
||||
vchMsg.clear();
|
||||
vchSig.clear();
|
||||
}
|
||||
|
||||
bool IsNull() const
|
||||
{
|
||||
return (hashCheckpoint == 0);
|
||||
}
|
||||
|
||||
uint256 GetHash() const
|
||||
{
|
||||
return Hash(this->vchMsg.begin(), this->vchMsg.end());
|
||||
}
|
||||
|
||||
bool RelayTo(CNode* pnode) const
|
||||
{
|
||||
// returns true if wasn't already sent
|
||||
if (pnode->hashCheckpointKnown != hashCheckpoint)
|
||||
{
|
||||
pnode->hashCheckpointKnown = hashCheckpoint;
|
||||
pnode->PushMessage("checkpoint", *this);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CheckSignature();
|
||||
bool ProcessSyncCheckpoint(CNode* pfrom);
|
||||
};
|
||||
|
||||
#endif
|
197
src/checkqueue.h
197
src/checkqueue.h
|
@ -1,197 +0,0 @@
|
|||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef CHECKQUEUE_H
|
||||
#define CHECKQUEUE_H
|
||||
|
||||
#include <boost/thread/mutex.hpp>
|
||||
#include <boost/thread/locks.hpp>
|
||||
#include <boost/thread/condition_variable.hpp>
|
||||
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
template<typename T> class CCheckQueueControl;
|
||||
|
||||
/** Queue for verifications that have to be performed.
|
||||
* The verifications are represented by a type T, which must provide an
|
||||
* operator(), returning a bool.
|
||||
*
|
||||
* One thread (the master) is assumed to push batches of verifications
|
||||
* onto the queue, where they are processed by N-1 worker threads. When
|
||||
* the master is done adding work, it temporarily joins the worker pool
|
||||
* as an N'th worker, until all jobs are done.
|
||||
*/
|
||||
template<typename T> class CCheckQueue {
|
||||
private:
|
||||
// Mutex to allow only one control class access at a time
|
||||
boost::mutex controlMutex;
|
||||
|
||||
// Mutex to protect the inner state
|
||||
boost::mutex mutex;
|
||||
|
||||
// Worker threads block on this when out of work
|
||||
boost::condition_variable condWorker;
|
||||
|
||||
// Master thread blocks on this when out of work
|
||||
boost::condition_variable condMaster;
|
||||
|
||||
// The queue of elements to be processed.
|
||||
// As the order of booleans doesn't matter, it is used as a LIFO (stack)
|
||||
std::vector<T> queue;
|
||||
|
||||
// The number of workers (including the master) that are idle.
|
||||
int nIdle;
|
||||
|
||||
// The total number of workers (including the master).
|
||||
int nTotal;
|
||||
|
||||
// The temporary evaluation result.
|
||||
bool fAllOk;
|
||||
|
||||
// Number of verifications that haven't completed yet.
|
||||
// This includes elements that are not anymore in queue, but still in
|
||||
// worker's own batches.
|
||||
unsigned int nTodo;
|
||||
|
||||
// Whether we're shutting down.
|
||||
bool fQuit;
|
||||
|
||||
// The maximum number of elements to be processed in one batch
|
||||
unsigned int nBatchSize;
|
||||
|
||||
// Internal function that does bulk of the verification work.
|
||||
bool Loop(bool fMaster = false) {
|
||||
boost::condition_variable &cond = fMaster ? condMaster : condWorker;
|
||||
std::vector<T> vChecks;
|
||||
vChecks.reserve(nBatchSize);
|
||||
unsigned int nNow = 0;
|
||||
bool fOk = true;
|
||||
do {
|
||||
{
|
||||
boost::unique_lock<boost::mutex> lock(mutex);
|
||||
// first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
|
||||
if (nNow) {
|
||||
fAllOk &= fOk;
|
||||
nTodo -= nNow;
|
||||
if (nTodo == 0 && !fMaster)
|
||||
// We processed the last element; inform the master he can exit and return the result
|
||||
condMaster.notify_one();
|
||||
} else {
|
||||
// first iteration
|
||||
nTotal++;
|
||||
}
|
||||
// logically, the do loop starts here
|
||||
while (queue.empty()) {
|
||||
if ((fMaster || fQuit) && nTodo == 0) {
|
||||
nTotal--;
|
||||
bool fRet = fAllOk;
|
||||
// reset the status for new work later
|
||||
if (fMaster)
|
||||
fAllOk = true;
|
||||
// return the current status
|
||||
return fRet;
|
||||
}
|
||||
nIdle++;
|
||||
cond.wait(lock); // wait
|
||||
nIdle--;
|
||||
}
|
||||
// Decide how many work units to process now.
|
||||
// * Do not try to do everything at once, but aim for increasingly smaller batches so
|
||||
// all workers finish approximately simultaneously.
|
||||
// * Try to account for idle jobs which will instantly start helping.
|
||||
// * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
|
||||
nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
|
||||
vChecks.resize(nNow);
|
||||
for (unsigned int i = 0; i < nNow; i++) {
|
||||
// We want the lock on the mutex to be as short as possible, so swap jobs from the global
|
||||
// queue to the local batch vector instead of copying.
|
||||
vChecks[i].swap(queue.back());
|
||||
queue.pop_back();
|
||||
}
|
||||
// Check whether we need to do work at all
|
||||
fOk = fAllOk;
|
||||
}
|
||||
// execute work
|
||||
BOOST_FOREACH(T &check, vChecks)
|
||||
if (fOk)
|
||||
fOk = check();
|
||||
vChecks.clear();
|
||||
} while(true);
|
||||
}
|
||||
|
||||
public:
|
||||
// Create a new check queue
|
||||
CCheckQueue(unsigned int nBatchSizeIn) :
|
||||
nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
|
||||
|
||||
// Worker thread
|
||||
void Thread() {
|
||||
Loop();
|
||||
}
|
||||
|
||||
// Wait until execution finishes, and return whether all evaluations where succesful.
|
||||
bool Wait() {
|
||||
return Loop(true);
|
||||
}
|
||||
|
||||
// Add a batch of checks to the queue
|
||||
void Add(std::vector<T> &vChecks) {
|
||||
boost::unique_lock<boost::mutex> lock(mutex);
|
||||
BOOST_FOREACH(T &check, vChecks) {
|
||||
queue.push_back(T());
|
||||
check.swap(queue.back());
|
||||
}
|
||||
nTodo += vChecks.size();
|
||||
if (vChecks.size() == 1)
|
||||
condWorker.notify_one();
|
||||
else if (vChecks.size() > 1)
|
||||
condWorker.notify_all();
|
||||
}
|
||||
|
||||
~CCheckQueue() {
|
||||
}
|
||||
|
||||
friend class CCheckQueueControl<T>;
|
||||
};
|
||||
|
||||
/** RAII-style controller object for a CCheckQueue that guarantees the passed
|
||||
* queue is finished before continuing.
|
||||
*/
|
||||
template<typename T> class CCheckQueueControl {
|
||||
private:
|
||||
CCheckQueue<T> *pqueue;
|
||||
bool fDone;
|
||||
|
||||
public:
|
||||
CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
|
||||
// passed queue is supposed to be unused, or NULL
|
||||
if (pqueue != NULL) {
|
||||
pqueue->controlMutex.lock();
|
||||
assert(pqueue->nTotal == pqueue->nIdle);
|
||||
assert(pqueue->nTodo == 0);
|
||||
assert(pqueue->fAllOk == true);
|
||||
}
|
||||
}
|
||||
|
||||
bool Wait() {
|
||||
if (pqueue == NULL)
|
||||
return true;
|
||||
bool fRet = pqueue->Wait();
|
||||
pqueue->controlMutex.unlock();
|
||||
fDone = true;
|
||||
return fRet;
|
||||
}
|
||||
|
||||
void Add(std::vector<T> &vChecks) {
|
||||
if (pqueue != NULL)
|
||||
pqueue->Add(vChecks);
|
||||
}
|
||||
|
||||
~CCheckQueueControl() {
|
||||
if (!fDone)
|
||||
Wait();
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
|
@ -28,7 +28,10 @@
|
|||
#include <net/if.h>
|
||||
#include <netinet/in.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <unistd.h>
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
typedef unsigned long long uint64;
|
||||
|
||||
#ifdef __sun__
|
||||
using std::map;
|
||||
|
|
121
src/crypter.cpp
121
src/crypter.cpp
|
@ -1,121 +0,0 @@
|
|||
// Copyright (c) 2009-2012 The Bitcoin Developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <openssl/aes.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#ifdef WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include "crypter.h"
|
||||
|
||||
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
|
||||
{
|
||||
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
|
||||
return false;
|
||||
|
||||
int i = 0;
|
||||
if (nDerivationMethod == 0)
|
||||
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
|
||||
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
|
||||
|
||||
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
|
||||
{
|
||||
OPENSSL_cleanse(chKey, sizeof(chKey));
|
||||
OPENSSL_cleanse(chIV, sizeof(chIV));
|
||||
return false;
|
||||
}
|
||||
|
||||
fKeySet = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
|
||||
{
|
||||
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
|
||||
return false;
|
||||
|
||||
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
|
||||
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
|
||||
|
||||
fKeySet = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
|
||||
{
|
||||
if (!fKeySet)
|
||||
return false;
|
||||
|
||||
// max ciphertext len for a n bytes of plaintext is
|
||||
// n + AES_BLOCK_SIZE - 1 bytes
|
||||
int nLen = vchPlaintext.size();
|
||||
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
|
||||
vchCiphertext = std::vector<unsigned char> (nCLen);
|
||||
|
||||
EVP_CIPHER_CTX ctx;
|
||||
|
||||
bool fOk = true;
|
||||
|
||||
EVP_CIPHER_CTX_init(&ctx);
|
||||
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
|
||||
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
|
||||
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
|
||||
EVP_CIPHER_CTX_cleanup(&ctx);
|
||||
|
||||
if (!fOk) return false;
|
||||
|
||||
vchCiphertext.resize(nCLen + nFLen);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
|
||||
{
|
||||
if (!fKeySet)
|
||||
return false;
|
||||
|
||||
// plaintext will always be equal to or lesser than length of ciphertext
|
||||
int nLen = vchCiphertext.size();
|
||||
int nPLen = nLen, nFLen = 0;
|
||||
|
||||
vchPlaintext = CKeyingMaterial(nPLen);
|
||||
|
||||
EVP_CIPHER_CTX ctx;
|
||||
|
||||
bool fOk = true;
|
||||
|
||||
EVP_CIPHER_CTX_init(&ctx);
|
||||
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
|
||||
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
|
||||
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
|
||||
EVP_CIPHER_CTX_cleanup(&ctx);
|
||||
|
||||
if (!fOk) return false;
|
||||
|
||||
vchPlaintext.resize(nPLen + nFLen);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
|
||||
{
|
||||
CCrypter cKeyCrypter;
|
||||
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
|
||||
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
|
||||
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
|
||||
return false;
|
||||
return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext);
|
||||
}
|
||||
|
||||
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CSecret& vchPlaintext)
|
||||
{
|
||||
CCrypter cKeyCrypter;
|
||||
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
|
||||
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
|
||||
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
|
||||
return false;
|
||||
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
|
||||
}
|
107
src/crypter.h
107
src/crypter.h
|
@ -1,107 +0,0 @@
|
|||
// Copyright (c) 2009-2012 The Bitcoin Developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef __CRYPTER_H__
|
||||
#define __CRYPTER_H__
|
||||
|
||||
#include "allocators.h" /* for SecureString */
|
||||
#include "key.h"
|
||||
#include "serialize.h"
|
||||
|
||||
const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
|
||||
const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
|
||||
|
||||
/*
|
||||
Private key encryption is done based on a CMasterKey,
|
||||
which holds a salt and random encryption key.
|
||||
|
||||
CMasterKeys are encrypted using AES-256-CBC using a key
|
||||
derived using derivation method nDerivationMethod
|
||||
(0 == EVP_sha512()) and derivation iterations nDeriveIterations.
|
||||
vchOtherDerivationParameters is provided for alternative algorithms
|
||||
which may require more parameters (such as scrypt).
|
||||
|
||||
Wallet Private Keys are then encrypted using AES-256-CBC
|
||||
with the double-sha256 of the public key as the IV, and the
|
||||
master key's key as the encryption key (see keystore.[ch]).
|
||||
*/
|
||||
|
||||
/** Master key for wallet encryption */
|
||||
class CMasterKey
|
||||
{
|
||||
public:
|
||||
std::vector<unsigned char> vchCryptedKey;
|
||||
std::vector<unsigned char> vchSalt;
|
||||
// 0 = EVP_sha512()
|
||||
// 1 = scrypt()
|
||||
unsigned int nDerivationMethod;
|
||||
unsigned int nDeriveIterations;
|
||||
// Use this for more parameters to key derivation,
|
||||
// such as the various parameters to scrypt
|
||||
std::vector<unsigned char> vchOtherDerivationParameters;
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(vchCryptedKey);
|
||||
READWRITE(vchSalt);
|
||||
READWRITE(nDerivationMethod);
|
||||
READWRITE(nDeriveIterations);
|
||||
READWRITE(vchOtherDerivationParameters);
|
||||
)
|
||||
CMasterKey()
|
||||
{
|
||||
// 25000 rounds is just under 0.1 seconds on a 1.86 GHz Pentium M
|
||||
// ie slightly lower than the lowest hardware we need bother supporting
|
||||
nDeriveIterations = 25000;
|
||||
nDerivationMethod = 0;
|
||||
vchOtherDerivationParameters = std::vector<unsigned char>(0);
|
||||
}
|
||||
};
|
||||
|
||||
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
|
||||
|
||||
/** Encryption/decryption context with key information */
|
||||
class CCrypter
|
||||
{
|
||||
private:
|
||||
unsigned char chKey[WALLET_CRYPTO_KEY_SIZE];
|
||||
unsigned char chIV[WALLET_CRYPTO_KEY_SIZE];
|
||||
bool fKeySet;
|
||||
|
||||
public:
|
||||
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod);
|
||||
bool Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext);
|
||||
bool Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext);
|
||||
bool SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV);
|
||||
|
||||
void CleanKey()
|
||||
{
|
||||
OPENSSL_cleanse(chKey, sizeof(chKey));
|
||||
OPENSSL_cleanse(chIV, sizeof(chIV));
|
||||
fKeySet = false;
|
||||
}
|
||||
|
||||
CCrypter()
|
||||
{
|
||||
fKeySet = false;
|
||||
|
||||
// Try to keep the key data out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap)
|
||||
// Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
|
||||
// Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.
|
||||
LockedPageManager::instance.LockRange(&chKey[0], sizeof chKey);
|
||||
LockedPageManager::instance.LockRange(&chIV[0], sizeof chIV);
|
||||
}
|
||||
|
||||
~CCrypter()
|
||||
{
|
||||
CleanKey();
|
||||
|
||||
LockedPageManager::instance.UnlockRange(&chKey[0], sizeof chKey);
|
||||
LockedPageManager::instance.UnlockRange(&chIV[0], sizeof chIV);
|
||||
}
|
||||
};
|
||||
|
||||
bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext);
|
||||
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char> &vchCiphertext, const uint256& nIV, CSecret &vchPlaintext);
|
||||
|
||||
#endif
|
583
src/db.cpp
583
src/db.cpp
|
@ -1,583 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "db.h"
|
||||
#include "util.h"
|
||||
#include "main.h"
|
||||
#include <boost/version.hpp>
|
||||
#include <boost/filesystem.hpp>
|
||||
#include <boost/filesystem/fstream.hpp>
|
||||
|
||||
#ifndef WIN32
|
||||
#include "sys/stat.h"
|
||||
#endif
|
||||
|
||||
using namespace std;
|
||||
using namespace boost;
|
||||
|
||||
|
||||
unsigned int nWalletDBUpdated;
|
||||
|
||||
|
||||
|
||||
//
|
||||
// CDB
|
||||
//
|
||||
|
||||
CDBEnv bitdb;
|
||||
|
||||
void CDBEnv::EnvShutdown()
|
||||
{
|
||||
if (!fDbEnvInit)
|
||||
return;
|
||||
|
||||
fDbEnvInit = false;
|
||||
int ret = dbenv.close(0);
|
||||
if (ret != 0)
|
||||
printf("EnvShutdown exception: %s (%d)\n", DbEnv::strerror(ret), ret);
|
||||
if (!fMockDb)
|
||||
DbEnv(0).remove(path.string().c_str(), 0);
|
||||
}
|
||||
|
||||
CDBEnv::CDBEnv() : dbenv(DB_CXX_NO_EXCEPTIONS)
|
||||
{
|
||||
fDbEnvInit = false;
|
||||
fMockDb = false;
|
||||
}
|
||||
|
||||
CDBEnv::~CDBEnv()
|
||||
{
|
||||
EnvShutdown();
|
||||
}
|
||||
|
||||
void CDBEnv::Close()
|
||||
{
|
||||
EnvShutdown();
|
||||
}
|
||||
|
||||
bool CDBEnv::Open(const boost::filesystem::path& pathIn)
|
||||
{
|
||||
if (fDbEnvInit)
|
||||
return true;
|
||||
|
||||
boost::this_thread::interruption_point();
|
||||
|
||||
path = pathIn;
|
||||
filesystem::path pathLogDir = path / "database";
|
||||
filesystem::create_directory(pathLogDir);
|
||||
filesystem::path pathErrorFile = path / "db.log";
|
||||
printf("dbenv.open LogDir=%s ErrorFile=%s\n", pathLogDir.string().c_str(), pathErrorFile.string().c_str());
|
||||
|
||||
unsigned int nEnvFlags = 0;
|
||||
if (GetBoolArg("-privdb", true))
|
||||
nEnvFlags |= DB_PRIVATE;
|
||||
|
||||
dbenv.set_lg_dir(pathLogDir.string().c_str());
|
||||
dbenv.set_cachesize(0, 0x100000, 1); // 1 MiB should be enough for just the wallet
|
||||
dbenv.set_lg_bsize(0x10000);
|
||||
dbenv.set_lg_max(1048576);
|
||||
dbenv.set_lk_max_locks(40000);
|
||||
dbenv.set_lk_max_objects(40000);
|
||||
dbenv.set_errfile(fopen(pathErrorFile.string().c_str(), "a")); /// debug
|
||||
dbenv.set_flags(DB_AUTO_COMMIT, 1);
|
||||
dbenv.set_flags(DB_TXN_WRITE_NOSYNC, 1);
|
||||
dbenv.log_set_config(DB_LOG_AUTO_REMOVE, 1);
|
||||
int ret = dbenv.open(path.string().c_str(),
|
||||
DB_CREATE |
|
||||
DB_INIT_LOCK |
|
||||
DB_INIT_LOG |
|
||||
DB_INIT_MPOOL |
|
||||
DB_INIT_TXN |
|
||||
DB_THREAD |
|
||||
DB_RECOVER |
|
||||
nEnvFlags,
|
||||
S_IRUSR | S_IWUSR);
|
||||
if (ret != 0)
|
||||
return error("CDB() : error %s (%d) opening database environment", DbEnv::strerror(ret), ret);
|
||||
|
||||
fDbEnvInit = true;
|
||||
fMockDb = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void CDBEnv::MakeMock()
|
||||
{
|
||||
if (fDbEnvInit)
|
||||
throw runtime_error("CDBEnv::MakeMock(): already initialized");
|
||||
|
||||
boost::this_thread::interruption_point();
|
||||
|
||||
printf("CDBEnv::MakeMock()\n");
|
||||
|
||||
dbenv.set_cachesize(1, 0, 1);
|
||||
dbenv.set_lg_bsize(10485760*4);
|
||||
dbenv.set_lg_max(10485760);
|
||||
dbenv.set_lk_max_locks(10000);
|
||||
dbenv.set_lk_max_objects(10000);
|
||||
dbenv.set_flags(DB_AUTO_COMMIT, 1);
|
||||
dbenv.log_set_config(DB_LOG_IN_MEMORY, 1);
|
||||
int ret = dbenv.open(NULL,
|
||||
DB_CREATE |
|
||||
DB_INIT_LOCK |
|
||||
DB_INIT_LOG |
|
||||
DB_INIT_MPOOL |
|
||||
DB_INIT_TXN |
|
||||
DB_THREAD |
|
||||
DB_PRIVATE,
|
||||
S_IRUSR | S_IWUSR);
|
||||
if (ret > 0)
|
||||
throw runtime_error(strprintf("CDBEnv::MakeMock(): error %d opening database environment", ret));
|
||||
|
||||
fDbEnvInit = true;
|
||||
fMockDb = true;
|
||||
}
|
||||
|
||||
CDBEnv::VerifyResult CDBEnv::Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile))
|
||||
{
|
||||
LOCK(cs_db);
|
||||
assert(mapFileUseCount.count(strFile) == 0);
|
||||
|
||||
Db db(&dbenv, 0);
|
||||
int result = db.verify(strFile.c_str(), NULL, NULL, 0);
|
||||
if (result == 0)
|
||||
return VERIFY_OK;
|
||||
else if (recoverFunc == NULL)
|
||||
return RECOVER_FAIL;
|
||||
|
||||
// Try to recover:
|
||||
bool fRecovered = (*recoverFunc)(*this, strFile);
|
||||
return (fRecovered ? RECOVER_OK : RECOVER_FAIL);
|
||||
}
|
||||
|
||||
bool CDBEnv::Salvage(std::string strFile, bool fAggressive,
|
||||
std::vector<CDBEnv::KeyValPair >& vResult)
|
||||
{
|
||||
LOCK(cs_db);
|
||||
assert(mapFileUseCount.count(strFile) == 0);
|
||||
|
||||
u_int32_t flags = DB_SALVAGE;
|
||||
if (fAggressive) flags |= DB_AGGRESSIVE;
|
||||
|
||||
stringstream strDump;
|
||||
|
||||
Db db(&dbenv, 0);
|
||||
int result = db.verify(strFile.c_str(), NULL, &strDump, flags);
|
||||
if (result == DB_VERIFY_BAD)
|
||||
{
|
||||
printf("Error: Salvage found errors, all data may not be recoverable.\n");
|
||||
if (!fAggressive)
|
||||
{
|
||||
printf("Error: Rerun with aggressive mode to ignore errors and continue.\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (result != 0 && result != DB_VERIFY_BAD)
|
||||
{
|
||||
printf("ERROR: db salvage failed: %d\n",result);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Format of bdb dump is ascii lines:
|
||||
// header lines...
|
||||
// HEADER=END
|
||||
// hexadecimal key
|
||||
// hexadecimal value
|
||||
// ... repeated
|
||||
// DATA=END
|
||||
|
||||
string strLine;
|
||||
while (!strDump.eof() && strLine != "HEADER=END")
|
||||
getline(strDump, strLine); // Skip past header
|
||||
|
||||
std::string keyHex, valueHex;
|
||||
while (!strDump.eof() && keyHex != "DATA=END")
|
||||
{
|
||||
getline(strDump, keyHex);
|
||||
if (keyHex != "DATA_END")
|
||||
{
|
||||
getline(strDump, valueHex);
|
||||
vResult.push_back(make_pair(ParseHex(keyHex),ParseHex(valueHex)));
|
||||
}
|
||||
}
|
||||
|
||||
return (result == 0);
|
||||
}
|
||||
|
||||
|
||||
void CDBEnv::CheckpointLSN(std::string strFile)
|
||||
{
|
||||
dbenv.txn_checkpoint(0, 0, 0);
|
||||
if (fMockDb)
|
||||
return;
|
||||
dbenv.lsn_reset(strFile.c_str(), 0);
|
||||
}
|
||||
|
||||
|
||||
CDB::CDB(const char *pszFile, const char* pszMode) :
|
||||
pdb(NULL), activeTxn(NULL)
|
||||
{
|
||||
int ret;
|
||||
if (pszFile == NULL)
|
||||
return;
|
||||
|
||||
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
|
||||
bool fCreate = strchr(pszMode, 'c');
|
||||
unsigned int nFlags = DB_THREAD;
|
||||
if (fCreate)
|
||||
nFlags |= DB_CREATE;
|
||||
|
||||
{
|
||||
LOCK(bitdb.cs_db);
|
||||
if (!bitdb.Open(GetDataDir()))
|
||||
throw runtime_error("env open failed");
|
||||
|
||||
strFile = pszFile;
|
||||
++bitdb.mapFileUseCount[strFile];
|
||||
pdb = bitdb.mapDb[strFile];
|
||||
if (pdb == NULL)
|
||||
{
|
||||
pdb = new Db(&bitdb.dbenv, 0);
|
||||
|
||||
bool fMockDb = bitdb.IsMock();
|
||||
if (fMockDb)
|
||||
{
|
||||
DbMpoolFile*mpf = pdb->get_mpf();
|
||||
ret = mpf->set_flags(DB_MPOOL_NOFILE, 1);
|
||||
if (ret != 0)
|
||||
throw runtime_error(strprintf("CDB() : failed to configure for no temp file backing for database %s", pszFile));
|
||||
}
|
||||
|
||||
ret = pdb->open(NULL, // Txn pointer
|
||||
fMockDb ? NULL : pszFile, // Filename
|
||||
fMockDb ? pszFile : "main", // Logical db name
|
||||
DB_BTREE, // Database type
|
||||
nFlags, // Flags
|
||||
0);
|
||||
|
||||
if (ret != 0)
|
||||
{
|
||||
delete pdb;
|
||||
pdb = NULL;
|
||||
--bitdb.mapFileUseCount[strFile];
|
||||
strFile = "";
|
||||
throw runtime_error(strprintf("CDB() : can't open database file %s, error %d", pszFile, ret));
|
||||
}
|
||||
|
||||
if (fCreate && !Exists(string("version")))
|
||||
{
|
||||
bool fTmp = fReadOnly;
|
||||
fReadOnly = false;
|
||||
WriteVersion(CLIENT_VERSION);
|
||||
fReadOnly = fTmp;
|
||||
}
|
||||
|
||||
bitdb.mapDb[strFile] = pdb;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CDB::Flush()
|
||||
{
|
||||
if (activeTxn)
|
||||
return;
|
||||
|
||||
// Flush database activity from memory pool to disk log
|
||||
unsigned int nMinutes = 0;
|
||||
if (fReadOnly)
|
||||
nMinutes = 1;
|
||||
|
||||
bitdb.dbenv.txn_checkpoint(nMinutes ? GetArg("-dblogsize", 100)*1024 : 0, nMinutes, 0);
|
||||
}
|
||||
|
||||
void CDB::Close()
|
||||
{
|
||||
if (!pdb)
|
||||
return;
|
||||
if (activeTxn)
|
||||
activeTxn->abort();
|
||||
activeTxn = NULL;
|
||||
pdb = NULL;
|
||||
|
||||
Flush();
|
||||
|
||||
{
|
||||
LOCK(bitdb.cs_db);
|
||||
--bitdb.mapFileUseCount[strFile];
|
||||
}
|
||||
}
|
||||
|
||||
void CDBEnv::CloseDb(const string& strFile)
|
||||
{
|
||||
{
|
||||
LOCK(cs_db);
|
||||
if (mapDb[strFile] != NULL)
|
||||
{
|
||||
// Close the database handle
|
||||
Db* pdb = mapDb[strFile];
|
||||
pdb->close(0);
|
||||
delete pdb;
|
||||
mapDb[strFile] = NULL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CDBEnv::RemoveDb(const string& strFile)
|
||||
{
|
||||
this->CloseDb(strFile);
|
||||
|
||||
LOCK(cs_db);
|
||||
int rc = dbenv.dbremove(NULL, strFile.c_str(), NULL, DB_AUTO_COMMIT);
|
||||
return (rc == 0);
|
||||
}
|
||||
|
||||
bool CDB::Rewrite(const string& strFile, const char* pszSkip)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
{
|
||||
LOCK(bitdb.cs_db);
|
||||
if (!bitdb.mapFileUseCount.count(strFile) || bitdb.mapFileUseCount[strFile] == 0)
|
||||
{
|
||||
// Flush log data to the dat file
|
||||
bitdb.CloseDb(strFile);
|
||||
bitdb.CheckpointLSN(strFile);
|
||||
bitdb.mapFileUseCount.erase(strFile);
|
||||
|
||||
bool fSuccess = true;
|
||||
printf("Rewriting %s...\n", strFile.c_str());
|
||||
string strFileRes = strFile + ".rewrite";
|
||||
{ // surround usage of db with extra {}
|
||||
CDB db(strFile.c_str(), "r");
|
||||
Db* pdbCopy = new Db(&bitdb.dbenv, 0);
|
||||
|
||||
int ret = pdbCopy->open(NULL, // Txn pointer
|
||||
strFileRes.c_str(), // Filename
|
||||
"main", // Logical db name
|
||||
DB_BTREE, // Database type
|
||||
DB_CREATE, // Flags
|
||||
0);
|
||||
if (ret > 0)
|
||||
{
|
||||
printf("Cannot create database file %s\n", strFileRes.c_str());
|
||||
fSuccess = false;
|
||||
}
|
||||
|
||||
Dbc* pcursor = db.GetCursor();
|
||||
if (pcursor)
|
||||
while (fSuccess)
|
||||
{
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||
int ret = db.ReadAtCursor(pcursor, ssKey, ssValue, DB_NEXT);
|
||||
if (ret == DB_NOTFOUND)
|
||||
{
|
||||
pcursor->close();
|
||||
break;
|
||||
}
|
||||
else if (ret != 0)
|
||||
{
|
||||
pcursor->close();
|
||||
fSuccess = false;
|
||||
break;
|
||||
}
|
||||
if (pszSkip &&
|
||||
strncmp(&ssKey[0], pszSkip, std::min(ssKey.size(), strlen(pszSkip))) == 0)
|
||||
continue;
|
||||
if (strncmp(&ssKey[0], "\x07version", 8) == 0)
|
||||
{
|
||||
// Update version:
|
||||
ssValue.clear();
|
||||
ssValue << CLIENT_VERSION;
|
||||
}
|
||||
Dbt datKey(&ssKey[0], ssKey.size());
|
||||
Dbt datValue(&ssValue[0], ssValue.size());
|
||||
int ret2 = pdbCopy->put(NULL, &datKey, &datValue, DB_NOOVERWRITE);
|
||||
if (ret2 > 0)
|
||||
fSuccess = false;
|
||||
}
|
||||
if (fSuccess)
|
||||
{
|
||||
db.Close();
|
||||
bitdb.CloseDb(strFile);
|
||||
if (pdbCopy->close(0))
|
||||
fSuccess = false;
|
||||
delete pdbCopy;
|
||||
}
|
||||
}
|
||||
if (fSuccess)
|
||||
{
|
||||
Db dbA(&bitdb.dbenv, 0);
|
||||
if (dbA.remove(strFile.c_str(), NULL, 0))
|
||||
fSuccess = false;
|
||||
Db dbB(&bitdb.dbenv, 0);
|
||||
if (dbB.rename(strFileRes.c_str(), NULL, strFile.c_str(), 0))
|
||||
fSuccess = false;
|
||||
}
|
||||
if (!fSuccess)
|
||||
printf("Rewriting of %s FAILED!\n", strFileRes.c_str());
|
||||
return fSuccess;
|
||||
}
|
||||
}
|
||||
MilliSleep(100);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
void CDBEnv::Flush(bool fShutdown)
|
||||
{
|
||||
int64 nStart = GetTimeMillis();
|
||||
// Flush log data to the actual data file
|
||||
// on all files that are not in use
|
||||
printf("Flush(%s)%s\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started");
|
||||
if (!fDbEnvInit)
|
||||
return;
|
||||
{
|
||||
LOCK(cs_db);
|
||||
map<string, int>::iterator mi = mapFileUseCount.begin();
|
||||
while (mi != mapFileUseCount.end())
|
||||
{
|
||||
string strFile = (*mi).first;
|
||||
int nRefCount = (*mi).second;
|
||||
printf("%s refcount=%d\n", strFile.c_str(), nRefCount);
|
||||
if (nRefCount == 0)
|
||||
{
|
||||
// Move log data to the dat file
|
||||
CloseDb(strFile);
|
||||
printf("%s checkpoint\n", strFile.c_str());
|
||||
dbenv.txn_checkpoint(0, 0, 0);
|
||||
printf("%s detach\n", strFile.c_str());
|
||||
if (!fMockDb)
|
||||
dbenv.lsn_reset(strFile.c_str(), 0);
|
||||
printf("%s closed\n", strFile.c_str());
|
||||
mapFileUseCount.erase(mi++);
|
||||
}
|
||||
else
|
||||
mi++;
|
||||
}
|
||||
printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
|
||||
if (fShutdown)
|
||||
{
|
||||
char** listp;
|
||||
if (mapFileUseCount.empty())
|
||||
{
|
||||
dbenv.log_archive(&listp, DB_ARCH_REMOVE);
|
||||
Close();
|
||||
if (!fMockDb)
|
||||
boost::filesystem::remove_all(path / "database");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//
|
||||
// CAddrDB
|
||||
//
|
||||
|
||||
|
||||
CAddrDB::CAddrDB()
|
||||
{
|
||||
pathAddr = GetDataDir() / "peers.dat";
|
||||
}
|
||||
|
||||
bool CAddrDB::Write(const CAddrMan& addr)
|
||||
{
|
||||
// Generate random temporary filename
|
||||
unsigned short randv = 0;
|
||||
RAND_bytes((unsigned char *)&randv, sizeof(randv));
|
||||
std::string tmpfn = strprintf("peers.dat.%04x", randv);
|
||||
|
||||
// serialize addresses, checksum data up to that point, then append csum
|
||||
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
|
||||
ssPeers << FLATDATA(pchMessageStart);
|
||||
ssPeers << addr;
|
||||
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
|
||||
ssPeers << hash;
|
||||
|
||||
// open temp output file, and associate with CAutoFile
|
||||
boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
|
||||
FILE *file = fopen(pathTmp.string().c_str(), "wb");
|
||||
CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION);
|
||||
if (!fileout)
|
||||
return error("CAddrman::Write() : open failed");
|
||||
|
||||
// Write and commit header, data
|
||||
try {
|
||||
fileout << ssPeers;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
return error("CAddrman::Write() : I/O error");
|
||||
}
|
||||
FileCommit(fileout);
|
||||
fileout.fclose();
|
||||
|
||||
// replace existing peers.dat, if any, with new peers.dat.XXXX
|
||||
if (!RenameOver(pathTmp, pathAddr))
|
||||
return error("CAddrman::Write() : Rename-into-place failed");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CAddrDB::Read(CAddrMan& addr)
|
||||
{
|
||||
// open input file, and associate with CAutoFile
|
||||
FILE *file = fopen(pathAddr.string().c_str(), "rb");
|
||||
CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION);
|
||||
if (!filein)
|
||||
return error("CAddrman::Read() : open failed");
|
||||
|
||||
// use file size to size memory buffer
|
||||
int fileSize = GetFilesize(filein);
|
||||
int dataSize = fileSize - sizeof(uint256);
|
||||
vector<unsigned char> vchData;
|
||||
vchData.resize(dataSize);
|
||||
uint256 hashIn;
|
||||
|
||||
// read data and checksum from file
|
||||
try {
|
||||
filein.read((char *)&vchData[0], dataSize);
|
||||
filein >> hashIn;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
return error("CAddrman::Read() 2 : I/O error or stream data corrupted");
|
||||
}
|
||||
filein.fclose();
|
||||
|
||||
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
|
||||
|
||||
// verify stored checksum matches input data
|
||||
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
|
||||
if (hashIn != hashTmp)
|
||||
return error("CAddrman::Read() : checksum mismatch; data corrupted");
|
||||
|
||||
unsigned char pchMsgTmp[4];
|
||||
try {
|
||||
// de-serialize file header (pchMessageStart magic number) and
|
||||
ssPeers >> FLATDATA(pchMsgTmp);
|
||||
|
||||
// verify the network matches ours
|
||||
if (memcmp(pchMsgTmp, pchMessageStart, sizeof(pchMsgTmp)))
|
||||
return error("CAddrman::Read() : invalid network magic number");
|
||||
|
||||
// de-serialize address data into one CAddrMan object
|
||||
ssPeers >> addr;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
return error("CAddrman::Read() : I/O error or stream data corrupted");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
327
src/db.h
327
src/db.h
|
@ -1,327 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_DB_H
|
||||
#define BITCOIN_DB_H
|
||||
|
||||
#include "main.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <db_cxx.h>
|
||||
|
||||
class CAddress;
|
||||
class CAddrMan;
|
||||
class CBlockLocator;
|
||||
class CDiskBlockIndex;
|
||||
class CMasterKey;
|
||||
class COutPoint;
|
||||
class CWallet;
|
||||
class CWalletTx;
|
||||
|
||||
extern unsigned int nWalletDBUpdated;
|
||||
|
||||
void ThreadFlushWalletDB(const std::string& strWalletFile);
|
||||
bool BackupWallet(const CWallet& wallet, const std::string& strDest);
|
||||
|
||||
|
||||
class CDBEnv
|
||||
{
|
||||
private:
|
||||
bool fDbEnvInit;
|
||||
bool fMockDb;
|
||||
boost::filesystem::path path;
|
||||
|
||||
void EnvShutdown();
|
||||
|
||||
public:
|
||||
mutable CCriticalSection cs_db;
|
||||
DbEnv dbenv;
|
||||
std::map<std::string, int> mapFileUseCount;
|
||||
std::map<std::string, Db*> mapDb;
|
||||
|
||||
CDBEnv();
|
||||
~CDBEnv();
|
||||
void MakeMock();
|
||||
bool IsMock() { return fMockDb; }
|
||||
|
||||
/*
|
||||
* Verify that database file strFile is OK. If it is not,
|
||||
* call the callback to try to recover.
|
||||
* This must be called BEFORE strFile is opened.
|
||||
* Returns true if strFile is OK.
|
||||
*/
|
||||
enum VerifyResult { VERIFY_OK, RECOVER_OK, RECOVER_FAIL };
|
||||
VerifyResult Verify(std::string strFile, bool (*recoverFunc)(CDBEnv& dbenv, std::string strFile));
|
||||
/*
|
||||
* Salvage data from a file that Verify says is bad.
|
||||
* fAggressive sets the DB_AGGRESSIVE flag (see berkeley DB->verify() method documentation).
|
||||
* Appends binary key/value pairs to vResult, returns true if successful.
|
||||
* NOTE: reads the entire database into memory, so cannot be used
|
||||
* for huge databases.
|
||||
*/
|
||||
typedef std::pair<std::vector<unsigned char>, std::vector<unsigned char> > KeyValPair;
|
||||
bool Salvage(std::string strFile, bool fAggressive, std::vector<KeyValPair>& vResult);
|
||||
|
||||
bool Open(const boost::filesystem::path &path);
|
||||
void Close();
|
||||
void Flush(bool fShutdown);
|
||||
void CheckpointLSN(std::string strFile);
|
||||
|
||||
void CloseDb(const std::string& strFile);
|
||||
bool RemoveDb(const std::string& strFile);
|
||||
|
||||
DbTxn *TxnBegin(int flags=DB_TXN_WRITE_NOSYNC)
|
||||
{
|
||||
DbTxn* ptxn = NULL;
|
||||
int ret = dbenv.txn_begin(NULL, &ptxn, flags);
|
||||
if (!ptxn || ret != 0)
|
||||
return NULL;
|
||||
return ptxn;
|
||||
}
|
||||
};
|
||||
|
||||
extern CDBEnv bitdb;
|
||||
|
||||
|
||||
/** RAII class that provides access to a Berkeley database */
|
||||
class CDB
|
||||
{
|
||||
protected:
|
||||
Db* pdb;
|
||||
std::string strFile;
|
||||
DbTxn *activeTxn;
|
||||
bool fReadOnly;
|
||||
|
||||
explicit CDB(const char* pszFile, const char* pszMode="r+");
|
||||
~CDB() { Close(); }
|
||||
public:
|
||||
void Flush();
|
||||
void Close();
|
||||
private:
|
||||
CDB(const CDB&);
|
||||
void operator=(const CDB&);
|
||||
|
||||
protected:
|
||||
template<typename K, typename T>
|
||||
bool Read(const K& key, T& value)
|
||||
{
|
||||
if (!pdb)
|
||||
return false;
|
||||
|
||||
// Key
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(1000);
|
||||
ssKey << key;
|
||||
Dbt datKey(&ssKey[0], ssKey.size());
|
||||
|
||||
// Read
|
||||
Dbt datValue;
|
||||
datValue.set_flags(DB_DBT_MALLOC);
|
||||
int ret = pdb->get(activeTxn, &datKey, &datValue, 0);
|
||||
memset(datKey.get_data(), 0, datKey.get_size());
|
||||
if (datValue.get_data() == NULL)
|
||||
return false;
|
||||
|
||||
// Unserialize value
|
||||
try {
|
||||
CDataStream ssValue((char*)datValue.get_data(), (char*)datValue.get_data() + datValue.get_size(), SER_DISK, CLIENT_VERSION);
|
||||
ssValue >> value;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Clear and free memory
|
||||
memset(datValue.get_data(), 0, datValue.get_size());
|
||||
free(datValue.get_data());
|
||||
return (ret == 0);
|
||||
}
|
||||
|
||||
template<typename K, typename T>
|
||||
bool Write(const K& key, const T& value, bool fOverwrite=true)
|
||||
{
|
||||
if (!pdb)
|
||||
return false;
|
||||
if (fReadOnly)
|
||||
assert(!"Write called on database in read-only mode");
|
||||
|
||||
// Key
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(1000);
|
||||
ssKey << key;
|
||||
Dbt datKey(&ssKey[0], ssKey.size());
|
||||
|
||||
// Value
|
||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||
ssValue.reserve(10000);
|
||||
ssValue << value;
|
||||
Dbt datValue(&ssValue[0], ssValue.size());
|
||||
|
||||
// Write
|
||||
int ret = pdb->put(activeTxn, &datKey, &datValue, (fOverwrite ? 0 : DB_NOOVERWRITE));
|
||||
|
||||
// Clear memory in case it was a private key
|
||||
memset(datKey.get_data(), 0, datKey.get_size());
|
||||
memset(datValue.get_data(), 0, datValue.get_size());
|
||||
return (ret == 0);
|
||||
}
|
||||
|
||||
template<typename K>
|
||||
bool Erase(const K& key)
|
||||
{
|
||||
if (!pdb)
|
||||
return false;
|
||||
if (fReadOnly)
|
||||
assert(!"Erase called on database in read-only mode");
|
||||
|
||||
// Key
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(1000);
|
||||
ssKey << key;
|
||||
Dbt datKey(&ssKey[0], ssKey.size());
|
||||
|
||||
// Erase
|
||||
int ret = pdb->del(activeTxn, &datKey, 0);
|
||||
|
||||
// Clear memory
|
||||
memset(datKey.get_data(), 0, datKey.get_size());
|
||||
return (ret == 0 || ret == DB_NOTFOUND);
|
||||
}
|
||||
|
||||
template<typename K>
|
||||
bool Exists(const K& key)
|
||||
{
|
||||
if (!pdb)
|
||||
return false;
|
||||
|
||||
// Key
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(1000);
|
||||
ssKey << key;
|
||||
Dbt datKey(&ssKey[0], ssKey.size());
|
||||
|
||||
// Exists
|
||||
int ret = pdb->exists(activeTxn, &datKey, 0);
|
||||
|
||||
// Clear memory
|
||||
memset(datKey.get_data(), 0, datKey.get_size());
|
||||
return (ret == 0);
|
||||
}
|
||||
|
||||
Dbc* GetCursor()
|
||||
{
|
||||
if (!pdb)
|
||||
return NULL;
|
||||
Dbc* pcursor = NULL;
|
||||
int ret = pdb->cursor(NULL, &pcursor, 0);
|
||||
if (ret != 0)
|
||||
return NULL;
|
||||
return pcursor;
|
||||
}
|
||||
|
||||
int ReadAtCursor(Dbc* pcursor, CDataStream& ssKey, CDataStream& ssValue, unsigned int fFlags=DB_NEXT)
|
||||
{
|
||||
// Read at cursor
|
||||
Dbt datKey;
|
||||
if (fFlags == DB_SET || fFlags == DB_SET_RANGE || fFlags == DB_GET_BOTH || fFlags == DB_GET_BOTH_RANGE)
|
||||
{
|
||||
datKey.set_data(&ssKey[0]);
|
||||
datKey.set_size(ssKey.size());
|
||||
}
|
||||
Dbt datValue;
|
||||
if (fFlags == DB_GET_BOTH || fFlags == DB_GET_BOTH_RANGE)
|
||||
{
|
||||
datValue.set_data(&ssValue[0]);
|
||||
datValue.set_size(ssValue.size());
|
||||
}
|
||||
datKey.set_flags(DB_DBT_MALLOC);
|
||||
datValue.set_flags(DB_DBT_MALLOC);
|
||||
int ret = pcursor->get(&datKey, &datValue, fFlags);
|
||||
if (ret != 0)
|
||||
return ret;
|
||||
else if (datKey.get_data() == NULL || datValue.get_data() == NULL)
|
||||
return 99999;
|
||||
|
||||
// Convert to streams
|
||||
ssKey.SetType(SER_DISK);
|
||||
ssKey.clear();
|
||||
ssKey.write((char*)datKey.get_data(), datKey.get_size());
|
||||
ssValue.SetType(SER_DISK);
|
||||
ssValue.clear();
|
||||
ssValue.write((char*)datValue.get_data(), datValue.get_size());
|
||||
|
||||
// Clear and free memory
|
||||
memset(datKey.get_data(), 0, datKey.get_size());
|
||||
memset(datValue.get_data(), 0, datValue.get_size());
|
||||
free(datKey.get_data());
|
||||
free(datValue.get_data());
|
||||
return 0;
|
||||
}
|
||||
|
||||
public:
|
||||
bool TxnBegin()
|
||||
{
|
||||
if (!pdb || activeTxn)
|
||||
return false;
|
||||
DbTxn* ptxn = bitdb.TxnBegin();
|
||||
if (!ptxn)
|
||||
return false;
|
||||
activeTxn = ptxn;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TxnCommit()
|
||||
{
|
||||
if (!pdb || !activeTxn)
|
||||
return false;
|
||||
int ret = activeTxn->commit(0);
|
||||
activeTxn = NULL;
|
||||
return (ret == 0);
|
||||
}
|
||||
|
||||
bool TxnAbort()
|
||||
{
|
||||
if (!pdb || !activeTxn)
|
||||
return false;
|
||||
int ret = activeTxn->abort();
|
||||
activeTxn = NULL;
|
||||
return (ret == 0);
|
||||
}
|
||||
|
||||
bool ReadVersion(int& nVersion)
|
||||
{
|
||||
nVersion = 0;
|
||||
return Read(std::string("version"), nVersion);
|
||||
}
|
||||
|
||||
bool WriteVersion(int nVersion)
|
||||
{
|
||||
return Write(std::string("version"), nVersion);
|
||||
}
|
||||
|
||||
bool static Rewrite(const std::string& strFile, const char* pszSkip = NULL);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/** Access to the (IP) address database (peers.dat) */
|
||||
class CAddrDB
|
||||
{
|
||||
private:
|
||||
boost::filesystem::path pathAddr;
|
||||
public:
|
||||
CAddrDB();
|
||||
bool Write(const CAddrMan& addr);
|
||||
bool Read(CAddrMan& addr);
|
||||
};
|
||||
|
||||
#endif // BITCOIN_DB_H
|
58
src/hash.cpp
58
src/hash.cpp
|
@ -1,58 +0,0 @@
|
|||
#include "hash.h"
|
||||
|
||||
inline uint32_t ROTL32 ( uint32_t x, int8_t r )
|
||||
{
|
||||
return (x << r) | (x >> (32 - r));
|
||||
}
|
||||
|
||||
unsigned int MurmurHash3(unsigned int nHashSeed, const std::vector<unsigned char>& vDataToHash)
|
||||
{
|
||||
// The following is MurmurHash3 (x86_32), see http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
|
||||
uint32_t h1 = nHashSeed;
|
||||
const uint32_t c1 = 0xcc9e2d51;
|
||||
const uint32_t c2 = 0x1b873593;
|
||||
|
||||
const int nblocks = vDataToHash.size() / 4;
|
||||
|
||||
//----------
|
||||
// body
|
||||
const uint32_t * blocks = (const uint32_t *)(&vDataToHash[0] + nblocks*4);
|
||||
|
||||
for(int i = -nblocks; i; i++)
|
||||
{
|
||||
uint32_t k1 = blocks[i];
|
||||
|
||||
k1 *= c1;
|
||||
k1 = ROTL32(k1,15);
|
||||
k1 *= c2;
|
||||
|
||||
h1 ^= k1;
|
||||
h1 = ROTL32(h1,13);
|
||||
h1 = h1*5+0xe6546b64;
|
||||
}
|
||||
|
||||
//----------
|
||||
// tail
|
||||
const uint8_t * tail = (const uint8_t*)(&vDataToHash[0] + nblocks*4);
|
||||
|
||||
uint32_t k1 = 0;
|
||||
|
||||
switch(vDataToHash.size() & 3)
|
||||
{
|
||||
case 3: k1 ^= tail[2] << 16;
|
||||
case 2: k1 ^= tail[1] << 8;
|
||||
case 1: k1 ^= tail[0];
|
||||
k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1;
|
||||
};
|
||||
|
||||
//----------
|
||||
// finalization
|
||||
h1 ^= vDataToHash.size();
|
||||
h1 ^= h1 >> 16;
|
||||
h1 *= 0x85ebca6b;
|
||||
h1 ^= h1 >> 13;
|
||||
h1 *= 0xc2b2ae35;
|
||||
h1 ^= h1 >> 16;
|
||||
|
||||
return h1;
|
||||
}
|
16
src/hash.h
16
src/hash.h
|
@ -6,7 +6,6 @@
|
|||
#define BITCOIN_HASH_H
|
||||
|
||||
#include "uint256.h"
|
||||
#include "serialize.h"
|
||||
|
||||
#include <openssl/sha.h>
|
||||
#include <openssl/ripemd.h>
|
||||
|
@ -53,13 +52,6 @@ public:
|
|||
SHA256((unsigned char*)&hash1, sizeof(hash1), (unsigned char*)&hash2);
|
||||
return hash2;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
CHashWriter& operator<<(const T& obj) {
|
||||
// Serialize to this stream
|
||||
::Serialize(*this, obj, nType, nVersion);
|
||||
return (*this);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
@ -97,14 +89,6 @@ inline uint256 Hash(const T1 p1begin, const T1 p1end,
|
|||
return hash2;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
uint256 SerializeHash(const T& obj, int nType=SER_GETHASH, int nVersion=PROTOCOL_VERSION)
|
||||
{
|
||||
CHashWriter ss(nType, nVersion);
|
||||
ss << obj;
|
||||
return ss.GetHash();
|
||||
}
|
||||
|
||||
inline uint160 Hash160(const std::vector<unsigned char>& vch)
|
||||
{
|
||||
uint256 hash1;
|
||||
|
|
1096
src/init.cpp
1096
src/init.cpp
File diff suppressed because it is too large
Load Diff
18
src/init.h
18
src/init.h
|
@ -1,18 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_INIT_H
|
||||
#define BITCOIN_INIT_H
|
||||
|
||||
#include "wallet.h"
|
||||
|
||||
extern CWallet* pwalletMain;
|
||||
|
||||
void StartShutdown();
|
||||
bool ShutdownRequested();
|
||||
void Shutdown();
|
||||
bool AppInit2(boost::thread_group& threadGroup);
|
||||
std::string HelpMessage();
|
||||
|
||||
#endif
|
406
src/key.cpp
406
src/key.cpp
|
@ -1,406 +0,0 @@
|
|||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <map>
|
||||
|
||||
#include <openssl/ecdsa.h>
|
||||
#include <openssl/obj_mac.h>
|
||||
|
||||
#include "key.h"
|
||||
|
||||
// Generate a private key from just the secret parameter
|
||||
int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
|
||||
{
|
||||
int ok = 0;
|
||||
BN_CTX *ctx = NULL;
|
||||
EC_POINT *pub_key = NULL;
|
||||
|
||||
if (!eckey) return 0;
|
||||
|
||||
const EC_GROUP *group = EC_KEY_get0_group(eckey);
|
||||
|
||||
if ((ctx = BN_CTX_new()) == NULL)
|
||||
goto err;
|
||||
|
||||
pub_key = EC_POINT_new(group);
|
||||
|
||||
if (pub_key == NULL)
|
||||
goto err;
|
||||
|
||||
if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
|
||||
goto err;
|
||||
|
||||
EC_KEY_set_private_key(eckey,priv_key);
|
||||
EC_KEY_set_public_key(eckey,pub_key);
|
||||
|
||||
ok = 1;
|
||||
|
||||
err:
|
||||
|
||||
if (pub_key)
|
||||
EC_POINT_free(pub_key);
|
||||
if (ctx != NULL)
|
||||
BN_CTX_free(ctx);
|
||||
|
||||
return(ok);
|
||||
}
|
||||
|
||||
// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
|
||||
// recid selects which key is recovered
|
||||
// if check is non-zero, additional checks are performed
|
||||
int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
|
||||
{
|
||||
if (!eckey) return 0;
|
||||
|
||||
int ret = 0;
|
||||
BN_CTX *ctx = NULL;
|
||||
|
||||
BIGNUM *x = NULL;
|
||||
BIGNUM *e = NULL;
|
||||
BIGNUM *order = NULL;
|
||||
BIGNUM *sor = NULL;
|
||||
BIGNUM *eor = NULL;
|
||||
BIGNUM *field = NULL;
|
||||
EC_POINT *R = NULL;
|
||||
EC_POINT *O = NULL;
|
||||
EC_POINT *Q = NULL;
|
||||
BIGNUM *rr = NULL;
|
||||
BIGNUM *zero = NULL;
|
||||
int n = 0;
|
||||
int i = recid / 2;
|
||||
|
||||
const EC_GROUP *group = EC_KEY_get0_group(eckey);
|
||||
if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
|
||||
BN_CTX_start(ctx);
|
||||
order = BN_CTX_get(ctx);
|
||||
if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
|
||||
x = BN_CTX_get(ctx);
|
||||
if (!BN_copy(x, order)) { ret=-1; goto err; }
|
||||
if (!BN_mul_word(x, i)) { ret=-1; goto err; }
|
||||
if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
|
||||
field = BN_CTX_get(ctx);
|
||||
if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
|
||||
if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
|
||||
if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
|
||||
if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
|
||||
if (check)
|
||||
{
|
||||
if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
|
||||
if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
|
||||
if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
|
||||
}
|
||||
if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
|
||||
n = EC_GROUP_get_degree(group);
|
||||
e = BN_CTX_get(ctx);
|
||||
if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
|
||||
if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
|
||||
zero = BN_CTX_get(ctx);
|
||||
if (!BN_zero(zero)) { ret=-1; goto err; }
|
||||
if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
|
||||
rr = BN_CTX_get(ctx);
|
||||
if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
|
||||
sor = BN_CTX_get(ctx);
|
||||
if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
|
||||
eor = BN_CTX_get(ctx);
|
||||
if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
|
||||
if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
|
||||
if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
|
||||
|
||||
ret = 1;
|
||||
|
||||
err:
|
||||
if (ctx) {
|
||||
BN_CTX_end(ctx);
|
||||
BN_CTX_free(ctx);
|
||||
}
|
||||
if (R != NULL) EC_POINT_free(R);
|
||||
if (O != NULL) EC_POINT_free(O);
|
||||
if (Q != NULL) EC_POINT_free(Q);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void CKey::SetCompressedPubKey(bool fCompressed)
|
||||
{
|
||||
EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
|
||||
fCompressedPubKey = true;
|
||||
}
|
||||
|
||||
void CKey::Reset()
|
||||
{
|
||||
fCompressedPubKey = false;
|
||||
if (pkey != NULL)
|
||||
EC_KEY_free(pkey);
|
||||
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
|
||||
if (pkey == NULL)
|
||||
throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
|
||||
fSet = false;
|
||||
}
|
||||
|
||||
CKey::CKey()
|
||||
{
|
||||
pkey = NULL;
|
||||
Reset();
|
||||
}
|
||||
|
||||
CKey::CKey(const CKey& b)
|
||||
{
|
||||
pkey = EC_KEY_dup(b.pkey);
|
||||
if (pkey == NULL)
|
||||
throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
|
||||
fSet = b.fSet;
|
||||
}
|
||||
|
||||
CKey& CKey::operator=(const CKey& b)
|
||||
{
|
||||
if (!EC_KEY_copy(pkey, b.pkey))
|
||||
throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
|
||||
fSet = b.fSet;
|
||||
return (*this);
|
||||
}
|
||||
|
||||
CKey::~CKey()
|
||||
{
|
||||
EC_KEY_free(pkey);
|
||||
}
|
||||
|
||||
bool CKey::IsNull() const
|
||||
{
|
||||
return !fSet;
|
||||
}
|
||||
|
||||
bool CKey::IsCompressed() const
|
||||
{
|
||||
return fCompressedPubKey;
|
||||
}
|
||||
|
||||
void CKey::MakeNewKey(bool fCompressed)
|
||||
{
|
||||
if (!EC_KEY_generate_key(pkey))
|
||||
throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
|
||||
if (fCompressed)
|
||||
SetCompressedPubKey();
|
||||
fSet = true;
|
||||
}
|
||||
|
||||
bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
|
||||
{
|
||||
const unsigned char* pbegin = &vchPrivKey[0];
|
||||
if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
|
||||
{
|
||||
// In testing, d2i_ECPrivateKey can return true
|
||||
// but fill in pkey with a key that fails
|
||||
// EC_KEY_check_key, so:
|
||||
if (EC_KEY_check_key(pkey))
|
||||
{
|
||||
fSet = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// If vchPrivKey data is bad d2i_ECPrivateKey() can
|
||||
// leave pkey in a state where calling EC_KEY_free()
|
||||
// crashes. To avoid that, set pkey to NULL and
|
||||
// leak the memory (a leak is better than a crash)
|
||||
pkey = NULL;
|
||||
Reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
|
||||
{
|
||||
EC_KEY_free(pkey);
|
||||
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
|
||||
if (pkey == NULL)
|
||||
throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
|
||||
if (vchSecret.size() != 32)
|
||||
throw key_error("CKey::SetSecret() : secret must be 32 bytes");
|
||||
BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
|
||||
if (bn == NULL)
|
||||
throw key_error("CKey::SetSecret() : BN_bin2bn failed");
|
||||
if (!EC_KEY_regenerate_key(pkey,bn))
|
||||
{
|
||||
BN_clear_free(bn);
|
||||
throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
|
||||
}
|
||||
BN_clear_free(bn);
|
||||
fSet = true;
|
||||
if (fCompressed || fCompressedPubKey)
|
||||
SetCompressedPubKey();
|
||||
return true;
|
||||
}
|
||||
|
||||
CSecret CKey::GetSecret(bool &fCompressed) const
|
||||
{
|
||||
CSecret vchRet;
|
||||
vchRet.resize(32);
|
||||
const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
|
||||
int nBytes = BN_num_bytes(bn);
|
||||
if (bn == NULL)
|
||||
throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
|
||||
int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
|
||||
if (n != nBytes)
|
||||
throw key_error("CKey::GetSecret(): BN_bn2bin failed");
|
||||
fCompressed = fCompressedPubKey;
|
||||
return vchRet;
|
||||
}
|
||||
|
||||
CPrivKey CKey::GetPrivKey() const
|
||||
{
|
||||
int nSize = i2d_ECPrivateKey(pkey, NULL);
|
||||
if (!nSize)
|
||||
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
|
||||
CPrivKey vchPrivKey(nSize, 0);
|
||||
unsigned char* pbegin = &vchPrivKey[0];
|
||||
if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
|
||||
throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
|
||||
return vchPrivKey;
|
||||
}
|
||||
|
||||
bool CKey::SetPubKey(const CPubKey& vchPubKey)
|
||||
{
|
||||
const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
|
||||
if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
|
||||
{
|
||||
fSet = true;
|
||||
if (vchPubKey.vchPubKey.size() == 33)
|
||||
SetCompressedPubKey();
|
||||
return true;
|
||||
}
|
||||
pkey = NULL;
|
||||
Reset();
|
||||
return false;
|
||||
}
|
||||
|
||||
CPubKey CKey::GetPubKey() const
|
||||
{
|
||||
int nSize = i2o_ECPublicKey(pkey, NULL);
|
||||
if (!nSize)
|
||||
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
|
||||
std::vector<unsigned char> vchPubKey(nSize, 0);
|
||||
unsigned char* pbegin = &vchPubKey[0];
|
||||
if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
|
||||
throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
|
||||
return CPubKey(vchPubKey);
|
||||
}
|
||||
|
||||
bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
|
||||
{
|
||||
unsigned int nSize = ECDSA_size(pkey);
|
||||
vchSig.resize(nSize); // Make sure it is big enough
|
||||
if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey))
|
||||
{
|
||||
vchSig.clear();
|
||||
return false;
|
||||
}
|
||||
vchSig.resize(nSize); // Shrink to fit actual size
|
||||
return true;
|
||||
}
|
||||
|
||||
// create a compact signature (65 bytes), which allows reconstructing the used public key
|
||||
// The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
|
||||
// The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
|
||||
// 0x1D = second key with even y, 0x1E = second key with odd y
|
||||
bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
|
||||
{
|
||||
bool fOk = false;
|
||||
ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
|
||||
if (sig==NULL)
|
||||
return false;
|
||||
vchSig.clear();
|
||||
vchSig.resize(65,0);
|
||||
int nBitsR = BN_num_bits(sig->r);
|
||||
int nBitsS = BN_num_bits(sig->s);
|
||||
if (nBitsR <= 256 && nBitsS <= 256)
|
||||
{
|
||||
int nRecId = -1;
|
||||
for (int i=0; i<4; i++)
|
||||
{
|
||||
CKey keyRec;
|
||||
keyRec.fSet = true;
|
||||
if (fCompressedPubKey)
|
||||
keyRec.SetCompressedPubKey();
|
||||
if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
|
||||
if (keyRec.GetPubKey() == this->GetPubKey())
|
||||
{
|
||||
nRecId = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (nRecId == -1)
|
||||
throw key_error("CKey::SignCompact() : unable to construct recoverable key");
|
||||
|
||||
vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
|
||||
BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
|
||||
BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
|
||||
fOk = true;
|
||||
}
|
||||
ECDSA_SIG_free(sig);
|
||||
return fOk;
|
||||
}
|
||||
|
||||
// reconstruct public key from a compact signature
|
||||
// This is only slightly more CPU intensive than just verifying it.
|
||||
// If this function succeeds, the recovered public key is guaranteed to be valid
|
||||
// (the signature is a valid signature of the given data for that key)
|
||||
bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
|
||||
{
|
||||
if (vchSig.size() != 65)
|
||||
return false;
|
||||
int nV = vchSig[0];
|
||||
if (nV<27 || nV>=35)
|
||||
return false;
|
||||
ECDSA_SIG *sig = ECDSA_SIG_new();
|
||||
BN_bin2bn(&vchSig[1],32,sig->r);
|
||||
BN_bin2bn(&vchSig[33],32,sig->s);
|
||||
|
||||
EC_KEY_free(pkey);
|
||||
pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
|
||||
if (nV >= 31)
|
||||
{
|
||||
SetCompressedPubKey();
|
||||
nV -= 4;
|
||||
}
|
||||
if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
|
||||
{
|
||||
fSet = true;
|
||||
ECDSA_SIG_free(sig);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
|
||||
{
|
||||
// -1 = error, 0 = bad sig, 1 = good
|
||||
if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
|
||||
{
|
||||
CKey key;
|
||||
if (!key.SetCompactSignature(hash, vchSig))
|
||||
return false;
|
||||
if (GetPubKey() != key.GetPubKey())
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CKey::IsValid()
|
||||
{
|
||||
if (!fSet)
|
||||
return false;
|
||||
|
||||
if (!EC_KEY_check_key(pkey))
|
||||
return false;
|
||||
|
||||
bool fCompr;
|
||||
CSecret secret = GetSecret(fCompr);
|
||||
CKey key2;
|
||||
key2.SetSecret(secret, fCompr);
|
||||
return GetPubKey() == key2.GetPubKey();
|
||||
}
|
221
src/keystore.cpp
221
src/keystore.cpp
|
@ -1,221 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "keystore.h"
|
||||
#include "script.h"
|
||||
|
||||
bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
|
||||
{
|
||||
CKey key;
|
||||
if (!GetKey(address, key))
|
||||
return false;
|
||||
vchPubKeyOut = key.GetPubKey();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBasicKeyStore::AddKey(const CKey& key)
|
||||
{
|
||||
bool fCompressed = false;
|
||||
CSecret secret = key.GetSecret(fCompressed);
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBasicKeyStore::AddCScript(const CScript& redeemScript)
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
mapScripts[redeemScript.GetID()] = redeemScript;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const
|
||||
{
|
||||
bool result;
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
result = (mapScripts.count(hash) > 0);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
ScriptMap::const_iterator mi = mapScripts.find(hash);
|
||||
if (mi != mapScripts.end())
|
||||
{
|
||||
redeemScriptOut = (*mi).second;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::SetCrypted()
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (fUseCrypto)
|
||||
return true;
|
||||
if (!mapKeys.empty())
|
||||
return false;
|
||||
fUseCrypto = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::Lock()
|
||||
{
|
||||
if (!SetCrypted())
|
||||
return false;
|
||||
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
vMasterKey.clear();
|
||||
}
|
||||
|
||||
NotifyStatusChanged(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (!SetCrypted())
|
||||
return false;
|
||||
|
||||
CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
|
||||
for (; mi != mapCryptedKeys.end(); ++mi)
|
||||
{
|
||||
const CPubKey &vchPubKey = (*mi).second.first;
|
||||
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
|
||||
CSecret vchSecret;
|
||||
if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
|
||||
return false;
|
||||
if (vchSecret.size() != 32)
|
||||
return false;
|
||||
CKey key;
|
||||
key.SetPubKey(vchPubKey);
|
||||
key.SetSecret(vchSecret);
|
||||
if (key.GetPubKey() == vchPubKey)
|
||||
break;
|
||||
return false;
|
||||
}
|
||||
vMasterKey = vMasterKeyIn;
|
||||
}
|
||||
NotifyStatusChanged(this);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::AddKey(const CKey& key)
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (!IsCrypted())
|
||||
return CBasicKeyStore::AddKey(key);
|
||||
|
||||
if (IsLocked())
|
||||
return false;
|
||||
|
||||
std::vector<unsigned char> vchCryptedSecret;
|
||||
CPubKey vchPubKey = key.GetPubKey();
|
||||
bool fCompressed;
|
||||
if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
|
||||
return false;
|
||||
|
||||
if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (!SetCrypted())
|
||||
return false;
|
||||
|
||||
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (!IsCrypted())
|
||||
return CBasicKeyStore::GetKey(address, keyOut);
|
||||
|
||||
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
|
||||
if (mi != mapCryptedKeys.end())
|
||||
{
|
||||
const CPubKey &vchPubKey = (*mi).second.first;
|
||||
const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
|
||||
CSecret vchSecret;
|
||||
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
|
||||
return false;
|
||||
if (vchSecret.size() != 32)
|
||||
return false;
|
||||
keyOut.SetPubKey(vchPubKey);
|
||||
keyOut.SetSecret(vchSecret);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (!IsCrypted())
|
||||
return CKeyStore::GetPubKey(address, vchPubKeyOut);
|
||||
|
||||
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
|
||||
if (mi != mapCryptedKeys.end())
|
||||
{
|
||||
vchPubKeyOut = (*mi).second.first;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
|
||||
{
|
||||
{
|
||||
LOCK(cs_KeyStore);
|
||||
if (!mapCryptedKeys.empty() || IsCrypted())
|
||||
return false;
|
||||
|
||||
fUseCrypto = true;
|
||||
BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys)
|
||||
{
|
||||
CKey key;
|
||||
if (!key.SetSecret(mKey.second.first, mKey.second.second))
|
||||
return false;
|
||||
const CPubKey vchPubKey = key.GetPubKey();
|
||||
std::vector<unsigned char> vchCryptedSecret;
|
||||
bool fCompressed;
|
||||
if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret))
|
||||
return false;
|
||||
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
|
||||
return false;
|
||||
}
|
||||
mapKeys.clear();
|
||||
}
|
||||
return true;
|
||||
}
|
|
@ -1,81 +0,0 @@
|
|||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "leveldb.h"
|
||||
#include "util.h"
|
||||
|
||||
#include <leveldb/env.h>
|
||||
#include <leveldb/cache.h>
|
||||
#include <leveldb/filter_policy.h>
|
||||
#include <memenv/memenv.h>
|
||||
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
void HandleError(const leveldb::Status &status) throw(leveldb_error) {
|
||||
if (status.ok())
|
||||
return;
|
||||
if (status.IsCorruption())
|
||||
throw leveldb_error("Database corrupted");
|
||||
if (status.IsIOError())
|
||||
throw leveldb_error("Database I/O error");
|
||||
if (status.IsNotFound())
|
||||
throw leveldb_error("Database entry missing");
|
||||
throw leveldb_error("Unknown database error");
|
||||
}
|
||||
|
||||
static leveldb::Options GetOptions(size_t nCacheSize) {
|
||||
leveldb::Options options;
|
||||
options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
|
||||
options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
|
||||
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
|
||||
options.compression = leveldb::kNoCompression;
|
||||
options.max_open_files = 64;
|
||||
return options;
|
||||
}
|
||||
|
||||
CLevelDB::CLevelDB(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory, bool fWipe) {
|
||||
penv = NULL;
|
||||
readoptions.verify_checksums = true;
|
||||
iteroptions.verify_checksums = true;
|
||||
iteroptions.fill_cache = false;
|
||||
syncoptions.sync = true;
|
||||
options = GetOptions(nCacheSize);
|
||||
options.create_if_missing = true;
|
||||
if (fMemory) {
|
||||
penv = leveldb::NewMemEnv(leveldb::Env::Default());
|
||||
options.env = penv;
|
||||
} else {
|
||||
if (fWipe) {
|
||||
printf("Wiping LevelDB in %s\n", path.string().c_str());
|
||||
leveldb::DestroyDB(path.string(), options);
|
||||
}
|
||||
boost::filesystem::create_directory(path);
|
||||
printf("Opening LevelDB in %s\n", path.string().c_str());
|
||||
}
|
||||
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
|
||||
if (!status.ok())
|
||||
throw std::runtime_error(strprintf("CLevelDB(): error opening database environment %s", status.ToString().c_str()));
|
||||
printf("Opened LevelDB successfully\n");
|
||||
}
|
||||
|
||||
CLevelDB::~CLevelDB() {
|
||||
delete pdb;
|
||||
pdb = NULL;
|
||||
delete options.filter_policy;
|
||||
options.filter_policy = NULL;
|
||||
delete options.block_cache;
|
||||
options.block_cache = NULL;
|
||||
delete penv;
|
||||
options.env = NULL;
|
||||
}
|
||||
|
||||
bool CLevelDB::WriteBatch(CLevelDBBatch &batch, bool fSync) throw(leveldb_error) {
|
||||
leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
|
||||
if (!status.ok()) {
|
||||
printf("LevelDB write failure: %s\n", status.ToString().c_str());
|
||||
HandleError(status);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
153
src/leveldb.h
153
src/leveldb.h
|
@ -1,153 +0,0 @@
|
|||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_LEVELDB_H
|
||||
#define BITCOIN_LEVELDB_H
|
||||
|
||||
#include "serialize.h"
|
||||
|
||||
#include <leveldb/db.h>
|
||||
#include <leveldb/write_batch.h>
|
||||
|
||||
#include <boost/filesystem/path.hpp>
|
||||
|
||||
class leveldb_error : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
leveldb_error(const std::string &msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
void HandleError(const leveldb::Status &status) throw(leveldb_error);
|
||||
|
||||
// Batch of changes queued to be written to a CLevelDB
|
||||
class CLevelDBBatch
|
||||
{
|
||||
friend class CLevelDB;
|
||||
|
||||
private:
|
||||
leveldb::WriteBatch batch;
|
||||
|
||||
public:
|
||||
template<typename K, typename V> void Write(const K& key, const V& value) {
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(ssKey.GetSerializeSize(key));
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(&ssKey[0], ssKey.size());
|
||||
|
||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||
ssValue.reserve(ssValue.GetSerializeSize(value));
|
||||
ssValue << value;
|
||||
leveldb::Slice slValue(&ssValue[0], ssValue.size());
|
||||
|
||||
batch.Put(slKey, slValue);
|
||||
}
|
||||
|
||||
template<typename K> void Erase(const K& key) {
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(ssKey.GetSerializeSize(key));
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(&ssKey[0], ssKey.size());
|
||||
|
||||
batch.Delete(slKey);
|
||||
}
|
||||
};
|
||||
|
||||
class CLevelDB
|
||||
{
|
||||
private:
|
||||
// custom environment this database is using (may be NULL in case of default environment)
|
||||
leveldb::Env *penv;
|
||||
|
||||
// database options used
|
||||
leveldb::Options options;
|
||||
|
||||
// options used when reading from the database
|
||||
leveldb::ReadOptions readoptions;
|
||||
|
||||
// options used when iterating over values of the database
|
||||
leveldb::ReadOptions iteroptions;
|
||||
|
||||
// options used when writing to the database
|
||||
leveldb::WriteOptions writeoptions;
|
||||
|
||||
// options used when sync writing to the database
|
||||
leveldb::WriteOptions syncoptions;
|
||||
|
||||
// the database itself
|
||||
leveldb::DB *pdb;
|
||||
|
||||
public:
|
||||
CLevelDB(const boost::filesystem::path &path, size_t nCacheSize, bool fMemory = false, bool fWipe = false);
|
||||
~CLevelDB();
|
||||
|
||||
template<typename K, typename V> bool Read(const K& key, V& value) throw(leveldb_error) {
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(ssKey.GetSerializeSize(key));
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(&ssKey[0], ssKey.size());
|
||||
|
||||
std::string strValue;
|
||||
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
|
||||
if (!status.ok()) {
|
||||
if (status.IsNotFound())
|
||||
return false;
|
||||
printf("LevelDB read failure: %s\n", status.ToString().c_str());
|
||||
HandleError(status);
|
||||
}
|
||||
try {
|
||||
CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION);
|
||||
ssValue >> value;
|
||||
} catch(std::exception &e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template<typename K, typename V> bool Write(const K& key, const V& value, bool fSync = false) throw(leveldb_error) {
|
||||
CLevelDBBatch batch;
|
||||
batch.Write(key, value);
|
||||
return WriteBatch(batch, fSync);
|
||||
}
|
||||
|
||||
template<typename K> bool Exists(const K& key) throw(leveldb_error) {
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
ssKey.reserve(ssKey.GetSerializeSize(key));
|
||||
ssKey << key;
|
||||
leveldb::Slice slKey(&ssKey[0], ssKey.size());
|
||||
|
||||
std::string strValue;
|
||||
leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
|
||||
if (!status.ok()) {
|
||||
if (status.IsNotFound())
|
||||
return false;
|
||||
printf("LevelDB read failure: %s\n", status.ToString().c_str());
|
||||
HandleError(status);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template<typename K> bool Erase(const K& key, bool fSync = false) throw(leveldb_error) {
|
||||
CLevelDBBatch batch;
|
||||
batch.Erase(key);
|
||||
return WriteBatch(batch, fSync);
|
||||
}
|
||||
|
||||
bool WriteBatch(CLevelDBBatch &batch, bool fSync = false) throw(leveldb_error);
|
||||
|
||||
// not available for LevelDB; provide for compatibility with BDB
|
||||
bool Flush() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Sync() throw(leveldb_error) {
|
||||
CLevelDBBatch batch;
|
||||
return WriteBatch(batch, true);
|
||||
}
|
||||
|
||||
// not exactly clean encapsulation, but it's easiest for now
|
||||
leveldb::Iterator *NewIterator() {
|
||||
return pdb->NewIterator(iteroptions);
|
||||
}
|
||||
};
|
||||
|
||||
#endif // BITCOIN_LEVELDB_H
|
5004
src/main.cpp
5004
src/main.cpp
File diff suppressed because it is too large
Load Diff
1934
src/main.h
1934
src/main.h
File diff suppressed because it is too large
Load Diff
|
@ -11,8 +11,7 @@
|
|||
#include <map>
|
||||
|
||||
#include "prime.h"
|
||||
#include "serialize.h"
|
||||
#include "bitcoinrpc.h"
|
||||
//#include "bitcoinrpc.h"
|
||||
#include "json/json_spirit_value.h"
|
||||
#include <boost/thread.hpp>
|
||||
#include <boost/asio.hpp>
|
||||
|
@ -24,15 +23,6 @@
|
|||
|
||||
#define MAX_THREADS 32
|
||||
|
||||
// <START> be compatible to original code (not actually used!)
|
||||
#include "txdb.h"
|
||||
#include "ui_interface.h"
|
||||
CClientUIInterface uiInterface;
|
||||
void StartShutdown() {
|
||||
exit(0);
|
||||
}
|
||||
// </END>
|
||||
|
||||
/*********************************
|
||||
* global variables, structs and extern functions
|
||||
*********************************/
|
||||
|
|
|
@ -81,47 +81,13 @@ LIBS+= \
|
|||
-l pthread
|
||||
|
||||
|
||||
# Hardening
|
||||
# Make some classes of vulnerabilities unexploitable in case one is discovered.
|
||||
#
|
||||
# This is a workaround for Ubuntu bug #691722, the default -fstack-protector causes
|
||||
# -fstack-protector-all to be ignored unless -fno-stack-protector is used first.
|
||||
# see: https://bugs.launchpad.net/ubuntu/+source/gcc-4.5/+bug/691722
|
||||
HARDENING=-fno-stack-protector
|
||||
|
||||
# Stack Canaries
|
||||
# Put numbers at the beginning of each stack frame and check that they are the same.
|
||||
# If a stack buffer if overflowed, it writes over the canary number and then on return
|
||||
# when that number is checked, it won't be the same and the program will exit with
|
||||
# a "Stack smashing detected" error instead of being exploited.
|
||||
HARDENING+=-fstack-protector-all -Wstack-protector
|
||||
|
||||
# Make some important things such as the global offset table read only as soon as
|
||||
# the dynamic linker is finished building it. This will prevent overwriting of addresses
|
||||
# which would later be jumped to.
|
||||
LDHARDENING+=-Wl,-z,relro -Wl,-z,now
|
||||
|
||||
# Build position independent code to take advantage of Address Space Layout Randomization
|
||||
# offered by some kernels.
|
||||
# see doc/build-unix.txt for more information.
|
||||
ifdef PIE
|
||||
HARDENING+=-fPIE
|
||||
LDHARDENING+=-pie
|
||||
endif
|
||||
|
||||
# -D_FORTIFY_SOURCE=2 does some checking for potentially exploitable code patterns in
|
||||
# the source such overflowing a statically defined buffer.
|
||||
HARDENING+=-D_FORTIFY_SOURCE=2
|
||||
#
|
||||
|
||||
|
||||
#DEBUGFLAGS=-g3 -fno-inline -O0
|
||||
DEBUGFLAGS=
|
||||
|
||||
# CXXFLAGS can be specified on the make command line, so we use xCXXFLAGS that only
|
||||
# adds some defaults in front. Unfortunately, CXXFLAGS=... $(CXXFLAGS) does not work.
|
||||
xCXXFLAGS=-O2 -pthread -Wall -Wextra -Wformat -Wformat-security -Wno-unused-parameter \
|
||||
$(DEBUGFLAGS) $(DEFS) $(HARDENING) $(CXXFLAGS) -march=native
|
||||
$(DEBUGFLAGS) $(DEFS) $(CXXFLAGS) -march=native
|
||||
|
||||
# LDFLAGS can be specified on the make command line, so we use xLDFLAGS that only
|
||||
# adds some defaults in front. Unfortunately, LDFLAGS=... $(LDFLAGS) does not work.
|
||||
|
|
64
src/mruset.h
64
src/mruset.h
|
@ -1,64 +0,0 @@
|
|||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_MRUSET_H
|
||||
#define BITCOIN_MRUSET_H
|
||||
|
||||
#include <set>
|
||||
#include <deque>
|
||||
|
||||
/** STL-like set container that only keeps the most recent N elements. */
|
||||
template <typename T> class mruset
|
||||
{
|
||||
public:
|
||||
typedef T key_type;
|
||||
typedef T value_type;
|
||||
typedef typename std::set<T>::iterator iterator;
|
||||
typedef typename std::set<T>::const_iterator const_iterator;
|
||||
typedef typename std::set<T>::size_type size_type;
|
||||
|
||||
protected:
|
||||
std::set<T> set;
|
||||
std::deque<T> queue;
|
||||
size_type nMaxSize;
|
||||
|
||||
public:
|
||||
mruset(size_type nMaxSizeIn = 0) { nMaxSize = nMaxSizeIn; }
|
||||
iterator begin() const { return set.begin(); }
|
||||
iterator end() const { return set.end(); }
|
||||
size_type size() const { return set.size(); }
|
||||
bool empty() const { return set.empty(); }
|
||||
iterator find(const key_type& k) const { return set.find(k); }
|
||||
size_type count(const key_type& k) const { return set.count(k); }
|
||||
bool inline friend operator==(const mruset<T>& a, const mruset<T>& b) { return a.set == b.set; }
|
||||
bool inline friend operator==(const mruset<T>& a, const std::set<T>& b) { return a.set == b; }
|
||||
bool inline friend operator<(const mruset<T>& a, const mruset<T>& b) { return a.set < b.set; }
|
||||
std::pair<iterator, bool> insert(const key_type& x)
|
||||
{
|
||||
std::pair<iterator, bool> ret = set.insert(x);
|
||||
if (ret.second)
|
||||
{
|
||||
if (nMaxSize && queue.size() == nMaxSize)
|
||||
{
|
||||
set.erase(queue.front());
|
||||
queue.pop_front();
|
||||
}
|
||||
queue.push_back(x);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
size_type max_size() const { return nMaxSize; }
|
||||
size_type max_size(size_type s)
|
||||
{
|
||||
if (s)
|
||||
while (queue.size() > s)
|
||||
{
|
||||
set.erase(queue.front());
|
||||
queue.pop_front();
|
||||
}
|
||||
nMaxSize = s;
|
||||
return nMaxSize;
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
1893
src/net.cpp
1893
src/net.cpp
File diff suppressed because it is too large
Load Diff
639
src/net.h
639
src/net.h
|
@ -1,639 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_NET_H
|
||||
#define BITCOIN_NET_H
|
||||
|
||||
#include <deque>
|
||||
#include <boost/array.hpp>
|
||||
#include <boost/foreach.hpp>
|
||||
#include <openssl/rand.h>
|
||||
|
||||
#ifndef WIN32
|
||||
#include <arpa/inet.h>
|
||||
#endif
|
||||
|
||||
#include "mruset.h"
|
||||
#include "limitedmap.h"
|
||||
#include "netbase.h"
|
||||
#include "protocol.h"
|
||||
#include "addrman.h"
|
||||
#include "hash.h"
|
||||
#include "bloom.h"
|
||||
|
||||
class CNode;
|
||||
class CBlockIndex;
|
||||
extern int nBestHeight;
|
||||
|
||||
|
||||
|
||||
inline unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
|
||||
inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
|
||||
|
||||
void AddOneShot(std::string strDest);
|
||||
bool RecvLine(SOCKET hSocket, std::string& strLine);
|
||||
bool GetMyExternalIP(CNetAddr& ipRet);
|
||||
void AddressCurrentlyConnected(const CService& addr);
|
||||
CNode* FindNode(const CNetAddr& ip);
|
||||
CNode* FindNode(const CService& ip);
|
||||
CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL);
|
||||
void MapPort(bool fUseUPnP);
|
||||
unsigned short GetListenPort();
|
||||
bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
|
||||
void StartNode(boost::thread_group& threadGroup);
|
||||
bool StopNode();
|
||||
void SocketSendData(CNode *pnode);
|
||||
|
||||
enum
|
||||
{
|
||||
LOCAL_NONE, // unknown
|
||||
LOCAL_IF, // address a local interface listens on
|
||||
LOCAL_BIND, // address explicit bound to
|
||||
LOCAL_UPNP, // address reported by UPnP
|
||||
LOCAL_HTTP, // address reported by whatismyip.com and similar
|
||||
LOCAL_MANUAL, // address explicitly specified (-externalip=)
|
||||
|
||||
LOCAL_MAX
|
||||
};
|
||||
|
||||
void SetLimited(enum Network net, bool fLimited = true);
|
||||
bool IsLimited(enum Network net);
|
||||
bool IsLimited(const CNetAddr& addr);
|
||||
bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
|
||||
bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
|
||||
bool SeenLocal(const CService& addr);
|
||||
bool IsLocal(const CService& addr);
|
||||
bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
|
||||
bool IsReachable(const CNetAddr &addr);
|
||||
void SetReachable(enum Network net, bool fFlag = true);
|
||||
CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
|
||||
|
||||
|
||||
extern bool fDiscover;
|
||||
extern uint64 nLocalServices;
|
||||
extern uint64 nLocalHostNonce;
|
||||
extern CAddrMan addrman;
|
||||
extern int nMaxConnections;
|
||||
|
||||
extern std::vector<CNode*> vNodes;
|
||||
extern CCriticalSection cs_vNodes;
|
||||
extern std::map<CInv, CDataStream> mapRelay;
|
||||
extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
|
||||
extern CCriticalSection cs_mapRelay;
|
||||
extern limitedmap<CInv, int64> mapAlreadyAskedFor;
|
||||
|
||||
extern std::vector<std::string> vAddedNodes;
|
||||
extern CCriticalSection cs_vAddedNodes;
|
||||
|
||||
|
||||
|
||||
|
||||
class CNodeStats
|
||||
{
|
||||
public:
|
||||
uint64 nServices;
|
||||
int64 nLastSend;
|
||||
int64 nLastRecv;
|
||||
int64 nTimeConnected;
|
||||
std::string addrName;
|
||||
int nVersion;
|
||||
std::string strSubVer;
|
||||
bool fInbound;
|
||||
int nStartingHeight;
|
||||
int nMisbehavior;
|
||||
uint64 nSendBytes;
|
||||
uint64 nRecvBytes;
|
||||
bool fSyncNode;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
class CNetMessage {
|
||||
public:
|
||||
bool in_data; // parsing header (false) or data (true)
|
||||
|
||||
CDataStream hdrbuf; // partially received header
|
||||
CMessageHeader hdr; // complete header
|
||||
unsigned int nHdrPos;
|
||||
|
||||
CDataStream vRecv; // received message data
|
||||
unsigned int nDataPos;
|
||||
|
||||
CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
|
||||
hdrbuf.resize(24);
|
||||
in_data = false;
|
||||
nHdrPos = 0;
|
||||
nDataPos = 0;
|
||||
}
|
||||
|
||||
bool complete() const
|
||||
{
|
||||
if (!in_data)
|
||||
return false;
|
||||
return (hdr.nMessageSize == nDataPos);
|
||||
}
|
||||
|
||||
void SetVersion(int nVersionIn)
|
||||
{
|
||||
hdrbuf.SetVersion(nVersionIn);
|
||||
vRecv.SetVersion(nVersionIn);
|
||||
}
|
||||
|
||||
int readHeader(const char *pch, unsigned int nBytes);
|
||||
int readData(const char *pch, unsigned int nBytes);
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/** Information about a peer */
|
||||
class CNode
|
||||
{
|
||||
public:
|
||||
// socket
|
||||
uint64 nServices;
|
||||
SOCKET hSocket;
|
||||
CDataStream ssSend;
|
||||
size_t nSendSize; // total size of all vSendMsg entries
|
||||
size_t nSendOffset; // offset inside the first vSendMsg already sent
|
||||
uint64 nSendBytes;
|
||||
std::deque<CSerializeData> vSendMsg;
|
||||
CCriticalSection cs_vSend;
|
||||
|
||||
std::deque<CInv> vRecvGetData;
|
||||
std::deque<CNetMessage> vRecvMsg;
|
||||
CCriticalSection cs_vRecvMsg;
|
||||
uint64 nRecvBytes;
|
||||
int nRecvVersion;
|
||||
|
||||
int64 nLastSend;
|
||||
int64 nLastRecv;
|
||||
int64 nLastSendEmpty;
|
||||
int64 nTimeConnected;
|
||||
CAddress addr;
|
||||
std::string addrName;
|
||||
CService addrLocal;
|
||||
int nVersion;
|
||||
std::string strSubVer;
|
||||
bool fOneShot;
|
||||
bool fClient;
|
||||
bool fInbound;
|
||||
bool fNetworkNode;
|
||||
bool fSuccessfullyConnected;
|
||||
bool fDisconnect;
|
||||
// We use fRelayTxes for two purposes -
|
||||
// a) it allows us to not relay tx invs before receiving the peer's version message
|
||||
// b) the peer may tell us in their version message that we should not relay tx invs
|
||||
// until they have initialized their bloom filter.
|
||||
bool fRelayTxes;
|
||||
CSemaphoreGrant grantOutbound;
|
||||
CCriticalSection cs_filter;
|
||||
CBloomFilter* pfilter;
|
||||
int nRefCount;
|
||||
protected:
|
||||
|
||||
// Denial-of-service detection/prevention
|
||||
// Key is IP address, value is banned-until-time
|
||||
static std::map<CNetAddr, int64> setBanned;
|
||||
static CCriticalSection cs_setBanned;
|
||||
int nMisbehavior;
|
||||
|
||||
public:
|
||||
uint256 hashContinue;
|
||||
CBlockIndex* pindexLastGetBlocksBegin;
|
||||
uint256 hashLastGetBlocksEnd;
|
||||
int nStartingHeight;
|
||||
bool fStartSync;
|
||||
|
||||
// flood relay
|
||||
std::vector<CAddress> vAddrToSend;
|
||||
std::set<CAddress> setAddrKnown;
|
||||
bool fGetAddr;
|
||||
std::set<uint256> setKnown;
|
||||
uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
|
||||
|
||||
// inventory based relay
|
||||
mruset<CInv> setInventoryKnown;
|
||||
std::vector<CInv> vInventoryToSend;
|
||||
CCriticalSection cs_inventory;
|
||||
std::multimap<int64, CInv> mapAskFor;
|
||||
|
||||
CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : ssSend(SER_NETWORK, MIN_PROTO_VERSION)
|
||||
{
|
||||
nServices = 0;
|
||||
hSocket = hSocketIn;
|
||||
nRecvVersion = MIN_PROTO_VERSION;
|
||||
nLastSend = 0;
|
||||
nLastRecv = 0;
|
||||
nSendBytes = 0;
|
||||
nRecvBytes = 0;
|
||||
nLastSendEmpty = GetTime();
|
||||
nTimeConnected = GetTime();
|
||||
addr = addrIn;
|
||||
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
|
||||
nVersion = 0;
|
||||
strSubVer = "";
|
||||
fOneShot = false;
|
||||
fClient = false; // set by version message
|
||||
fInbound = fInboundIn;
|
||||
fNetworkNode = false;
|
||||
fSuccessfullyConnected = false;
|
||||
fDisconnect = false;
|
||||
nRefCount = 0;
|
||||
nSendSize = 0;
|
||||
nSendOffset = 0;
|
||||
hashContinue = 0;
|
||||
pindexLastGetBlocksBegin = 0;
|
||||
hashLastGetBlocksEnd = 0;
|
||||
nStartingHeight = -1;
|
||||
fStartSync = false;
|
||||
fGetAddr = false;
|
||||
nMisbehavior = 0;
|
||||
hashCheckpointKnown = 0;
|
||||
fRelayTxes = false;
|
||||
setInventoryKnown.max_size(SendBufferSize() / 1000);
|
||||
pfilter = NULL;
|
||||
|
||||
// Be shy and don't send version until we hear
|
||||
if (hSocket != INVALID_SOCKET && !fInbound)
|
||||
PushVersion();
|
||||
}
|
||||
|
||||
~CNode()
|
||||
{
|
||||
if (hSocket != INVALID_SOCKET)
|
||||
{
|
||||
closesocket(hSocket);
|
||||
hSocket = INVALID_SOCKET;
|
||||
}
|
||||
if (pfilter)
|
||||
delete pfilter;
|
||||
}
|
||||
|
||||
private:
|
||||
CNode(const CNode&);
|
||||
void operator=(const CNode&);
|
||||
public:
|
||||
|
||||
|
||||
int GetRefCount()
|
||||
{
|
||||
assert(nRefCount >= 0);
|
||||
return nRefCount;
|
||||
}
|
||||
|
||||
// requires LOCK(cs_vRecvMsg)
|
||||
unsigned int GetTotalRecvSize()
|
||||
{
|
||||
unsigned int total = 0;
|
||||
BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
|
||||
total += msg.vRecv.size() + 24;
|
||||
return total;
|
||||
}
|
||||
|
||||
// requires LOCK(cs_vRecvMsg)
|
||||
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
|
||||
|
||||
// requires LOCK(cs_vRecvMsg)
|
||||
void SetRecvVersion(int nVersionIn)
|
||||
{
|
||||
nRecvVersion = nVersionIn;
|
||||
BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
|
||||
msg.SetVersion(nVersionIn);
|
||||
}
|
||||
|
||||
CNode* AddRef()
|
||||
{
|
||||
nRefCount++;
|
||||
return this;
|
||||
}
|
||||
|
||||
void Release()
|
||||
{
|
||||
nRefCount--;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void AddAddressKnown(const CAddress& addr)
|
||||
{
|
||||
setAddrKnown.insert(addr);
|
||||
}
|
||||
|
||||
void PushAddress(const CAddress& addr)
|
||||
{
|
||||
// Known checking here is only to save space from duplicates.
|
||||
// SendMessages will filter it again for knowns that were added
|
||||
// after addresses were pushed.
|
||||
if (addr.IsValid() && !setAddrKnown.count(addr))
|
||||
vAddrToSend.push_back(addr);
|
||||
}
|
||||
|
||||
|
||||
void AddInventoryKnown(const CInv& inv)
|
||||
{
|
||||
{
|
||||
LOCK(cs_inventory);
|
||||
setInventoryKnown.insert(inv);
|
||||
}
|
||||
}
|
||||
|
||||
void PushInventory(const CInv& inv)
|
||||
{
|
||||
{
|
||||
LOCK(cs_inventory);
|
||||
if (!setInventoryKnown.count(inv))
|
||||
vInventoryToSend.push_back(inv);
|
||||
}
|
||||
}
|
||||
|
||||
void AskFor(const CInv& inv)
|
||||
{
|
||||
// We're using mapAskFor as a priority queue,
|
||||
// the key is the earliest time the request can be sent
|
||||
int64 nRequestTime;
|
||||
limitedmap<CInv, int64>::const_iterator it = mapAlreadyAskedFor.find(inv);
|
||||
if (it != mapAlreadyAskedFor.end())
|
||||
nRequestTime = it->second;
|
||||
else
|
||||
nRequestTime = 0;
|
||||
if (fDebugNet)
|
||||
printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
|
||||
|
||||
// Make sure not to reuse time indexes to keep things in the same order
|
||||
int64 nNow = (GetTime() - 1) * 1000000;
|
||||
static int64 nLastTime;
|
||||
++nLastTime;
|
||||
nNow = std::max(nNow, nLastTime);
|
||||
nLastTime = nNow;
|
||||
|
||||
// Each retry is 2 minutes after the last
|
||||
nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
|
||||
if (it != mapAlreadyAskedFor.end())
|
||||
mapAlreadyAskedFor.update(it, nRequestTime);
|
||||
else
|
||||
mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
|
||||
mapAskFor.insert(std::make_pair(nRequestTime, inv));
|
||||
}
|
||||
|
||||
|
||||
|
||||
// TODO: Document the postcondition of this function. Is cs_vSend locked?
|
||||
void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
|
||||
{
|
||||
ENTER_CRITICAL_SECTION(cs_vSend);
|
||||
assert(ssSend.size() == 0);
|
||||
ssSend << CMessageHeader(pszCommand, 0);
|
||||
if (fDebug)
|
||||
printf("sending: %s ", pszCommand);
|
||||
}
|
||||
|
||||
// TODO: Document the precondition of this function. Is cs_vSend locked?
|
||||
void AbortMessage() UNLOCK_FUNCTION(cs_vSend)
|
||||
{
|
||||
ssSend.clear();
|
||||
|
||||
LEAVE_CRITICAL_SECTION(cs_vSend);
|
||||
|
||||
if (fDebug)
|
||||
printf("(aborted)\n");
|
||||
}
|
||||
|
||||
// TODO: Document the precondition of this function. Is cs_vSend locked?
|
||||
void EndMessage() UNLOCK_FUNCTION(cs_vSend)
|
||||
{
|
||||
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
|
||||
{
|
||||
printf("dropmessages DROPPING SEND MESSAGE\n");
|
||||
AbortMessage();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ssSend.size() == 0)
|
||||
return;
|
||||
|
||||
// Set the size
|
||||
unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
|
||||
memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
|
||||
|
||||
// Set the checksum
|
||||
uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
|
||||
unsigned int nChecksum = 0;
|
||||
memcpy(&nChecksum, &hash, sizeof(nChecksum));
|
||||
assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
|
||||
memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
|
||||
|
||||
if (fDebug) {
|
||||
printf("(%d bytes)\n", nSize);
|
||||
}
|
||||
|
||||
std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
|
||||
ssSend.GetAndClear(*it);
|
||||
nSendSize += (*it).size();
|
||||
|
||||
// If write queue empty, attempt "optimistic write"
|
||||
if (it == vSendMsg.begin())
|
||||
SocketSendData(this);
|
||||
|
||||
LEAVE_CRITICAL_SECTION(cs_vSend);
|
||||
}
|
||||
|
||||
void PushVersion();
|
||||
|
||||
|
||||
void PushMessage(const char* pszCommand)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1>
|
||||
void PushMessage(const char* pszCommand, const T1& a1)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3, typename T4>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3 << a4;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3, typename T4, typename T5>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3 << a4 << a5;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3 << a4 << a5 << a6;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
|
||||
void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9)
|
||||
{
|
||||
try
|
||||
{
|
||||
BeginMessage(pszCommand);
|
||||
ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
|
||||
EndMessage();
|
||||
}
|
||||
catch (...)
|
||||
{
|
||||
AbortMessage();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
|
||||
bool IsSubscribed(unsigned int nChannel);
|
||||
void Subscribe(unsigned int nChannel, unsigned int nHops=0);
|
||||
void CancelSubscribe(unsigned int nChannel);
|
||||
void CloseSocketDisconnect();
|
||||
void Cleanup();
|
||||
|
||||
|
||||
// Denial-of-service detection/prevention
|
||||
// The idea is to detect peers that are behaving
|
||||
// badly and disconnect/ban them, but do it in a
|
||||
// one-coding-mistake-won't-shatter-the-entire-network
|
||||
// way.
|
||||
// IMPORTANT: There should be nothing I can give a
|
||||
// node that it will forward on that will make that
|
||||
// node's peers drop it. If there is, an attacker
|
||||
// can isolate a node and/or try to split the network.
|
||||
// Dropping a node for sending stuff that is invalid
|
||||
// now but might be valid in a later version is also
|
||||
// dangerous, because it can cause a network split
|
||||
// between nodes running old code and nodes running
|
||||
// new code.
|
||||
static void ClearBanned(); // needed for unit testing
|
||||
static bool IsBanned(CNetAddr ip);
|
||||
bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
|
||||
void copyStats(CNodeStats &stats);
|
||||
};
|
||||
|
||||
|
||||
|
||||
class CTransaction;
|
||||
void RelayTransaction(const CTransaction& tx, const uint256& hash);
|
||||
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
|
||||
|
||||
#endif
|
|
@ -7,7 +7,6 @@
|
|||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "serialize.h"
|
||||
#include "compat.h"
|
||||
|
||||
extern int nConnectTimeout;
|
||||
|
@ -79,11 +78,6 @@ class CNetAddr
|
|||
friend bool operator==(const CNetAddr& a, const CNetAddr& b);
|
||||
friend bool operator!=(const CNetAddr& a, const CNetAddr& b);
|
||||
friend bool operator<(const CNetAddr& a, const CNetAddr& b);
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(FLATDATA(ip));
|
||||
)
|
||||
};
|
||||
|
||||
/** A combination of a network address (CNetAddr) and a (TCP) port */
|
||||
|
@ -120,15 +114,6 @@ class CService : public CNetAddr
|
|||
CService(const struct sockaddr_in6& addr);
|
||||
#endif
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
CService* pthis = const_cast<CService*>(this);
|
||||
READWRITE(FLATDATA(ip));
|
||||
unsigned short portN = htons(port);
|
||||
READWRITE(portN);
|
||||
if (fRead)
|
||||
pthis->port = ntohs(portN);
|
||||
)
|
||||
};
|
||||
|
||||
typedef std::pair<CService, int> proxyType;
|
||||
|
|
51
src/noui.cpp
51
src/noui.cpp
|
@ -1,51 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "ui_interface.h"
|
||||
#include "init.h"
|
||||
#include "bitcoinrpc.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
|
||||
{
|
||||
std::string strCaption;
|
||||
// Check for usage of predefined caption
|
||||
switch (style) {
|
||||
case CClientUIInterface::MSG_ERROR:
|
||||
strCaption += _("Error");
|
||||
break;
|
||||
case CClientUIInterface::MSG_WARNING:
|
||||
strCaption += _("Warning");
|
||||
break;
|
||||
case CClientUIInterface::MSG_INFORMATION:
|
||||
strCaption += _("Information");
|
||||
break;
|
||||
default:
|
||||
strCaption += caption; // Use supplied caption (can be empty)
|
||||
}
|
||||
|
||||
printf("%s: %s\n", strCaption.c_str(), message.c_str());
|
||||
fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool noui_ThreadSafeAskFee(int64 /*nFeeRequired*/)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
static void noui_InitMessage(const std::string &message)
|
||||
{
|
||||
printf("init message: %s\n", message.c_str());
|
||||
}
|
||||
|
||||
void noui_connect()
|
||||
{
|
||||
// Connect bitcoind signal handlers
|
||||
uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox);
|
||||
uiInterface.ThreadSafeAskFee.connect(noui_ThreadSafeAskFee);
|
||||
uiInterface.InitMessage.connect(noui_InitMessage);
|
||||
}
|
|
@ -3,6 +3,7 @@
|
|||
// see the accompanying file COPYING
|
||||
|
||||
#include "prime.h"
|
||||
#include <boost/foreach.hpp>
|
||||
#include <climits>
|
||||
|
||||
/**********************/
|
||||
|
@ -792,7 +793,7 @@ bool MineProbablePrimeChain(CBlock& block, mpz_class& mpzFixedMultiplier, bool&
|
|||
bnPrimeChainMultiplier.SetHex(mpzPrimeChainMultiplier.get_str(16));
|
||||
block.bnPrimeChainMultiplier = bnPrimeChainMultiplier;
|
||||
//printf("nTriedMultiplier = %u\n", nTriedMultiplier); // Debugging
|
||||
printf("Probable prime chain found for block=%s!!\n Target: %s\n Chain: %s\n", block.GetHash().GetHex().c_str(),
|
||||
printf("Probable prime chain found\n Target: %s\n Chain: %s\n",
|
||||
TargetToString(block.nBits).c_str(), GetPrimeChainName(nCandidateType, nChainLength).c_str());
|
||||
nProbableChainLength = nChainLength;
|
||||
return true;
|
||||
|
|
152
src/protocol.cpp
152
src/protocol.cpp
|
@ -1,152 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "protocol.h"
|
||||
#include "util.h"
|
||||
#include "netbase.h"
|
||||
#include "main.h"
|
||||
|
||||
#ifndef WIN32
|
||||
# include <arpa/inet.h>
|
||||
#endif
|
||||
|
||||
static const char* ppszTypeName[] =
|
||||
{
|
||||
"ERROR",
|
||||
"tx",
|
||||
"block",
|
||||
"filtered block"
|
||||
};
|
||||
|
||||
CMessageHeader::CMessageHeader()
|
||||
{
|
||||
memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
|
||||
memset(pchCommand, 0, sizeof(pchCommand));
|
||||
pchCommand[1] = 1;
|
||||
nMessageSize = -1;
|
||||
nChecksum = 0;
|
||||
}
|
||||
|
||||
CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
|
||||
{
|
||||
memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
|
||||
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
|
||||
nMessageSize = nMessageSizeIn;
|
||||
nChecksum = 0;
|
||||
}
|
||||
|
||||
std::string CMessageHeader::GetCommand() const
|
||||
{
|
||||
if (pchCommand[COMMAND_SIZE-1] == 0)
|
||||
return std::string(pchCommand, pchCommand + strlen(pchCommand));
|
||||
else
|
||||
return std::string(pchCommand, pchCommand + COMMAND_SIZE);
|
||||
}
|
||||
|
||||
bool CMessageHeader::IsValid() const
|
||||
{
|
||||
// Check start string
|
||||
if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
|
||||
return false;
|
||||
|
||||
// Check the command string for errors
|
||||
for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
|
||||
{
|
||||
if (*p1 == 0)
|
||||
{
|
||||
// Must be all zeros after the first zero
|
||||
for (; p1 < pchCommand + COMMAND_SIZE; p1++)
|
||||
if (*p1 != 0)
|
||||
return false;
|
||||
}
|
||||
else if (*p1 < ' ' || *p1 > 0x7E)
|
||||
return false;
|
||||
}
|
||||
|
||||
// Message size
|
||||
if (nMessageSize > MAX_SIZE)
|
||||
{
|
||||
printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
CAddress::CAddress() : CService()
|
||||
{
|
||||
Init();
|
||||
}
|
||||
|
||||
CAddress::CAddress(CService ipIn, uint64 nServicesIn) : CService(ipIn)
|
||||
{
|
||||
Init();
|
||||
nServices = nServicesIn;
|
||||
}
|
||||
|
||||
void CAddress::Init()
|
||||
{
|
||||
nServices = NODE_NETWORK;
|
||||
nTime = 100000000;
|
||||
nLastTry = 0;
|
||||
}
|
||||
|
||||
CInv::CInv()
|
||||
{
|
||||
type = 0;
|
||||
hash = 0;
|
||||
}
|
||||
|
||||
CInv::CInv(int typeIn, const uint256& hashIn)
|
||||
{
|
||||
type = typeIn;
|
||||
hash = hashIn;
|
||||
}
|
||||
|
||||
CInv::CInv(const std::string& strType, const uint256& hashIn)
|
||||
{
|
||||
unsigned int i;
|
||||
for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
|
||||
{
|
||||
if (strType == ppszTypeName[i])
|
||||
{
|
||||
type = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (i == ARRAYLEN(ppszTypeName))
|
||||
throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
|
||||
hash = hashIn;
|
||||
}
|
||||
|
||||
bool operator<(const CInv& a, const CInv& b)
|
||||
{
|
||||
return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
|
||||
}
|
||||
|
||||
bool CInv::IsKnownType() const
|
||||
{
|
||||
return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));
|
||||
}
|
||||
|
||||
const char* CInv::GetCommand() const
|
||||
{
|
||||
if (!IsKnownType())
|
||||
throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
|
||||
return ppszTypeName[type];
|
||||
}
|
||||
|
||||
std::string CInv::ToString() const
|
||||
{
|
||||
return strprintf("%s %s", GetCommand(), hash.ToString().c_str());
|
||||
}
|
||||
|
||||
void CInv::print() const
|
||||
{
|
||||
printf("CInv(%s)\n", ToString().c_str());
|
||||
}
|
||||
|
154
src/protocol.h
154
src/protocol.h
|
@ -1,154 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#ifndef __cplusplus
|
||||
# error This header can only be compiled as C++.
|
||||
#endif
|
||||
|
||||
#ifndef __INCLUDED_PROTOCOL_H__
|
||||
#define __INCLUDED_PROTOCOL_H__
|
||||
|
||||
#include "serialize.h"
|
||||
#include "netbase.h"
|
||||
#include <string>
|
||||
#include "uint256.h"
|
||||
|
||||
#define PRIMECOIN_PORT 9911
|
||||
#define RPC_PORT 9912
|
||||
#define TESTNET_PORT 9913
|
||||
#define TESTNET_RPC_PORT 9914
|
||||
|
||||
extern bool fTestNet;
|
||||
|
||||
static inline unsigned short GetDefaultPort(const bool testnet = fTestNet)
|
||||
{
|
||||
return testnet ? TESTNET_PORT : PRIMECOIN_PORT;
|
||||
}
|
||||
|
||||
|
||||
extern unsigned char pchMessageStart[4];
|
||||
|
||||
/** Message header.
|
||||
* (4) message start.
|
||||
* (12) command.
|
||||
* (4) size.
|
||||
* (4) checksum.
|
||||
*/
|
||||
class CMessageHeader
|
||||
{
|
||||
public:
|
||||
CMessageHeader();
|
||||
CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn);
|
||||
|
||||
std::string GetCommand() const;
|
||||
bool IsValid() const;
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(FLATDATA(pchMessageStart));
|
||||
READWRITE(FLATDATA(pchCommand));
|
||||
READWRITE(nMessageSize);
|
||||
READWRITE(nChecksum);
|
||||
)
|
||||
|
||||
// TODO: make private (improves encapsulation)
|
||||
public:
|
||||
enum {
|
||||
MESSAGE_START_SIZE=sizeof(::pchMessageStart),
|
||||
COMMAND_SIZE=12,
|
||||
MESSAGE_SIZE_SIZE=sizeof(int),
|
||||
CHECKSUM_SIZE=sizeof(int),
|
||||
|
||||
MESSAGE_SIZE_OFFSET=MESSAGE_START_SIZE+COMMAND_SIZE,
|
||||
CHECKSUM_OFFSET=MESSAGE_SIZE_OFFSET+MESSAGE_SIZE_SIZE,
|
||||
HEADER_SIZE=MESSAGE_START_SIZE+COMMAND_SIZE+MESSAGE_SIZE_SIZE+CHECKSUM_SIZE
|
||||
};
|
||||
char pchMessageStart[MESSAGE_START_SIZE];
|
||||
char pchCommand[COMMAND_SIZE];
|
||||
unsigned int nMessageSize;
|
||||
unsigned int nChecksum;
|
||||
};
|
||||
|
||||
/** nServices flags */
|
||||
enum
|
||||
{
|
||||
NODE_NETWORK = (1 << 0),
|
||||
};
|
||||
|
||||
/** A CService with information about it as peer */
|
||||
class CAddress : public CService
|
||||
{
|
||||
public:
|
||||
CAddress();
|
||||
explicit CAddress(CService ipIn, uint64 nServicesIn=NODE_NETWORK);
|
||||
|
||||
void Init();
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
CAddress* pthis = const_cast<CAddress*>(this);
|
||||
CService* pip = (CService*)pthis;
|
||||
if (fRead)
|
||||
pthis->Init();
|
||||
if (nType & SER_DISK)
|
||||
READWRITE(nVersion);
|
||||
if ((nType & SER_DISK) ||
|
||||
(nVersion >= CADDR_TIME_VERSION && !(nType & SER_GETHASH)))
|
||||
READWRITE(nTime);
|
||||
READWRITE(nServices);
|
||||
READWRITE(*pip);
|
||||
)
|
||||
|
||||
void print() const;
|
||||
|
||||
// TODO: make private (improves encapsulation)
|
||||
public:
|
||||
uint64 nServices;
|
||||
|
||||
// disk and network only
|
||||
unsigned int nTime;
|
||||
|
||||
// memory only
|
||||
int64 nLastTry;
|
||||
};
|
||||
|
||||
/** inv message data */
|
||||
class CInv
|
||||
{
|
||||
public:
|
||||
CInv();
|
||||
CInv(int typeIn, const uint256& hashIn);
|
||||
CInv(const std::string& strType, const uint256& hashIn);
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
READWRITE(type);
|
||||
READWRITE(hash);
|
||||
)
|
||||
|
||||
friend bool operator<(const CInv& a, const CInv& b);
|
||||
|
||||
bool IsKnownType() const;
|
||||
const char* GetCommand() const;
|
||||
std::string ToString() const;
|
||||
void print() const;
|
||||
|
||||
// TODO: make private (improves encapsulation)
|
||||
public:
|
||||
int type;
|
||||
uint256 hash;
|
||||
};
|
||||
|
||||
enum
|
||||
{
|
||||
MSG_TX = 1,
|
||||
MSG_BLOCK,
|
||||
// Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however,
|
||||
// MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata.
|
||||
MSG_FILTERED_BLOCK,
|
||||
};
|
||||
|
||||
#endif // __INCLUDED_PROTOCOL_H__
|
|
@ -1,364 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under conditional MIT/X11 software license,
|
||||
// see the accompanying file COPYING
|
||||
|
||||
#include "main.h"
|
||||
#include "bitcoinrpc.h"
|
||||
#include "prime.h"
|
||||
#include "wallet.h"
|
||||
#include "init.h"
|
||||
|
||||
using namespace json_spirit;
|
||||
using namespace std;
|
||||
|
||||
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out);
|
||||
|
||||
// Primecoin: get prime difficulty value (chain length)
|
||||
double GetDifficulty(const CBlockIndex* blockindex)
|
||||
{
|
||||
// Floating point number that is approximate log scale of prime target,
|
||||
// minimum difficulty = 256, maximum difficulty = 2039
|
||||
if (blockindex == NULL)
|
||||
{
|
||||
if (pindexBest == NULL)
|
||||
return 256.0;
|
||||
else
|
||||
blockindex = pindexBest;
|
||||
}
|
||||
|
||||
double dDiff = GetPrimeDifficulty(blockindex->nBits);
|
||||
return dDiff;
|
||||
}
|
||||
|
||||
Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex)
|
||||
{
|
||||
Object result;
|
||||
result.push_back(Pair("hash", block.GetHash().GetHex()));
|
||||
CMerkleTx txGen(block.vtx[0]);
|
||||
txGen.SetMerkleBranch(&block);
|
||||
result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain()));
|
||||
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
|
||||
result.push_back(Pair("height", blockindex->nHeight));
|
||||
result.push_back(Pair("version", block.nVersion));
|
||||
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
|
||||
Array txs;
|
||||
BOOST_FOREACH(const CTransaction&tx, block.vtx)
|
||||
txs.push_back(tx.GetHash().GetHex());
|
||||
result.push_back(Pair("tx", txs));
|
||||
result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime()));
|
||||
result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce));
|
||||
result.push_back(Pair("bits", HexBits(block.nBits)));
|
||||
result.push_back(Pair("difficulty", GetPrimeDifficulty(block.nBits)));
|
||||
result.push_back(Pair("transition", GetPrimeDifficulty(blockindex->nWorkTransition)));
|
||||
CBigNum bnPrimeChainOrigin = CBigNum(block.GetHeaderHash()) * block.bnPrimeChainMultiplier;
|
||||
result.push_back(Pair("primechain", GetPrimeChainName(blockindex->nPrimeChainType, blockindex->nPrimeChainLength).c_str()));
|
||||
result.push_back(Pair("primeorigin", bnPrimeChainOrigin.ToString().c_str()));
|
||||
|
||||
if (blockindex->pprev)
|
||||
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
|
||||
if (blockindex->pnext)
|
||||
result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex()));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
Value getblockcount(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getblockcount\n"
|
||||
"Returns the number of blocks in the longest block chain.");
|
||||
|
||||
return nBestHeight;
|
||||
}
|
||||
|
||||
|
||||
Value getdifficulty(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getdifficulty\n"
|
||||
"Returns the proof-of-work difficulty in prime chain length.");
|
||||
|
||||
return GetDifficulty();
|
||||
}
|
||||
|
||||
|
||||
Value settxfee(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE)
|
||||
throw runtime_error(
|
||||
"settxfee <amount>\n"
|
||||
"<amount> is a real and is rounded to 0.01 (cent)\n"
|
||||
"Minimum and default transaction fee per KB is 1 cent");
|
||||
|
||||
nTransactionFee = (AmountFromValue(params[0]) / CENT) * CENT; // round to cent
|
||||
return true;
|
||||
}
|
||||
|
||||
Value getrawmempool(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getrawmempool\n"
|
||||
"Returns all transaction ids in memory pool.");
|
||||
|
||||
vector<uint256> vtxid;
|
||||
mempool.queryHashes(vtxid);
|
||||
|
||||
Array a;
|
||||
BOOST_FOREACH(const uint256& hash, vtxid)
|
||||
a.push_back(hash.ToString());
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
Value getblockhash(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"getblockhash <index>\n"
|
||||
"Returns hash of block in best-block-chain at <index>.");
|
||||
|
||||
int nHeight = params[0].get_int();
|
||||
if (nHeight < 0 || nHeight > nBestHeight)
|
||||
throw runtime_error("Block number out of range.");
|
||||
|
||||
CBlockIndex* pblockindex = FindBlockByHeight(nHeight);
|
||||
return pblockindex->phashBlock->GetHex();
|
||||
}
|
||||
|
||||
Value getblock(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"getblock <hash>\n"
|
||||
"Returns details of a block with given block-hash.");
|
||||
|
||||
std::string strHash = params[0].get_str();
|
||||
uint256 hash(strHash);
|
||||
|
||||
if (mapBlockIndex.count(hash) == 0)
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
|
||||
|
||||
CBlock block;
|
||||
CBlockIndex* pblockindex = mapBlockIndex[hash];
|
||||
block.ReadFromDisk(pblockindex);
|
||||
|
||||
return blockToJSON(block, pblockindex);
|
||||
}
|
||||
|
||||
Value gettxoutsetinfo(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"gettxoutsetinfo\n"
|
||||
"Returns statistics about the unspent transaction output set.");
|
||||
|
||||
Object ret;
|
||||
|
||||
CCoinsStats stats;
|
||||
if (pcoinsTip->GetStats(stats)) {
|
||||
ret.push_back(Pair("height", (boost::int64_t)stats.nHeight));
|
||||
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
|
||||
ret.push_back(Pair("transactions", (boost::int64_t)stats.nTransactions));
|
||||
ret.push_back(Pair("txouts", (boost::int64_t)stats.nTransactionOutputs));
|
||||
ret.push_back(Pair("bytes_serialized", (boost::int64_t)stats.nSerializedSize));
|
||||
ret.push_back(Pair("hash_serialized", stats.hashSerialized.GetHex()));
|
||||
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
Value gettxout(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 2 || params.size() > 3)
|
||||
throw runtime_error(
|
||||
"gettxout <txid> <n> [includemempool=true]\n"
|
||||
"Returns details about an unspent transaction output.");
|
||||
|
||||
Object ret;
|
||||
|
||||
std::string strHash = params[0].get_str();
|
||||
uint256 hash(strHash);
|
||||
int n = params[1].get_int();
|
||||
bool fMempool = true;
|
||||
if (params.size() > 2)
|
||||
fMempool = params[2].get_bool();
|
||||
|
||||
CCoins coins;
|
||||
if (fMempool) {
|
||||
LOCK(mempool.cs);
|
||||
CCoinsViewMemPool view(*pcoinsTip, mempool);
|
||||
if (!view.GetCoins(hash, coins))
|
||||
return Value::null;
|
||||
mempool.pruneSpent(hash, coins); // TODO: this should be done by the CCoinsViewMemPool
|
||||
} else {
|
||||
if (!pcoinsTip->GetCoins(hash, coins))
|
||||
return Value::null;
|
||||
}
|
||||
if (n<0 || (unsigned int)n>=coins.vout.size() || coins.vout[n].IsNull())
|
||||
return Value::null;
|
||||
|
||||
ret.push_back(Pair("bestblock", pcoinsTip->GetBestBlock()->GetBlockHash().GetHex()));
|
||||
if ((unsigned int)coins.nHeight == MEMPOOL_HEIGHT)
|
||||
ret.push_back(Pair("confirmations", 0));
|
||||
else
|
||||
ret.push_back(Pair("confirmations", pcoinsTip->GetBestBlock()->nHeight - coins.nHeight + 1));
|
||||
ret.push_back(Pair("value", ValueFromAmount(coins.vout[n].nValue)));
|
||||
Object o;
|
||||
ScriptPubKeyToJSON(coins.vout[n].scriptPubKey, o);
|
||||
ret.push_back(Pair("scriptPubKey", o));
|
||||
ret.push_back(Pair("version", coins.nVersion));
|
||||
ret.push_back(Pair("coinbase", coins.fCoinBase));
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Primecoin: list prime chain records within primecoin network
|
||||
Value listprimerecords(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||
throw runtime_error(
|
||||
"listprimerecords <primechain length> [primechain type]\n"
|
||||
"Returns the list of record prime chains in primecoin network.\n"
|
||||
"<primechain length> is integer like 10, 11, 12 etc.\n"
|
||||
"[primechain type] is optional type, among 1CC, 2CC and TWN");
|
||||
|
||||
int nPrimeChainLength = params[0].get_int();
|
||||
unsigned int nPrimeChainType = 0;
|
||||
if (params.size() > 1)
|
||||
{
|
||||
std::string strPrimeChainType = params[1].get_str();
|
||||
if (strPrimeChainType.compare("1CC") == 0)
|
||||
nPrimeChainType = PRIME_CHAIN_CUNNINGHAM1;
|
||||
else if (strPrimeChainType.compare("2CC") == 0)
|
||||
nPrimeChainType = PRIME_CHAIN_CUNNINGHAM2;
|
||||
else if (strPrimeChainType.compare("TWN") == 0)
|
||||
nPrimeChainType = PRIME_CHAIN_BI_TWIN;
|
||||
else
|
||||
throw runtime_error("Prime chain type must be 1CC, 2CC or TWN.");
|
||||
}
|
||||
|
||||
Array ret;
|
||||
|
||||
CBigNum bnPrimeRecord = 0;
|
||||
|
||||
for (CBlockIndex* pindex = pindexGenesisBlock; pindex; pindex = pindex->pnext)
|
||||
{
|
||||
if (nPrimeChainLength != (int) TargetGetLength(pindex->nPrimeChainLength))
|
||||
continue; // length not matching, next block
|
||||
if (nPrimeChainType && nPrimeChainType != pindex->nPrimeChainType)
|
||||
continue; // type not matching, next block
|
||||
|
||||
CBlock block;
|
||||
block.ReadFromDisk(pindex); // read block
|
||||
CBigNum bnPrimeChainOrigin = CBigNum(block.GetHeaderHash()) * block.bnPrimeChainMultiplier; // compute prime chain origin
|
||||
|
||||
if (bnPrimeChainOrigin > bnPrimeRecord)
|
||||
{
|
||||
bnPrimeRecord = bnPrimeChainOrigin; // new record in primecoin
|
||||
Object entry;
|
||||
entry.push_back(Pair("time", DateTimeStrFormat("%Y-%m-%d %H:%M:%S UTC", pindex->GetBlockTime()).c_str()));
|
||||
entry.push_back(Pair("epoch", (boost::int64_t) pindex->GetBlockTime()));
|
||||
entry.push_back(Pair("height", pindex->nHeight));
|
||||
entry.push_back(Pair("ismine", pwalletMain->IsMine(block.vtx[0])));
|
||||
entry.push_back(Pair("primedigit", (int) bnPrimeChainOrigin.ToString().length()));
|
||||
entry.push_back(Pair("primechain", GetPrimeChainName(pindex->nPrimeChainType, pindex->nPrimeChainLength).c_str()));
|
||||
entry.push_back(Pair("primeorigin", bnPrimeChainOrigin.ToString().c_str()));
|
||||
entry.push_back(Pair("primorialform", GetPrimeOriginPrimorialForm(bnPrimeChainOrigin).c_str()));
|
||||
ret.push_back(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Primecoin: list top prime chain within primecoin network
|
||||
Value listtopprimes(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||
throw runtime_error(
|
||||
"listtopprimes <primechain length> [primechain type]\n"
|
||||
"Returns the list of top prime chains in primecoin network.\n"
|
||||
"<primechain length> is integer like 10, 11, 12 etc.\n"
|
||||
"[primechain type] is optional type, among 1CC, 2CC and TWN");
|
||||
|
||||
int nPrimeChainLength = params[0].get_int();
|
||||
unsigned int nPrimeChainType = 0;
|
||||
if (params.size() > 1)
|
||||
{
|
||||
std::string strPrimeChainType = params[1].get_str();
|
||||
if (strPrimeChainType.compare("1CC") == 0)
|
||||
nPrimeChainType = PRIME_CHAIN_CUNNINGHAM1;
|
||||
else if (strPrimeChainType.compare("2CC") == 0)
|
||||
nPrimeChainType = PRIME_CHAIN_CUNNINGHAM2;
|
||||
else if (strPrimeChainType.compare("TWN") == 0)
|
||||
nPrimeChainType = PRIME_CHAIN_BI_TWIN;
|
||||
else
|
||||
throw runtime_error("Prime chain type must be 1CC, 2CC or TWN.");
|
||||
}
|
||||
|
||||
// Search for top prime chains
|
||||
unsigned int nRankingSize = 10; // ranking list size
|
||||
unsigned int nSortVectorSize = 64; // vector size for sort operation
|
||||
CBigNum bnPrimeQualify = 0; // minimum qualify value for ranking list
|
||||
vector<pair<CBigNum, uint256> > vSortedByOrigin;
|
||||
for (CBlockIndex* pindex = pindexGenesisBlock; pindex; pindex = pindex->pnext)
|
||||
{
|
||||
if (nPrimeChainLength != (int) TargetGetLength(pindex->nPrimeChainLength))
|
||||
continue; // length not matching, next block
|
||||
if (nPrimeChainType && nPrimeChainType != pindex->nPrimeChainType)
|
||||
continue; // type not matching, next block
|
||||
|
||||
CBlock block;
|
||||
block.ReadFromDisk(pindex); // read block
|
||||
CBigNum bnPrimeChainOrigin = CBigNum(block.GetHeaderHash()) * block.bnPrimeChainMultiplier; // compute prime chain origin
|
||||
|
||||
if (bnPrimeChainOrigin > bnPrimeQualify)
|
||||
vSortedByOrigin.push_back(make_pair(bnPrimeChainOrigin, block.GetHash()));
|
||||
|
||||
if (vSortedByOrigin.size() >= nSortVectorSize)
|
||||
{
|
||||
// Sort prime chain candidates
|
||||
sort(vSortedByOrigin.begin(), vSortedByOrigin.end());
|
||||
reverse(vSortedByOrigin.begin(), vSortedByOrigin.end());
|
||||
// Truncate candidate list
|
||||
while (vSortedByOrigin.size() > nRankingSize)
|
||||
vSortedByOrigin.pop_back();
|
||||
// Update minimum qualify value for top prime chains
|
||||
bnPrimeQualify = vSortedByOrigin.back().first;
|
||||
}
|
||||
}
|
||||
|
||||
// Final sort of prime chain candidates
|
||||
sort(vSortedByOrigin.begin(), vSortedByOrigin.end());
|
||||
reverse(vSortedByOrigin.begin(), vSortedByOrigin.end());
|
||||
// Truncate candidate list
|
||||
while (vSortedByOrigin.size() > nRankingSize)
|
||||
vSortedByOrigin.pop_back();
|
||||
|
||||
// Output top prime chains
|
||||
Array ret;
|
||||
BOOST_FOREACH(const PAIRTYPE(CBigNum, uint256)& item, vSortedByOrigin)
|
||||
{
|
||||
CBigNum bnPrimeChainOrigin = item.first;
|
||||
CBlockIndex* pindex = mapBlockIndex[item.second];
|
||||
CBlock block;
|
||||
block.ReadFromDisk(pindex); // read block
|
||||
Object entry;
|
||||
entry.push_back(Pair("time", DateTimeStrFormat("%Y-%m-%d %H:%M:%S UTC", pindex->GetBlockTime()).c_str()));
|
||||
entry.push_back(Pair("epoch", (boost::int64_t) pindex->GetBlockTime()));
|
||||
entry.push_back(Pair("height", pindex->nHeight));
|
||||
entry.push_back(Pair("ismine", pwalletMain->IsMine(block.vtx[0])));
|
||||
entry.push_back(Pair("primedigit", (int) bnPrimeChainOrigin.ToString().length()));
|
||||
entry.push_back(Pair("primechain", GetPrimeChainName(pindex->nPrimeChainType, pindex->nPrimeChainLength).c_str()));
|
||||
entry.push_back(Pair("primeorigin", bnPrimeChainOrigin.ToString().c_str()));
|
||||
entry.push_back(Pair("primorialform", GetPrimeOriginPrimorialForm(bnPrimeChainOrigin).c_str()));
|
||||
ret.push_back(entry);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
100
src/rpcdump.cpp
100
src/rpcdump.cpp
|
@ -1,100 +0,0 @@
|
|||
// Copyright (c) 2009-2012 Bitcoin Developers
|
||||
// Copyright (c) 2013 Primecoin Developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "init.h" // for pwalletMain
|
||||
#include "bitcoinrpc.h"
|
||||
#include "ui_interface.h"
|
||||
#include "base58.h"
|
||||
|
||||
#include <boost/lexical_cast.hpp>
|
||||
|
||||
#define printf OutputDebugStringF
|
||||
|
||||
using namespace json_spirit;
|
||||
using namespace std;
|
||||
|
||||
class CTxDump
|
||||
{
|
||||
public:
|
||||
CBlockIndex *pindex;
|
||||
int64 nValue;
|
||||
bool fSpent;
|
||||
CWalletTx* ptx;
|
||||
int nOut;
|
||||
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
|
||||
{
|
||||
pindex = NULL;
|
||||
nValue = 0;
|
||||
fSpent = false;
|
||||
this->ptx = ptx;
|
||||
this->nOut = nOut;
|
||||
}
|
||||
};
|
||||
|
||||
Value importprivkey(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 3)
|
||||
throw runtime_error(
|
||||
"importprivkey <primecoinprivkey> [label] [rescan=true]\n"
|
||||
"Adds a private key (as returned by dumpprivkey) to your wallet.");
|
||||
|
||||
string strSecret = params[0].get_str();
|
||||
string strLabel = "";
|
||||
if (params.size() > 1)
|
||||
strLabel = params[1].get_str();
|
||||
|
||||
// Whether to perform rescan after import
|
||||
bool fRescan = true;
|
||||
if (params.size() > 2)
|
||||
fRescan = params[2].get_bool();
|
||||
|
||||
CBitcoinSecret vchSecret;
|
||||
bool fGood = vchSecret.SetString(strSecret);
|
||||
|
||||
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
|
||||
|
||||
CKey key;
|
||||
bool fCompressed;
|
||||
CSecret secret = vchSecret.GetSecret(fCompressed);
|
||||
key.SetSecret(secret, fCompressed);
|
||||
CKeyID vchAddress = key.GetPubKey().GetID();
|
||||
{
|
||||
LOCK2(cs_main, pwalletMain->cs_wallet);
|
||||
|
||||
pwalletMain->MarkDirty();
|
||||
pwalletMain->SetAddressBookName(vchAddress, strLabel);
|
||||
|
||||
if (!pwalletMain->AddKey(key))
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
|
||||
|
||||
if (fRescan) {
|
||||
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
|
||||
pwalletMain->ReacceptWalletTransactions();
|
||||
}
|
||||
}
|
||||
|
||||
return Value::null;
|
||||
}
|
||||
|
||||
Value dumpprivkey(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"dumpprivkey <primecoinaddress>\n"
|
||||
"Reveals the private key corresponding to <primecoinaddress>.");
|
||||
|
||||
string strAddress = params[0].get_str();
|
||||
CBitcoinAddress address;
|
||||
if (!address.SetString(strAddress))
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Primecoin address");
|
||||
CKeyID keyID;
|
||||
if (!address.GetKeyID(keyID))
|
||||
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
|
||||
CSecret vchSecret;
|
||||
bool fCompressed;
|
||||
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
|
||||
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
|
||||
return CBitcoinSecret(vchSecret, fCompressed).ToString();
|
||||
}
|
|
@ -1,448 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2013 The Primecoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "main.h"
|
||||
#include "db.h"
|
||||
#include "init.h"
|
||||
#include "bitcoinrpc.h"
|
||||
#include "prime.h"
|
||||
|
||||
using namespace json_spirit;
|
||||
using namespace std;
|
||||
|
||||
Value getgenerate(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getgenerate\n"
|
||||
"Returns true or false.");
|
||||
|
||||
return GetBoolArg("-gen");
|
||||
}
|
||||
|
||||
|
||||
Value setgenerate(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||
throw runtime_error(
|
||||
"setgenerate <generate> [genproclimit]\n"
|
||||
"<generate> is true or false to turn generation on or off.\n"
|
||||
"Generation is limited to [genproclimit] processors, -1 is unlimited.");
|
||||
|
||||
bool fGenerate = true;
|
||||
if (params.size() > 0)
|
||||
fGenerate = params[0].get_bool();
|
||||
|
||||
if (params.size() > 1)
|
||||
{
|
||||
int nGenProcLimit = params[1].get_int();
|
||||
mapArgs["-genproclimit"] = itostr(nGenProcLimit);
|
||||
if (nGenProcLimit == 0)
|
||||
fGenerate = false;
|
||||
}
|
||||
mapArgs["-gen"] = (fGenerate ? "1" : "0");
|
||||
|
||||
GenerateBitcoins(fGenerate, pwalletMain);
|
||||
return Value::null;
|
||||
}
|
||||
|
||||
|
||||
Value getsievepercentage(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getsievepercentage\n"
|
||||
"Returns the current sieve percentage used by the mining algorithm.");
|
||||
|
||||
return (boost::int64_t)nSievePercentage;
|
||||
}
|
||||
|
||||
|
||||
Value setsievepercentage(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1)
|
||||
throw runtime_error(
|
||||
"setsievepercentage <sievepercentage>\n"
|
||||
"<sievepercentage> determines how many rounds the candidate multiplier sieve runs.");
|
||||
|
||||
unsigned int nPercentage = nDefaultSievePercentage;
|
||||
if (params.size() > 0)
|
||||
nPercentage = params[0].get_int();
|
||||
|
||||
nPercentage = std::max(std::min(nPercentage, nMaxSievePercentage), nMinSievePercentage);
|
||||
|
||||
nSievePercentage = nPercentage;
|
||||
return Value::null;
|
||||
}
|
||||
|
||||
|
||||
Value getsieveextensions(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getsieveextensions\n"
|
||||
"Returns the number of times the sieve is extended.");
|
||||
|
||||
return (boost::int64_t)nSieveExtensions;
|
||||
}
|
||||
|
||||
|
||||
Value setsieveextensions(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1)
|
||||
throw runtime_error(
|
||||
"setsieveextensions <sieveextensions>\n"
|
||||
"<sieveextensions> determines the number of times the sieve will be extended.");
|
||||
|
||||
unsigned int nExtensions = (fTestNet) ? nDefaultSieveExtensionsTestnet : nDefaultSieveExtensions;
|
||||
if (params.size() > 0)
|
||||
nExtensions = params[0].get_int();
|
||||
|
||||
nExtensions = std::max(std::min(nExtensions, nMaxSieveExtensions), nMinSieveExtensions);
|
||||
|
||||
nSieveExtensions = nExtensions;
|
||||
return Value::null;
|
||||
}
|
||||
|
||||
|
||||
Value getprimespersec(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getprimespersec\n"
|
||||
"Returns a recent primes per second performance measurement while generating.");
|
||||
|
||||
return (boost::int64_t)dPrimesPerSec;
|
||||
}
|
||||
|
||||
|
||||
Value getchainspermin(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getchainspermin\n"
|
||||
"Returns a recent chains per second performance measurement while generating.");
|
||||
|
||||
return (boost::int64_t)dChainsPerMinute;
|
||||
}
|
||||
|
||||
|
||||
extern Value getdifficulty(const Array& params, bool fHelp);
|
||||
|
||||
|
||||
Value getmininginfo(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getmininginfo\n"
|
||||
"Returns an object containing mining-related information.");
|
||||
|
||||
Object obj;
|
||||
obj.push_back(Pair("blocks", (int)nBestHeight));
|
||||
obj.push_back(Pair("chainspermin", getchainspermin(params, false)));
|
||||
obj.push_back(Pair("chainsperday", dChainsPerDay));
|
||||
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
|
||||
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
|
||||
obj.push_back(Pair("difficulty", getdifficulty(params, false)));
|
||||
obj.push_back(Pair("errors", GetWarnings("statusbar")));
|
||||
obj.push_back(Pair("generate", GetBoolArg("-gen")));
|
||||
obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1)));
|
||||
obj.push_back(Pair("primespersec", getprimespersec(params, false)));
|
||||
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
|
||||
obj.push_back(Pair("sieveextensions",(int)nSieveExtensions));
|
||||
obj.push_back(Pair("sievepercentage",(int)nSievePercentage));
|
||||
obj.push_back(Pair("sievesize", (int)nSieveSize));
|
||||
obj.push_back(Pair("testnet", fTestNet));
|
||||
return obj;
|
||||
}
|
||||
|
||||
|
||||
Value getwork(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() > 1)
|
||||
throw runtime_error(
|
||||
"getwork [data]\n"
|
||||
"If [data] is not specified, returns formatted hash data to work on:\n"
|
||||
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
|
||||
" \"data\" : block data\n"
|
||||
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
|
||||
" \"target\" : little endian hash target\n"
|
||||
"If [data] is specified, tries to solve the block and returns true if it was successful.");
|
||||
|
||||
if (vNodes.empty())
|
||||
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Primecoin is not connected!");
|
||||
|
||||
if (IsInitialBlockDownload())
|
||||
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Primecoin is downloading blocks...");
|
||||
|
||||
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
|
||||
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
|
||||
static vector<CBlockTemplate*> vNewBlockTemplate;
|
||||
|
||||
if (params.size() == 0)
|
||||
{
|
||||
// Update block
|
||||
static unsigned int nTransactionsUpdatedLast;
|
||||
static CBlockIndex* pindexPrev;
|
||||
static int64 nStart;
|
||||
static CBlockTemplate* pblocktemplate;
|
||||
if (pindexPrev != pindexBest ||
|
||||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60))
|
||||
{
|
||||
if (pindexPrev != pindexBest)
|
||||
{
|
||||
// Deallocate old blocks since they're obsolete now
|
||||
mapNewBlock.clear();
|
||||
BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate)
|
||||
delete pblocktemplate;
|
||||
vNewBlockTemplate.clear();
|
||||
}
|
||||
|
||||
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
|
||||
pindexPrev = NULL;
|
||||
|
||||
// Store the pindexBest used before CreateNewBlock, to avoid races
|
||||
nTransactionsUpdatedLast = nTransactionsUpdated;
|
||||
CBlockIndex* pindexPrevNew = pindexBest;
|
||||
nStart = GetTime();
|
||||
|
||||
// Create new block
|
||||
pblocktemplate = CreateNewBlock(*pMiningKey);
|
||||
if (!pblocktemplate)
|
||||
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
|
||||
vNewBlockTemplate.push_back(pblocktemplate);
|
||||
|
||||
// Need to update only after we know CreateNewBlock succeeded
|
||||
pindexPrev = pindexPrevNew;
|
||||
}
|
||||
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
|
||||
|
||||
// Update nTime
|
||||
pblock->UpdateTime(pindexPrev);
|
||||
pblock->nNonce = 0;
|
||||
|
||||
// Update nExtraNonce
|
||||
static unsigned int nExtraNonce = 0;
|
||||
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
|
||||
|
||||
// Save
|
||||
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
|
||||
|
||||
// Pre-build hash buffers
|
||||
char pmidstate[32];
|
||||
char pdata[128];
|
||||
char phash1[64];
|
||||
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
|
||||
|
||||
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
|
||||
|
||||
Object result;
|
||||
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
|
||||
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
|
||||
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
|
||||
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Parse parameters
|
||||
vector<unsigned char> vchData = ParseHex(params[0].get_str());
|
||||
if (vchData.size() != 128)
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
|
||||
CBlock* pdata = (CBlock*)&vchData[0];
|
||||
|
||||
// Byte reverse
|
||||
for (int i = 0; i < 128/4; i++)
|
||||
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
|
||||
|
||||
// Get saved block
|
||||
if (!mapNewBlock.count(pdata->hashMerkleRoot))
|
||||
return false;
|
||||
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
|
||||
|
||||
pblock->nTime = pdata->nTime;
|
||||
pblock->nNonce = pdata->nNonce;
|
||||
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
|
||||
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
|
||||
|
||||
return CheckWork(pblock, *pwalletMain, *pMiningKey);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Value getblocktemplate(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() > 1)
|
||||
throw runtime_error(
|
||||
"getblocktemplate [params]\n"
|
||||
"Returns data needed to construct a block to work on:\n"
|
||||
" \"version\" : block version\n"
|
||||
" \"previousblockhash\" : hash of current highest block\n"
|
||||
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
|
||||
" \"coinbaseaux\" : data that should be included in coinbase\n"
|
||||
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
|
||||
" \"target\" : hash target\n"
|
||||
" \"mintime\" : minimum timestamp appropriate for next block\n"
|
||||
" \"curtime\" : current timestamp\n"
|
||||
" \"mutable\" : list of ways the block template may be changed\n"
|
||||
" \"noncerange\" : range of valid nonces\n"
|
||||
" \"sigoplimit\" : limit of sigops in blocks\n"
|
||||
" \"sizelimit\" : limit of block size\n"
|
||||
" \"bits\" : compressed target of next block\n"
|
||||
" \"height\" : height of the next block\n"
|
||||
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
|
||||
|
||||
std::string strMode = "template";
|
||||
if (params.size() > 0)
|
||||
{
|
||||
const Object& oparam = params[0].get_obj();
|
||||
const Value& modeval = find_value(oparam, "mode");
|
||||
if (modeval.type() == str_type)
|
||||
strMode = modeval.get_str();
|
||||
else if (modeval.type() == null_type)
|
||||
{
|
||||
/* Do nothing */
|
||||
}
|
||||
else
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
|
||||
}
|
||||
|
||||
if (strMode != "template")
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
|
||||
|
||||
if (vNodes.empty())
|
||||
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Primecoin is not connected!");
|
||||
|
||||
if (IsInitialBlockDownload())
|
||||
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Primecoin is downloading blocks...");
|
||||
|
||||
// Update block
|
||||
static unsigned int nTransactionsUpdatedLast;
|
||||
static CBlockIndex* pindexPrev;
|
||||
static int64 nStart;
|
||||
static CBlockTemplate* pblocktemplate;
|
||||
if (pindexPrev != pindexBest ||
|
||||
(nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5))
|
||||
{
|
||||
// Clear pindexPrev so future calls make a new block, despite any failures from here on
|
||||
pindexPrev = NULL;
|
||||
|
||||
// Store the pindexBest used before CreateNewBlock, to avoid races
|
||||
nTransactionsUpdatedLast = nTransactionsUpdated;
|
||||
CBlockIndex* pindexPrevNew = pindexBest;
|
||||
nStart = GetTime();
|
||||
|
||||
// Create new block
|
||||
if(pblocktemplate)
|
||||
{
|
||||
delete pblocktemplate;
|
||||
pblocktemplate = NULL;
|
||||
}
|
||||
pblocktemplate = CreateNewBlock(*pMiningKey);
|
||||
if (!pblocktemplate)
|
||||
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
|
||||
|
||||
// Need to update only after we know CreateNewBlock succeeded
|
||||
pindexPrev = pindexPrevNew;
|
||||
}
|
||||
CBlock* pblock = &pblocktemplate->block; // pointer for convenience
|
||||
|
||||
// Update nTime
|
||||
pblock->UpdateTime(pindexPrev);
|
||||
pblock->nNonce = 0;
|
||||
|
||||
Array transactions;
|
||||
map<uint256, int64_t> setTxIndex;
|
||||
int i = 0;
|
||||
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
|
||||
{
|
||||
uint256 txHash = tx.GetHash();
|
||||
setTxIndex[txHash] = i++;
|
||||
|
||||
if (tx.IsCoinBase())
|
||||
continue;
|
||||
|
||||
Object entry;
|
||||
|
||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||
ssTx << tx;
|
||||
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
|
||||
|
||||
entry.push_back(Pair("hash", txHash.GetHex()));
|
||||
|
||||
Array deps;
|
||||
BOOST_FOREACH (const CTxIn &in, tx.vin)
|
||||
{
|
||||
if (setTxIndex.count(in.prevout.hash))
|
||||
deps.push_back(setTxIndex[in.prevout.hash]);
|
||||
}
|
||||
entry.push_back(Pair("depends", deps));
|
||||
|
||||
int index_in_template = i - 1;
|
||||
entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
|
||||
entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
|
||||
|
||||
transactions.push_back(entry);
|
||||
}
|
||||
|
||||
Object aux;
|
||||
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
|
||||
|
||||
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
|
||||
|
||||
static Array aMutable;
|
||||
if (aMutable.empty())
|
||||
{
|
||||
aMutable.push_back("time");
|
||||
aMutable.push_back("transactions");
|
||||
aMutable.push_back("prevblock");
|
||||
}
|
||||
|
||||
Object result;
|
||||
result.push_back(Pair("version", pblock->nVersion));
|
||||
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
|
||||
result.push_back(Pair("transactions", transactions));
|
||||
result.push_back(Pair("coinbaseaux", aux));
|
||||
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
|
||||
result.push_back(Pair("target", hashTarget.GetHex()));
|
||||
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1));
|
||||
result.push_back(Pair("mutable", aMutable));
|
||||
result.push_back(Pair("noncerange", "00000000ffffffff"));
|
||||
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
|
||||
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
|
||||
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
|
||||
result.push_back(Pair("bits", HexBits(pblock->nBits)));
|
||||
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Value submitblock(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||
throw runtime_error(
|
||||
"submitblock <hex data> [optional-params-obj]\n"
|
||||
"[optional-params-obj] parameter is currently ignored.\n"
|
||||
"Attempts to submit new block to network.\n"
|
||||
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
|
||||
|
||||
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
|
||||
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
|
||||
CBlock pblock;
|
||||
try {
|
||||
ssBlock >> pblock;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
|
||||
}
|
||||
|
||||
CValidationState state;
|
||||
bool fAccepted = ProcessBlock(state, NULL, &pblock);
|
||||
if (!fAccepted)
|
||||
return "rejected"; // TODO: report validation state
|
||||
|
||||
return Value::null;
|
||||
}
|
313
src/rpcnet.cpp
313
src/rpcnet.cpp
|
@ -1,313 +0,0 @@
|
|||
// Copyright (c) 2009-2012 Bitcoin Developers
|
||||
// Copyright (c) 2012-2013 PPCoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "net.h"
|
||||
#include "bitcoinrpc.h"
|
||||
#include "alert.h"
|
||||
#include "base58.h"
|
||||
|
||||
using namespace json_spirit;
|
||||
using namespace std;
|
||||
|
||||
Value getconnectioncount(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getconnectioncount\n"
|
||||
"Returns the number of connections to other nodes.");
|
||||
|
||||
LOCK(cs_vNodes);
|
||||
return (int)vNodes.size();
|
||||
}
|
||||
|
||||
static void CopyNodeStats(std::vector<CNodeStats>& vstats)
|
||||
{
|
||||
vstats.clear();
|
||||
|
||||
LOCK(cs_vNodes);
|
||||
vstats.reserve(vNodes.size());
|
||||
BOOST_FOREACH(CNode* pnode, vNodes) {
|
||||
CNodeStats stats;
|
||||
pnode->copyStats(stats);
|
||||
vstats.push_back(stats);
|
||||
}
|
||||
}
|
||||
|
||||
Value getpeerinfo(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 0)
|
||||
throw runtime_error(
|
||||
"getpeerinfo\n"
|
||||
"Returns data about each connected network node.");
|
||||
|
||||
vector<CNodeStats> vstats;
|
||||
CopyNodeStats(vstats);
|
||||
|
||||
Array ret;
|
||||
|
||||
BOOST_FOREACH(const CNodeStats& stats, vstats) {
|
||||
Object obj;
|
||||
|
||||
obj.push_back(Pair("addr", stats.addrName));
|
||||
obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices)));
|
||||
obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend));
|
||||
obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
|
||||
obj.push_back(Pair("bytessent", (boost::int64_t)stats.nSendBytes));
|
||||
obj.push_back(Pair("bytesrecv", (boost::int64_t)stats.nRecvBytes));
|
||||
obj.push_back(Pair("conntime", (boost::int64_t)stats.nTimeConnected));
|
||||
obj.push_back(Pair("version", stats.nVersion));
|
||||
obj.push_back(Pair("subver", stats.strSubVer));
|
||||
obj.push_back(Pair("inbound", stats.fInbound));
|
||||
obj.push_back(Pair("startingheight", stats.nStartingHeight));
|
||||
obj.push_back(Pair("banscore", stats.nMisbehavior));
|
||||
if (stats.fSyncNode)
|
||||
obj.push_back(Pair("syncnode", true));
|
||||
|
||||
ret.push_back(obj);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
Value addnode(const Array& params, bool fHelp)
|
||||
{
|
||||
string strCommand;
|
||||
if (params.size() == 2)
|
||||
strCommand = params[1].get_str();
|
||||
if (fHelp || params.size() != 2 ||
|
||||
(strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
|
||||
throw runtime_error(
|
||||
"addnode <node> <add|remove|onetry>\n"
|
||||
"Attempts add or remove <node> from the addnode list or try a connection to <node> once.");
|
||||
|
||||
string strNode = params[0].get_str();
|
||||
|
||||
if (strCommand == "onetry")
|
||||
{
|
||||
CAddress addr;
|
||||
ConnectNode(addr, strNode.c_str());
|
||||
return Value::null;
|
||||
}
|
||||
|
||||
LOCK(cs_vAddedNodes);
|
||||
vector<string>::iterator it = vAddedNodes.begin();
|
||||
for(; it != vAddedNodes.end(); it++)
|
||||
if (strNode == *it)
|
||||
break;
|
||||
|
||||
if (strCommand == "add")
|
||||
{
|
||||
if (it != vAddedNodes.end())
|
||||
throw JSONRPCError(-23, "Error: Node already added");
|
||||
vAddedNodes.push_back(strNode);
|
||||
}
|
||||
else if(strCommand == "remove")
|
||||
{
|
||||
if (it == vAddedNodes.end())
|
||||
throw JSONRPCError(-24, "Error: Node has not been added.");
|
||||
vAddedNodes.erase(it);
|
||||
}
|
||||
|
||||
return Value::null;
|
||||
}
|
||||
|
||||
Value getaddednodeinfo(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||
throw runtime_error(
|
||||
"getaddednodeinfo <dns> [node]\n"
|
||||
"Returns information about the given added node, or all added nodes\n"
|
||||
"(note that onetry addnodes are not listed here)\n"
|
||||
"If dns is false, only a list of added nodes will be provided,\n"
|
||||
"otherwise connected information will also be available.");
|
||||
|
||||
bool fDns = params[0].get_bool();
|
||||
|
||||
list<string> laddedNodes(0);
|
||||
if (params.size() == 1)
|
||||
{
|
||||
LOCK(cs_vAddedNodes);
|
||||
BOOST_FOREACH(string& strAddNode, vAddedNodes)
|
||||
laddedNodes.push_back(strAddNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
string strNode = params[1].get_str();
|
||||
LOCK(cs_vAddedNodes);
|
||||
BOOST_FOREACH(string& strAddNode, vAddedNodes)
|
||||
if (strAddNode == strNode)
|
||||
{
|
||||
laddedNodes.push_back(strAddNode);
|
||||
break;
|
||||
}
|
||||
if (laddedNodes.size() == 0)
|
||||
throw JSONRPCError(-24, "Error: Node has not been added.");
|
||||
}
|
||||
|
||||
if (!fDns)
|
||||
{
|
||||
Object ret;
|
||||
BOOST_FOREACH(string& strAddNode, laddedNodes)
|
||||
ret.push_back(Pair("addednode", strAddNode));
|
||||
return ret;
|
||||
}
|
||||
|
||||
Array ret;
|
||||
|
||||
list<pair<string, vector<CService> > > laddedAddreses(0);
|
||||
BOOST_FOREACH(string& strAddNode, laddedNodes)
|
||||
{
|
||||
vector<CService> vservNode(0);
|
||||
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
|
||||
laddedAddreses.push_back(make_pair(strAddNode, vservNode));
|
||||
else
|
||||
{
|
||||
Object obj;
|
||||
obj.push_back(Pair("addednode", strAddNode));
|
||||
obj.push_back(Pair("connected", false));
|
||||
Array addresses;
|
||||
obj.push_back(Pair("addresses", addresses));
|
||||
}
|
||||
}
|
||||
|
||||
LOCK(cs_vNodes);
|
||||
for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++)
|
||||
{
|
||||
Object obj;
|
||||
obj.push_back(Pair("addednode", it->first));
|
||||
|
||||
Array addresses;
|
||||
bool fConnected = false;
|
||||
BOOST_FOREACH(CService& addrNode, it->second)
|
||||
{
|
||||
bool fFound = false;
|
||||
Object node;
|
||||
node.push_back(Pair("address", addrNode.ToString()));
|
||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||
if (pnode->addr == addrNode)
|
||||
{
|
||||
fFound = true;
|
||||
fConnected = true;
|
||||
node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
|
||||
break;
|
||||
}
|
||||
if (!fFound)
|
||||
node.push_back(Pair("connected", "false"));
|
||||
addresses.push_back(node);
|
||||
}
|
||||
obj.push_back(Pair("connected", fConnected));
|
||||
obj.push_back(Pair("addresses", addresses));
|
||||
ret.push_back(obj);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
// make a public-private key pair (first introduced in ppcoin)
|
||||
Value makekeypair(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() > 1)
|
||||
throw runtime_error(
|
||||
"makekeypair [prefix]\n"
|
||||
"Make a public/private key pair.\n"
|
||||
"[prefix] is optional preferred prefix for the public key.\n");
|
||||
|
||||
string strPrefix = "";
|
||||
if (params.size() > 0)
|
||||
strPrefix = params[0].get_str();
|
||||
|
||||
CKey key;
|
||||
int nCount = 0;
|
||||
do
|
||||
{
|
||||
key.MakeNewKey(false);
|
||||
nCount++;
|
||||
} while (nCount < 10000 && strPrefix != HexStr(key.GetPubKey().Raw()).substr(0, strPrefix.size()));
|
||||
|
||||
if (strPrefix != HexStr(key.GetPubKey().Raw()).substr(0, strPrefix.size()))
|
||||
return Value::null;
|
||||
|
||||
bool fCompressed;
|
||||
CSecret vchSecret = key.GetSecret(fCompressed);
|
||||
Object result;
|
||||
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
|
||||
result.push_back(Pair("PrivateKey", CBitcoinSecret(vchSecret, fCompressed).ToString()));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
// Send alert (first introduced in ppcoin)
|
||||
// There is a known deadlock situation with ThreadMessageHandler
|
||||
// ThreadMessageHandler: holds cs_vSend and acquiring cs_main in SendMessages()
|
||||
// ThreadRPCServer: holds cs_main and acquiring cs_vSend in alert.RelayTo()/PushMessage()/BeginMessage()
|
||||
Value sendalert(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 6)
|
||||
throw runtime_error(
|
||||
"sendalert <message> <privatekey> <minver> <maxver> <priority> <id> [cancelupto]\n"
|
||||
"<message> is the alert text message\n"
|
||||
"<privatekey> is base58 hex string of alert master private key\n"
|
||||
"<minver> is the minimum applicable internal client version\n"
|
||||
"<maxver> is the maximum applicable internal client version\n"
|
||||
"<priority> is integer priority number\n"
|
||||
"<id> is the alert id\n"
|
||||
"[cancelupto] cancels all alert id's up to this number\n"
|
||||
"Returns true or false.");
|
||||
|
||||
// Prepare the alert message
|
||||
CAlert alert;
|
||||
alert.strStatusBar = params[0].get_str();
|
||||
alert.nMinVer = params[2].get_int();
|
||||
alert.nMaxVer = params[3].get_int();
|
||||
alert.nPriority = params[4].get_int();
|
||||
alert.nID = params[5].get_int();
|
||||
if (params.size() > 6)
|
||||
alert.nCancel = params[6].get_int();
|
||||
alert.nVersion = PROTOCOL_VERSION;
|
||||
alert.nRelayUntil = GetAdjustedTime() + 365*24*60*60;
|
||||
alert.nExpiration = GetAdjustedTime() + 365*24*60*60;
|
||||
|
||||
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
|
||||
sMsg << (CUnsignedAlert)alert;
|
||||
alert.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
|
||||
|
||||
// Prepare master key and sign alert message
|
||||
CBitcoinSecret vchSecret;
|
||||
if (!vchSecret.SetString(params[1].get_str()))
|
||||
throw runtime_error("Invalid alert master key");
|
||||
CKey key;
|
||||
bool fCompressed;
|
||||
CSecret secret = vchSecret.GetSecret(fCompressed);
|
||||
key.SetSecret(secret, fCompressed); // if key is not correct openssl may crash
|
||||
if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
|
||||
throw runtime_error(
|
||||
"Unable to sign alert, check alert master key?\n");
|
||||
|
||||
// Process alert
|
||||
if(!alert.ProcessAlert())
|
||||
throw runtime_error(
|
||||
"Failed to process alert.\n");
|
||||
|
||||
// Relay alert
|
||||
{
|
||||
LOCK(cs_vNodes);
|
||||
BOOST_FOREACH(CNode* pnode, vNodes)
|
||||
alert.RelayTo(pnode);
|
||||
}
|
||||
|
||||
Object result;
|
||||
result.push_back(Pair("strStatusBar", alert.strStatusBar));
|
||||
result.push_back(Pair("nVersion", alert.nVersion));
|
||||
result.push_back(Pair("nMinVer", alert.nMinVer));
|
||||
result.push_back(Pair("nMaxVer", alert.nMaxVer));
|
||||
result.push_back(Pair("nPriority", alert.nPriority));
|
||||
result.push_back(Pair("nID", alert.nID));
|
||||
if (alert.nCancel > 0)
|
||||
result.push_back(Pair("nCancel", alert.nCancel));
|
||||
return result;
|
||||
}
|
||||
|
|
@ -1,576 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include <boost/assign/list_of.hpp>
|
||||
|
||||
#include "base58.h"
|
||||
#include "bitcoinrpc.h"
|
||||
#include "db.h"
|
||||
#include "init.h"
|
||||
#include "main.h"
|
||||
#include "net.h"
|
||||
#include "wallet.h"
|
||||
|
||||
using namespace std;
|
||||
using namespace boost;
|
||||
using namespace boost::assign;
|
||||
using namespace json_spirit;
|
||||
|
||||
//
|
||||
// Utilities: convert hex-encoded Values
|
||||
// (throws error if not hex).
|
||||
//
|
||||
uint256 ParseHashV(const Value& v, string strName)
|
||||
{
|
||||
string strHex;
|
||||
if (v.type() == str_type)
|
||||
strHex = v.get_str();
|
||||
if (!IsHex(strHex)) // Note: IsHex("") is false
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
|
||||
uint256 result;
|
||||
result.SetHex(strHex);
|
||||
return result;
|
||||
}
|
||||
uint256 ParseHashO(const Object& o, string strKey)
|
||||
{
|
||||
return ParseHashV(find_value(o, strKey), strKey);
|
||||
}
|
||||
vector<unsigned char> ParseHexV(const Value& v, string strName)
|
||||
{
|
||||
string strHex;
|
||||
if (v.type() == str_type)
|
||||
strHex = v.get_str();
|
||||
if (!IsHex(strHex))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
|
||||
return ParseHex(strHex);
|
||||
}
|
||||
vector<unsigned char> ParseHexO(const Object& o, string strKey)
|
||||
{
|
||||
return ParseHexV(find_value(o, strKey), strKey);
|
||||
}
|
||||
|
||||
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
|
||||
{
|
||||
txnouttype type;
|
||||
vector<CTxDestination> addresses;
|
||||
int nRequired;
|
||||
|
||||
out.push_back(Pair("asm", scriptPubKey.ToString()));
|
||||
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
|
||||
|
||||
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
|
||||
{
|
||||
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
|
||||
return;
|
||||
}
|
||||
|
||||
out.push_back(Pair("reqSigs", nRequired));
|
||||
out.push_back(Pair("type", GetTxnOutputType(type)));
|
||||
|
||||
Array a;
|
||||
BOOST_FOREACH(const CTxDestination& addr, addresses)
|
||||
a.push_back(CBitcoinAddress(addr).ToString());
|
||||
out.push_back(Pair("addresses", a));
|
||||
}
|
||||
|
||||
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
|
||||
{
|
||||
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
|
||||
entry.push_back(Pair("version", tx.nVersion));
|
||||
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
|
||||
Array vin;
|
||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||
{
|
||||
Object in;
|
||||
if (tx.IsCoinBase())
|
||||
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
|
||||
else
|
||||
{
|
||||
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
|
||||
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
|
||||
Object o;
|
||||
o.push_back(Pair("asm", txin.scriptSig.ToString()));
|
||||
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
|
||||
in.push_back(Pair("scriptSig", o));
|
||||
}
|
||||
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
|
||||
vin.push_back(in);
|
||||
}
|
||||
entry.push_back(Pair("vin", vin));
|
||||
Array vout;
|
||||
for (unsigned int i = 0; i < tx.vout.size(); i++)
|
||||
{
|
||||
const CTxOut& txout = tx.vout[i];
|
||||
Object out;
|
||||
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
|
||||
out.push_back(Pair("n", (boost::int64_t)i));
|
||||
Object o;
|
||||
ScriptPubKeyToJSON(txout.scriptPubKey, o);
|
||||
out.push_back(Pair("scriptPubKey", o));
|
||||
vout.push_back(out);
|
||||
}
|
||||
entry.push_back(Pair("vout", vout));
|
||||
|
||||
if (hashBlock != 0)
|
||||
{
|
||||
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
|
||||
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
|
||||
if (mi != mapBlockIndex.end() && (*mi).second)
|
||||
{
|
||||
CBlockIndex* pindex = (*mi).second;
|
||||
if (pindex->IsInMainChain())
|
||||
{
|
||||
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
|
||||
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
|
||||
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
|
||||
}
|
||||
else
|
||||
entry.push_back(Pair("confirmations", 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Value getrawtransaction(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 2)
|
||||
throw runtime_error(
|
||||
"getrawtransaction <txid> [verbose=0]\n"
|
||||
"If verbose=0, returns a string that is\n"
|
||||
"serialized, hex-encoded data for <txid>.\n"
|
||||
"If verbose is non-zero, returns an Object\n"
|
||||
"with information about <txid>.");
|
||||
|
||||
uint256 hash = ParseHashV(params[0], "parameter 1");
|
||||
|
||||
bool fVerbose = false;
|
||||
if (params.size() > 1)
|
||||
fVerbose = (params[1].get_int() != 0);
|
||||
|
||||
CTransaction tx;
|
||||
uint256 hashBlock = 0;
|
||||
if (!GetTransaction(hash, tx, hashBlock, true))
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
|
||||
|
||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||
ssTx << tx;
|
||||
string strHex = HexStr(ssTx.begin(), ssTx.end());
|
||||
|
||||
if (!fVerbose)
|
||||
return strHex;
|
||||
|
||||
Object result;
|
||||
result.push_back(Pair("hex", strHex));
|
||||
TxToJSON(tx, hashBlock, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
Value listunspent(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() > 3)
|
||||
throw runtime_error(
|
||||
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
|
||||
"Returns array of unspent transaction outputs\n"
|
||||
"with between minconf and maxconf (inclusive) confirmations.\n"
|
||||
"Optionally filtered to only include txouts paid to specified addresses.\n"
|
||||
"Results are an array of Objects, each of which has:\n"
|
||||
"{txid, vout, scriptPubKey, amount, confirmations}");
|
||||
|
||||
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
|
||||
|
||||
int nMinDepth = 1;
|
||||
if (params.size() > 0)
|
||||
nMinDepth = params[0].get_int();
|
||||
|
||||
int nMaxDepth = 9999999;
|
||||
if (params.size() > 1)
|
||||
nMaxDepth = params[1].get_int();
|
||||
|
||||
set<CBitcoinAddress> setAddress;
|
||||
if (params.size() > 2)
|
||||
{
|
||||
Array inputs = params[2].get_array();
|
||||
BOOST_FOREACH(Value& input, inputs)
|
||||
{
|
||||
CBitcoinAddress address(input.get_str());
|
||||
if (!address.IsValid())
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+input.get_str());
|
||||
if (setAddress.count(address))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
|
||||
setAddress.insert(address);
|
||||
}
|
||||
}
|
||||
|
||||
Array results;
|
||||
vector<COutput> vecOutputs;
|
||||
pwalletMain->AvailableCoins(vecOutputs, false);
|
||||
BOOST_FOREACH(const COutput& out, vecOutputs)
|
||||
{
|
||||
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
|
||||
continue;
|
||||
|
||||
if (setAddress.size())
|
||||
{
|
||||
CTxDestination address;
|
||||
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
|
||||
continue;
|
||||
|
||||
if (!setAddress.count(address))
|
||||
continue;
|
||||
}
|
||||
|
||||
int64 nValue = out.tx->vout[out.i].nValue;
|
||||
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
|
||||
Object entry;
|
||||
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
|
||||
entry.push_back(Pair("vout", out.i));
|
||||
CTxDestination address;
|
||||
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
|
||||
{
|
||||
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
|
||||
if (pwalletMain->mapAddressBook.count(address))
|
||||
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
|
||||
}
|
||||
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
|
||||
if (pk.IsPayToScriptHash())
|
||||
{
|
||||
CTxDestination address;
|
||||
if (ExtractDestination(pk, address))
|
||||
{
|
||||
const CScriptID& hash = boost::get<const CScriptID&>(address);
|
||||
CScript redeemScript;
|
||||
if (pwalletMain->GetCScript(hash, redeemScript))
|
||||
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
|
||||
}
|
||||
}
|
||||
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
|
||||
entry.push_back(Pair("confirmations",out.nDepth));
|
||||
results.push_back(entry);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
Value createrawtransaction(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 2)
|
||||
throw runtime_error(
|
||||
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
|
||||
"Create a transaction spending given inputs\n"
|
||||
"(array of objects containing transaction id and output number),\n"
|
||||
"sending to given address(es).\n"
|
||||
"Returns hex-encoded raw transaction.\n"
|
||||
"Note that the transaction's inputs are not signed, and\n"
|
||||
"it is not stored in the wallet or transmitted to the network.");
|
||||
|
||||
RPCTypeCheck(params, list_of(array_type)(obj_type));
|
||||
|
||||
Array inputs = params[0].get_array();
|
||||
Object sendTo = params[1].get_obj();
|
||||
|
||||
CTransaction rawTx;
|
||||
|
||||
BOOST_FOREACH(const Value& input, inputs)
|
||||
{
|
||||
const Object& o = input.get_obj();
|
||||
|
||||
uint256 txid = ParseHashO(o, "txid");
|
||||
|
||||
const Value& vout_v = find_value(o, "vout");
|
||||
if (vout_v.type() != int_type)
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
|
||||
int nOutput = vout_v.get_int();
|
||||
if (nOutput < 0)
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
|
||||
|
||||
CTxIn in(COutPoint(txid, nOutput));
|
||||
rawTx.vin.push_back(in);
|
||||
}
|
||||
|
||||
set<CBitcoinAddress> setAddress;
|
||||
BOOST_FOREACH(const Pair& s, sendTo)
|
||||
{
|
||||
CBitcoinAddress address(s.name_);
|
||||
if (!address.IsValid())
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Bitcoin address: ")+s.name_);
|
||||
|
||||
if (setAddress.count(address))
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
|
||||
setAddress.insert(address);
|
||||
|
||||
CScript scriptPubKey;
|
||||
scriptPubKey.SetDestination(address.Get());
|
||||
int64 nAmount = AmountFromValue(s.value_);
|
||||
|
||||
CTxOut out(nAmount, scriptPubKey);
|
||||
rawTx.vout.push_back(out);
|
||||
}
|
||||
|
||||
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
|
||||
ss << rawTx;
|
||||
return HexStr(ss.begin(), ss.end());
|
||||
}
|
||||
|
||||
Value decoderawtransaction(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() != 1)
|
||||
throw runtime_error(
|
||||
"decoderawtransaction <hex string>\n"
|
||||
"Return a JSON object representing the serialized, hex-encoded transaction.");
|
||||
|
||||
vector<unsigned char> txData(ParseHexV(params[0], "argument"));
|
||||
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
||||
CTransaction tx;
|
||||
try {
|
||||
ssData >> tx;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
|
||||
}
|
||||
|
||||
Object result;
|
||||
TxToJSON(tx, 0, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Value signrawtransaction(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 4)
|
||||
throw runtime_error(
|
||||
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
|
||||
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
|
||||
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
|
||||
"this transaction depends on but may not yet be in the block chain.\n"
|
||||
"Third optional argument (may be null) is an array of base58-encoded private\n"
|
||||
"keys that, if given, will be the only keys used to sign the transaction.\n"
|
||||
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
|
||||
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
|
||||
"Returns json object with keys:\n"
|
||||
" hex : raw transaction with signature(s) (hex-encoded string)\n"
|
||||
" complete : 1 if transaction has a complete set of signature (0 if not)"
|
||||
+ HelpRequiringPassphrase());
|
||||
|
||||
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
|
||||
|
||||
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
|
||||
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
||||
vector<CTransaction> txVariants;
|
||||
while (!ssData.empty())
|
||||
{
|
||||
try {
|
||||
CTransaction tx;
|
||||
ssData >> tx;
|
||||
txVariants.push_back(tx);
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
|
||||
}
|
||||
}
|
||||
|
||||
if (txVariants.empty())
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
|
||||
|
||||
// mergedTx will end up with all the signatures; it
|
||||
// starts as a clone of the rawtx:
|
||||
CTransaction mergedTx(txVariants[0]);
|
||||
bool fComplete = true;
|
||||
|
||||
// Fetch previous transactions (inputs):
|
||||
CCoinsView viewDummy;
|
||||
CCoinsViewCache view(viewDummy);
|
||||
{
|
||||
LOCK(mempool.cs);
|
||||
CCoinsViewCache &viewChain = *pcoinsTip;
|
||||
CCoinsViewMemPool viewMempool(viewChain, mempool);
|
||||
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
|
||||
|
||||
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
|
||||
const uint256& prevHash = txin.prevout.hash;
|
||||
CCoins coins;
|
||||
view.GetCoins(prevHash, coins); // this is certainly allowed to fail
|
||||
}
|
||||
|
||||
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
|
||||
}
|
||||
|
||||
bool fGivenKeys = false;
|
||||
CBasicKeyStore tempKeystore;
|
||||
if (params.size() > 2 && params[2].type() != null_type)
|
||||
{
|
||||
fGivenKeys = true;
|
||||
Array keys = params[2].get_array();
|
||||
BOOST_FOREACH(Value k, keys)
|
||||
{
|
||||
CBitcoinSecret vchSecret;
|
||||
bool fGood = vchSecret.SetString(k.get_str());
|
||||
if (!fGood)
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
|
||||
CKey key;
|
||||
bool fCompressed;
|
||||
CSecret secret = vchSecret.GetSecret(fCompressed);
|
||||
key.SetSecret(secret, fCompressed);
|
||||
tempKeystore.AddKey(key);
|
||||
}
|
||||
}
|
||||
else
|
||||
EnsureWalletIsUnlocked();
|
||||
|
||||
// Add previous txouts given in the RPC call:
|
||||
if (params.size() > 1 && params[1].type() != null_type)
|
||||
{
|
||||
Array prevTxs = params[1].get_array();
|
||||
BOOST_FOREACH(Value& p, prevTxs)
|
||||
{
|
||||
if (p.type() != obj_type)
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
|
||||
|
||||
Object prevOut = p.get_obj();
|
||||
|
||||
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
|
||||
|
||||
uint256 txid = ParseHashO(prevOut, "txid");
|
||||
|
||||
int nOut = find_value(prevOut, "vout").get_int();
|
||||
if (nOut < 0)
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
|
||||
|
||||
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
|
||||
CScript scriptPubKey(pkData.begin(), pkData.end());
|
||||
|
||||
CCoins coins;
|
||||
if (view.GetCoins(txid, coins)) {
|
||||
if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
|
||||
string err("Previous output scriptPubKey mismatch:\n");
|
||||
err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
|
||||
scriptPubKey.ToString();
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
|
||||
}
|
||||
// what todo if txid is known, but the actual output isn't?
|
||||
}
|
||||
if ((unsigned int)nOut >= coins.vout.size())
|
||||
coins.vout.resize(nOut+1);
|
||||
coins.vout[nOut].scriptPubKey = scriptPubKey;
|
||||
coins.vout[nOut].nValue = 0; // we don't know the actual output value
|
||||
view.SetCoins(txid, coins);
|
||||
|
||||
// if redeemScript given and not using the local wallet (private keys
|
||||
// given), add redeemScript to the tempKeystore so it can be signed:
|
||||
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
|
||||
{
|
||||
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
|
||||
Value v = find_value(prevOut, "redeemScript");
|
||||
if (!(v == Value::null))
|
||||
{
|
||||
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
|
||||
CScript redeemScript(rsData.begin(), rsData.end());
|
||||
tempKeystore.AddCScript(redeemScript);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
|
||||
|
||||
int nHashType = SIGHASH_ALL;
|
||||
if (params.size() > 3 && params[3].type() != null_type)
|
||||
{
|
||||
static map<string, int> mapSigHashValues =
|
||||
boost::assign::map_list_of
|
||||
(string("ALL"), int(SIGHASH_ALL))
|
||||
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
|
||||
(string("NONE"), int(SIGHASH_NONE))
|
||||
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
|
||||
(string("SINGLE"), int(SIGHASH_SINGLE))
|
||||
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
|
||||
;
|
||||
string strHashType = params[3].get_str();
|
||||
if (mapSigHashValues.count(strHashType))
|
||||
nHashType = mapSigHashValues[strHashType];
|
||||
else
|
||||
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
|
||||
}
|
||||
|
||||
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
|
||||
|
||||
// Sign what we can:
|
||||
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
|
||||
{
|
||||
CTxIn& txin = mergedTx.vin[i];
|
||||
CCoins coins;
|
||||
if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
|
||||
{
|
||||
fComplete = false;
|
||||
continue;
|
||||
}
|
||||
const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
|
||||
|
||||
txin.scriptSig.clear();
|
||||
// Only sign SIGHASH_SINGLE if there's a corresponding output:
|
||||
if (!fHashSingle || (i < mergedTx.vout.size()))
|
||||
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
|
||||
|
||||
// ... and merge in other signatures:
|
||||
BOOST_FOREACH(const CTransaction& txv, txVariants)
|
||||
{
|
||||
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
|
||||
}
|
||||
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
|
||||
fComplete = false;
|
||||
}
|
||||
|
||||
Object result;
|
||||
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
|
||||
ssTx << mergedTx;
|
||||
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
|
||||
result.push_back(Pair("complete", fComplete));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Value sendrawtransaction(const Array& params, bool fHelp)
|
||||
{
|
||||
if (fHelp || params.size() < 1 || params.size() > 1)
|
||||
throw runtime_error(
|
||||
"sendrawtransaction <hex string>\n"
|
||||
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
|
||||
|
||||
// parse hex string from parameter
|
||||
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
|
||||
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
|
||||
CTransaction tx;
|
||||
|
||||
// deserialize binary data stream
|
||||
try {
|
||||
ssData >> tx;
|
||||
}
|
||||
catch (std::exception &e) {
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
|
||||
}
|
||||
uint256 hashTx = tx.GetHash();
|
||||
|
||||
bool fHave = false;
|
||||
CCoinsViewCache &view = *pcoinsTip;
|
||||
CCoins existingCoins;
|
||||
{
|
||||
fHave = view.GetCoins(hashTx, existingCoins);
|
||||
if (!fHave) {
|
||||
// push to local node
|
||||
CValidationState state;
|
||||
if (!tx.AcceptToMemoryPool(state, true, false))
|
||||
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state
|
||||
}
|
||||
}
|
||||
if (fHave) {
|
||||
if (existingCoins.nHeight < 1000000000)
|
||||
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain");
|
||||
// Not in block, but already in the memory pool; will drop
|
||||
// through to re-relay it.
|
||||
} else {
|
||||
SyncWithWallets(hashTx, tx, NULL, true);
|
||||
}
|
||||
RelayTransaction(tx, hashTx);
|
||||
|
||||
return hashTx.GetHex();
|
||||
}
|
1579
src/rpcwallet.cpp
1579
src/rpcwallet.cpp
File diff suppressed because it is too large
Load Diff
1906
src/script.cpp
1906
src/script.cpp
File diff suppressed because it is too large
Load Diff
685
src/script.h
685
src/script.h
|
@ -1,685 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef H_BITCOIN_SCRIPT
|
||||
#define H_BITCOIN_SCRIPT
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <boost/foreach.hpp>
|
||||
#include <boost/variant.hpp>
|
||||
|
||||
#include "keystore.h"
|
||||
#include "bignum.h"
|
||||
|
||||
class CCoins;
|
||||
class CTransaction;
|
||||
|
||||
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes
|
||||
|
||||
/** Signature hash types/flags */
|
||||
enum
|
||||
{
|
||||
SIGHASH_ALL = 1,
|
||||
SIGHASH_NONE = 2,
|
||||
SIGHASH_SINGLE = 3,
|
||||
SIGHASH_ANYONECANPAY = 0x80,
|
||||
};
|
||||
|
||||
/** Script verification flags */
|
||||
enum
|
||||
{
|
||||
SCRIPT_VERIFY_NONE = 0,
|
||||
SCRIPT_VERIFY_P2SH = (1U << 0),
|
||||
SCRIPT_VERIFY_STRICTENC = (1U << 1),
|
||||
SCRIPT_VERIFY_NOCACHE = (1U << 2),
|
||||
};
|
||||
|
||||
enum txnouttype
|
||||
{
|
||||
TX_NONSTANDARD,
|
||||
// 'standard' transaction types:
|
||||
TX_PUBKEY,
|
||||
TX_PUBKEYHASH,
|
||||
TX_SCRIPTHASH,
|
||||
TX_MULTISIG,
|
||||
};
|
||||
|
||||
class CNoDestination {
|
||||
public:
|
||||
friend bool operator==(const CNoDestination &a, const CNoDestination &b) { return true; }
|
||||
friend bool operator<(const CNoDestination &a, const CNoDestination &b) { return true; }
|
||||
};
|
||||
|
||||
/** A txout script template with a specific destination. It is either:
|
||||
* * CNoDestination: no destination set
|
||||
* * CKeyID: TX_PUBKEYHASH destination
|
||||
* * CScriptID: TX_SCRIPTHASH destination
|
||||
* A CTxDestination is the internal data type encoded in a CBitcoinAddress
|
||||
*/
|
||||
typedef boost::variant<CNoDestination, CKeyID, CScriptID> CTxDestination;
|
||||
|
||||
const char* GetTxnOutputType(txnouttype t);
|
||||
|
||||
/** Script opcodes */
|
||||
enum opcodetype
|
||||
{
|
||||
// push value
|
||||
OP_0 = 0x00,
|
||||
OP_FALSE = OP_0,
|
||||
OP_PUSHDATA1 = 0x4c,
|
||||
OP_PUSHDATA2 = 0x4d,
|
||||
OP_PUSHDATA4 = 0x4e,
|
||||
OP_1NEGATE = 0x4f,
|
||||
OP_RESERVED = 0x50,
|
||||
OP_1 = 0x51,
|
||||
OP_TRUE=OP_1,
|
||||
OP_2 = 0x52,
|
||||
OP_3 = 0x53,
|
||||
OP_4 = 0x54,
|
||||
OP_5 = 0x55,
|
||||
OP_6 = 0x56,
|
||||
OP_7 = 0x57,
|
||||
OP_8 = 0x58,
|
||||
OP_9 = 0x59,
|
||||
OP_10 = 0x5a,
|
||||
OP_11 = 0x5b,
|
||||
OP_12 = 0x5c,
|
||||
OP_13 = 0x5d,
|
||||
OP_14 = 0x5e,
|
||||
OP_15 = 0x5f,
|
||||
OP_16 = 0x60,
|
||||
|
||||
// control
|
||||
OP_NOP = 0x61,
|
||||
OP_VER = 0x62,
|
||||
OP_IF = 0x63,
|
||||
OP_NOTIF = 0x64,
|
||||
OP_VERIF = 0x65,
|
||||
OP_VERNOTIF = 0x66,
|
||||
OP_ELSE = 0x67,
|
||||
OP_ENDIF = 0x68,
|
||||
OP_VERIFY = 0x69,
|
||||
OP_RETURN = 0x6a,
|
||||
|
||||
// stack ops
|
||||
OP_TOALTSTACK = 0x6b,
|
||||
OP_FROMALTSTACK = 0x6c,
|
||||
OP_2DROP = 0x6d,
|
||||
OP_2DUP = 0x6e,
|
||||
OP_3DUP = 0x6f,
|
||||
OP_2OVER = 0x70,
|
||||
OP_2ROT = 0x71,
|
||||
OP_2SWAP = 0x72,
|
||||
OP_IFDUP = 0x73,
|
||||
OP_DEPTH = 0x74,
|
||||
OP_DROP = 0x75,
|
||||
OP_DUP = 0x76,
|
||||
OP_NIP = 0x77,
|
||||
OP_OVER = 0x78,
|
||||
OP_PICK = 0x79,
|
||||
OP_ROLL = 0x7a,
|
||||
OP_ROT = 0x7b,
|
||||
OP_SWAP = 0x7c,
|
||||
OP_TUCK = 0x7d,
|
||||
|
||||
// splice ops
|
||||
OP_CAT = 0x7e,
|
||||
OP_SUBSTR = 0x7f,
|
||||
OP_LEFT = 0x80,
|
||||
OP_RIGHT = 0x81,
|
||||
OP_SIZE = 0x82,
|
||||
|
||||
// bit logic
|
||||
OP_INVERT = 0x83,
|
||||
OP_AND = 0x84,
|
||||
OP_OR = 0x85,
|
||||
OP_XOR = 0x86,
|
||||
OP_EQUAL = 0x87,
|
||||
OP_EQUALVERIFY = 0x88,
|
||||
OP_RESERVED1 = 0x89,
|
||||
OP_RESERVED2 = 0x8a,
|
||||
|
||||
// numeric
|
||||
OP_1ADD = 0x8b,
|
||||
OP_1SUB = 0x8c,
|
||||
OP_2MUL = 0x8d,
|
||||
OP_2DIV = 0x8e,
|
||||
OP_NEGATE = 0x8f,
|
||||
OP_ABS = 0x90,
|
||||
OP_NOT = 0x91,
|
||||
OP_0NOTEQUAL = 0x92,
|
||||
|
||||
OP_ADD = 0x93,
|
||||
OP_SUB = 0x94,
|
||||
OP_MUL = 0x95,
|
||||
OP_DIV = 0x96,
|
||||
OP_MOD = 0x97,
|
||||
OP_LSHIFT = 0x98,
|
||||
OP_RSHIFT = 0x99,
|
||||
|
||||
OP_BOOLAND = 0x9a,
|
||||
OP_BOOLOR = 0x9b,
|
||||
OP_NUMEQUAL = 0x9c,
|
||||
OP_NUMEQUALVERIFY = 0x9d,
|
||||
OP_NUMNOTEQUAL = 0x9e,
|
||||
OP_LESSTHAN = 0x9f,
|
||||
OP_GREATERTHAN = 0xa0,
|
||||
OP_LESSTHANOREQUAL = 0xa1,
|
||||
OP_GREATERTHANOREQUAL = 0xa2,
|
||||
OP_MIN = 0xa3,
|
||||
OP_MAX = 0xa4,
|
||||
|
||||
OP_WITHIN = 0xa5,
|
||||
|
||||
// crypto
|
||||
OP_RIPEMD160 = 0xa6,
|
||||
OP_SHA1 = 0xa7,
|
||||
OP_SHA256 = 0xa8,
|
||||
OP_HASH160 = 0xa9,
|
||||
OP_HASH256 = 0xaa,
|
||||
OP_CODESEPARATOR = 0xab,
|
||||
OP_CHECKSIG = 0xac,
|
||||
OP_CHECKSIGVERIFY = 0xad,
|
||||
OP_CHECKMULTISIG = 0xae,
|
||||
OP_CHECKMULTISIGVERIFY = 0xaf,
|
||||
|
||||
// expansion
|
||||
OP_NOP1 = 0xb0,
|
||||
OP_NOP2 = 0xb1,
|
||||
OP_NOP3 = 0xb2,
|
||||
OP_NOP4 = 0xb3,
|
||||
OP_NOP5 = 0xb4,
|
||||
OP_NOP6 = 0xb5,
|
||||
OP_NOP7 = 0xb6,
|
||||
OP_NOP8 = 0xb7,
|
||||
OP_NOP9 = 0xb8,
|
||||
OP_NOP10 = 0xb9,
|
||||
|
||||
|
||||
|
||||
// template matching params
|
||||
OP_SMALLINTEGER = 0xfa,
|
||||
OP_PUBKEYS = 0xfb,
|
||||
OP_PUBKEYHASH = 0xfd,
|
||||
OP_PUBKEY = 0xfe,
|
||||
|
||||
OP_INVALIDOPCODE = 0xff,
|
||||
};
|
||||
|
||||
const char* GetOpName(opcodetype opcode);
|
||||
|
||||
|
||||
|
||||
inline std::string ValueString(const std::vector<unsigned char>& vch)
|
||||
{
|
||||
if (vch.size() <= 4)
|
||||
return strprintf("%d", CBigNum(vch).getint());
|
||||
else
|
||||
return HexStr(vch);
|
||||
}
|
||||
|
||||
inline std::string StackString(const std::vector<std::vector<unsigned char> >& vStack)
|
||||
{
|
||||
std::string str;
|
||||
BOOST_FOREACH(const std::vector<unsigned char>& vch, vStack)
|
||||
{
|
||||
if (!str.empty())
|
||||
str += " ";
|
||||
str += ValueString(vch);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/** Serialized script, used inside transaction inputs and outputs */
|
||||
class CScript : public std::vector<unsigned char>
|
||||
{
|
||||
protected:
|
||||
CScript& push_int64(int64 n)
|
||||
{
|
||||
if (n == -1 || (n >= 1 && n <= 16))
|
||||
{
|
||||
push_back(n + (OP_1 - 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
CBigNum bn(n);
|
||||
*this << bn.getvch();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScript& push_uint64(uint64 n)
|
||||
{
|
||||
if (n >= 1 && n <= 16)
|
||||
{
|
||||
push_back(n + (OP_1 - 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
CBigNum bn(n);
|
||||
*this << bn.getvch();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
public:
|
||||
CScript() { }
|
||||
CScript(const CScript& b) : std::vector<unsigned char>(b.begin(), b.end()) { }
|
||||
CScript(const_iterator pbegin, const_iterator pend) : std::vector<unsigned char>(pbegin, pend) { }
|
||||
#ifndef _MSC_VER
|
||||
CScript(const unsigned char* pbegin, const unsigned char* pend) : std::vector<unsigned char>(pbegin, pend) { }
|
||||
#endif
|
||||
|
||||
CScript& operator+=(const CScript& b)
|
||||
{
|
||||
insert(end(), b.begin(), b.end());
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend CScript operator+(const CScript& a, const CScript& b)
|
||||
{
|
||||
CScript ret = a;
|
||||
ret += b;
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
//explicit CScript(char b) is not portable. Use 'signed char' or 'unsigned char'.
|
||||
explicit CScript(signed char b) { operator<<(b); }
|
||||
explicit CScript(short b) { operator<<(b); }
|
||||
explicit CScript(int b) { operator<<(b); }
|
||||
explicit CScript(long b) { operator<<(b); }
|
||||
explicit CScript(int64 b) { operator<<(b); }
|
||||
explicit CScript(unsigned char b) { operator<<(b); }
|
||||
explicit CScript(unsigned int b) { operator<<(b); }
|
||||
explicit CScript(unsigned short b) { operator<<(b); }
|
||||
explicit CScript(unsigned long b) { operator<<(b); }
|
||||
explicit CScript(uint64 b) { operator<<(b); }
|
||||
|
||||
explicit CScript(opcodetype b) { operator<<(b); }
|
||||
explicit CScript(const uint256& b) { operator<<(b); }
|
||||
explicit CScript(const CBigNum& b) { operator<<(b); }
|
||||
explicit CScript(const std::vector<unsigned char>& b) { operator<<(b); }
|
||||
|
||||
|
||||
//CScript& operator<<(char b) is not portable. Use 'signed char' or 'unsigned char'.
|
||||
CScript& operator<<(signed char b) { return push_int64(b); }
|
||||
CScript& operator<<(short b) { return push_int64(b); }
|
||||
CScript& operator<<(int b) { return push_int64(b); }
|
||||
CScript& operator<<(long b) { return push_int64(b); }
|
||||
CScript& operator<<(int64 b) { return push_int64(b); }
|
||||
CScript& operator<<(unsigned char b) { return push_uint64(b); }
|
||||
CScript& operator<<(unsigned int b) { return push_uint64(b); }
|
||||
CScript& operator<<(unsigned short b) { return push_uint64(b); }
|
||||
CScript& operator<<(unsigned long b) { return push_uint64(b); }
|
||||
CScript& operator<<(uint64 b) { return push_uint64(b); }
|
||||
|
||||
CScript& operator<<(opcodetype opcode)
|
||||
{
|
||||
if (opcode < 0 || opcode > 0xff)
|
||||
throw std::runtime_error("CScript::operator<<() : invalid opcode");
|
||||
insert(end(), (unsigned char)opcode);
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScript& operator<<(const uint160& b)
|
||||
{
|
||||
insert(end(), sizeof(b));
|
||||
insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScript& operator<<(const uint256& b)
|
||||
{
|
||||
insert(end(), sizeof(b));
|
||||
insert(end(), (unsigned char*)&b, (unsigned char*)&b + sizeof(b));
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScript& operator<<(const CPubKey& key)
|
||||
{
|
||||
std::vector<unsigned char> vchKey = key.Raw();
|
||||
return (*this) << vchKey;
|
||||
}
|
||||
|
||||
CScript& operator<<(const CBigNum& b)
|
||||
{
|
||||
*this << b.getvch();
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScript& operator<<(const std::vector<unsigned char>& b)
|
||||
{
|
||||
if (b.size() < OP_PUSHDATA1)
|
||||
{
|
||||
insert(end(), (unsigned char)b.size());
|
||||
}
|
||||
else if (b.size() <= 0xff)
|
||||
{
|
||||
insert(end(), OP_PUSHDATA1);
|
||||
insert(end(), (unsigned char)b.size());
|
||||
}
|
||||
else if (b.size() <= 0xffff)
|
||||
{
|
||||
insert(end(), OP_PUSHDATA2);
|
||||
unsigned short nSize = b.size();
|
||||
insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
|
||||
}
|
||||
else
|
||||
{
|
||||
insert(end(), OP_PUSHDATA4);
|
||||
unsigned int nSize = b.size();
|
||||
insert(end(), (unsigned char*)&nSize, (unsigned char*)&nSize + sizeof(nSize));
|
||||
}
|
||||
insert(end(), b.begin(), b.end());
|
||||
return *this;
|
||||
}
|
||||
|
||||
CScript& operator<<(const CScript& b)
|
||||
{
|
||||
// I'm not sure if this should push the script or concatenate scripts.
|
||||
// If there's ever a use for pushing a script onto a script, delete this member fn
|
||||
assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
bool GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet)
|
||||
{
|
||||
// Wrapper so it can be called with either iterator or const_iterator
|
||||
const_iterator pc2 = pc;
|
||||
bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
|
||||
pc = begin() + (pc2 - begin());
|
||||
return fRet;
|
||||
}
|
||||
|
||||
bool GetOp(iterator& pc, opcodetype& opcodeRet)
|
||||
{
|
||||
const_iterator pc2 = pc;
|
||||
bool fRet = GetOp2(pc2, opcodeRet, NULL);
|
||||
pc = begin() + (pc2 - begin());
|
||||
return fRet;
|
||||
}
|
||||
|
||||
bool GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>& vchRet) const
|
||||
{
|
||||
return GetOp2(pc, opcodeRet, &vchRet);
|
||||
}
|
||||
|
||||
bool GetOp(const_iterator& pc, opcodetype& opcodeRet) const
|
||||
{
|
||||
return GetOp2(pc, opcodeRet, NULL);
|
||||
}
|
||||
|
||||
bool GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<unsigned char>* pvchRet) const
|
||||
{
|
||||
opcodeRet = OP_INVALIDOPCODE;
|
||||
if (pvchRet)
|
||||
pvchRet->clear();
|
||||
if (pc >= end())
|
||||
return false;
|
||||
|
||||
// Read instruction
|
||||
if (end() - pc < 1)
|
||||
return false;
|
||||
unsigned int opcode = *pc++;
|
||||
|
||||
// Immediate operand
|
||||
if (opcode <= OP_PUSHDATA4)
|
||||
{
|
||||
unsigned int nSize = 0;
|
||||
if (opcode < OP_PUSHDATA1)
|
||||
{
|
||||
nSize = opcode;
|
||||
}
|
||||
else if (opcode == OP_PUSHDATA1)
|
||||
{
|
||||
if (end() - pc < 1)
|
||||
return false;
|
||||
nSize = *pc++;
|
||||
}
|
||||
else if (opcode == OP_PUSHDATA2)
|
||||
{
|
||||
if (end() - pc < 2)
|
||||
return false;
|
||||
nSize = 0;
|
||||
memcpy(&nSize, &pc[0], 2);
|
||||
pc += 2;
|
||||
}
|
||||
else if (opcode == OP_PUSHDATA4)
|
||||
{
|
||||
if (end() - pc < 4)
|
||||
return false;
|
||||
memcpy(&nSize, &pc[0], 4);
|
||||
pc += 4;
|
||||
}
|
||||
if (end() - pc < 0 || (unsigned int)(end() - pc) < nSize)
|
||||
return false;
|
||||
if (pvchRet)
|
||||
pvchRet->assign(pc, pc + nSize);
|
||||
pc += nSize;
|
||||
}
|
||||
|
||||
opcodeRet = (opcodetype)opcode;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Encode/decode small integers:
|
||||
static int DecodeOP_N(opcodetype opcode)
|
||||
{
|
||||
if (opcode == OP_0)
|
||||
return 0;
|
||||
assert(opcode >= OP_1 && opcode <= OP_16);
|
||||
return (int)opcode - (int)(OP_1 - 1);
|
||||
}
|
||||
static opcodetype EncodeOP_N(int n)
|
||||
{
|
||||
assert(n >= 0 && n <= 16);
|
||||
if (n == 0)
|
||||
return OP_0;
|
||||
return (opcodetype)(OP_1+n-1);
|
||||
}
|
||||
|
||||
int FindAndDelete(const CScript& b)
|
||||
{
|
||||
int nFound = 0;
|
||||
if (b.empty())
|
||||
return nFound;
|
||||
iterator pc = begin();
|
||||
opcodetype opcode;
|
||||
do
|
||||
{
|
||||
while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
|
||||
{
|
||||
erase(pc, pc + b.size());
|
||||
++nFound;
|
||||
}
|
||||
}
|
||||
while (GetOp(pc, opcode));
|
||||
return nFound;
|
||||
}
|
||||
int Find(opcodetype op) const
|
||||
{
|
||||
int nFound = 0;
|
||||
opcodetype opcode;
|
||||
for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
|
||||
if (opcode == op)
|
||||
++nFound;
|
||||
return nFound;
|
||||
}
|
||||
|
||||
// Pre-version-0.6, Bitcoin always counted CHECKMULTISIGs
|
||||
// as 20 sigops. With pay-to-script-hash, that changed:
|
||||
// CHECKMULTISIGs serialized in scriptSigs are
|
||||
// counted more accurately, assuming they are of the form
|
||||
// ... OP_N CHECKMULTISIG ...
|
||||
unsigned int GetSigOpCount(bool fAccurate) const;
|
||||
|
||||
// Accurately count sigOps, including sigOps in
|
||||
// pay-to-script-hash transactions:
|
||||
unsigned int GetSigOpCount(const CScript& scriptSig) const;
|
||||
|
||||
bool IsPayToScriptHash() const;
|
||||
|
||||
// Called by CTransaction::IsStandard
|
||||
bool IsPushOnly() const
|
||||
{
|
||||
const_iterator pc = begin();
|
||||
while (pc < end())
|
||||
{
|
||||
opcodetype opcode;
|
||||
if (!GetOp(pc, opcode))
|
||||
return false;
|
||||
if (opcode > OP_16)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void SetDestination(const CTxDestination& address);
|
||||
void SetMultisig(int nRequired, const std::vector<CKey>& keys);
|
||||
|
||||
|
||||
void PrintHex() const
|
||||
{
|
||||
printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
|
||||
}
|
||||
|
||||
std::string ToString() const
|
||||
{
|
||||
std::string str;
|
||||
opcodetype opcode;
|
||||
std::vector<unsigned char> vch;
|
||||
const_iterator pc = begin();
|
||||
while (pc < end())
|
||||
{
|
||||
if (!str.empty())
|
||||
str += " ";
|
||||
if (!GetOp(pc, opcode, vch))
|
||||
{
|
||||
str += "[error]";
|
||||
return str;
|
||||
}
|
||||
if (0 <= opcode && opcode <= OP_PUSHDATA4)
|
||||
str += ValueString(vch);
|
||||
else
|
||||
str += GetOpName(opcode);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
void print() const
|
||||
{
|
||||
printf("%s\n", ToString().c_str());
|
||||
}
|
||||
|
||||
CScriptID GetID() const
|
||||
{
|
||||
return CScriptID(Hash160(*this));
|
||||
}
|
||||
};
|
||||
|
||||
/** Compact serializer for scripts.
|
||||
*
|
||||
* It detects common cases and encodes them much more efficiently.
|
||||
* 3 special cases are defined:
|
||||
* * Pay to pubkey hash (encoded as 21 bytes)
|
||||
* * Pay to script hash (encoded as 21 bytes)
|
||||
* * Pay to pubkey starting with 0x02, 0x03 or 0x04 (encoded as 33 bytes)
|
||||
*
|
||||
* Other scripts up to 121 bytes require 1 byte + script length. Above
|
||||
* that, scripts up to 16505 bytes require 2 bytes + script length.
|
||||
*/
|
||||
class CScriptCompressor
|
||||
{
|
||||
private:
|
||||
// make this static for now (there are only 6 special scripts defined)
|
||||
// this can potentially be extended together with a new nVersion for
|
||||
// transactions, in which case this value becomes dependent on nVersion
|
||||
// and nHeight of the enclosing transaction.
|
||||
static const unsigned int nSpecialScripts = 6;
|
||||
|
||||
CScript &script;
|
||||
protected:
|
||||
// These check for scripts for which a special case with a shorter encoding is defined.
|
||||
// They are implemented separately from the CScript test, as these test for exact byte
|
||||
// sequence correspondences, and are more strict. For example, IsToPubKey also verifies
|
||||
// whether the public key is valid (as invalid ones cannot be represented in compressed
|
||||
// form).
|
||||
bool IsToKeyID(CKeyID &hash) const;
|
||||
bool IsToScriptID(CScriptID &hash) const;
|
||||
bool IsToPubKey(std::vector<unsigned char> &pubkey) const;
|
||||
|
||||
bool Compress(std::vector<unsigned char> &out) const;
|
||||
unsigned int GetSpecialSize(unsigned int nSize) const;
|
||||
bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
|
||||
public:
|
||||
CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
|
||||
|
||||
unsigned int GetSerializeSize(int nType, int nVersion) const {
|
||||
std::vector<unsigned char> compr;
|
||||
if (Compress(compr))
|
||||
return compr.size();
|
||||
unsigned int nSize = script.size() + nSpecialScripts;
|
||||
return script.size() + VARINT(nSize).GetSerializeSize(nType, nVersion);
|
||||
}
|
||||
|
||||
template<typename Stream>
|
||||
void Serialize(Stream &s, int nType, int nVersion) const {
|
||||
std::vector<unsigned char> compr;
|
||||
if (Compress(compr)) {
|
||||
s << CFlatData(&compr[0], &compr[compr.size()]);
|
||||
return;
|
||||
}
|
||||
unsigned int nSize = script.size() + nSpecialScripts;
|
||||
s << VARINT(nSize);
|
||||
s << CFlatData(&script[0], &script[script.size()]);
|
||||
}
|
||||
|
||||
template<typename Stream>
|
||||
void Unserialize(Stream &s, int nType, int nVersion) {
|
||||
unsigned int nSize = 0;
|
||||
s >> VARINT(nSize);
|
||||
if (nSize < nSpecialScripts) {
|
||||
std::vector<unsigned char> vch(GetSpecialSize(nSize), 0x00);
|
||||
s >> REF(CFlatData(&vch[0], &vch[vch.size()]));
|
||||
Decompress(nSize, vch);
|
||||
return;
|
||||
}
|
||||
nSize -= nSpecialScripts;
|
||||
script.resize(nSize);
|
||||
s >> REF(CFlatData(&script[0], &script[script.size()]));
|
||||
}
|
||||
};
|
||||
|
||||
bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
|
||||
bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);
|
||||
|
||||
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
|
||||
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
|
||||
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
|
||||
bool IsStandard(const CScript& scriptPubKey);
|
||||
bool IsMine(const CKeyStore& keystore, const CScript& scriptPubKey);
|
||||
bool IsMine(const CKeyStore& keystore, const CTxDestination &dest);
|
||||
bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet);
|
||||
bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet);
|
||||
bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
|
||||
bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
|
||||
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
|
||||
|
||||
// Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
|
||||
// combine them intelligently and return the result.
|
||||
CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2);
|
||||
|
||||
#endif
|
1374
src/serialize.h
1374
src/serialize.h
File diff suppressed because it is too large
Load Diff
128
src/sync.cpp
128
src/sync.cpp
|
@ -1,128 +0,0 @@
|
|||
// Copyright (c) 2011-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "sync.h"
|
||||
#include "util.h"
|
||||
|
||||
#include <boost/foreach.hpp>
|
||||
|
||||
#ifdef DEBUG_LOCKCONTENTION
|
||||
void PrintLockContention(const char* pszName, const char* pszFile, int nLine)
|
||||
{
|
||||
printf("LOCKCONTENTION: %s\n", pszName);
|
||||
printf("Locker: %s:%d\n", pszFile, nLine);
|
||||
}
|
||||
#endif /* DEBUG_LOCKCONTENTION */
|
||||
|
||||
#ifdef DEBUG_LOCKORDER
|
||||
//
|
||||
// Early deadlock detection.
|
||||
// Problem being solved:
|
||||
// Thread 1 locks A, then B, then C
|
||||
// Thread 2 locks D, then C, then A
|
||||
// --> may result in deadlock between the two threads, depending on when they run.
|
||||
// Solution implemented here:
|
||||
// Keep track of pairs of locks: (A before B), (A before C), etc.
|
||||
// Complain if any thread tries to lock in a different order.
|
||||
//
|
||||
|
||||
struct CLockLocation
|
||||
{
|
||||
CLockLocation(const char* pszName, const char* pszFile, int nLine)
|
||||
{
|
||||
mutexName = pszName;
|
||||
sourceFile = pszFile;
|
||||
sourceLine = nLine;
|
||||
}
|
||||
|
||||
std::string ToString() const
|
||||
{
|
||||
return mutexName+" "+sourceFile+":"+itostr(sourceLine);
|
||||
}
|
||||
|
||||
private:
|
||||
std::string mutexName;
|
||||
std::string sourceFile;
|
||||
int sourceLine;
|
||||
};
|
||||
|
||||
typedef std::vector< std::pair<void*, CLockLocation> > LockStack;
|
||||
|
||||
static boost::mutex dd_mutex;
|
||||
static std::map<std::pair<void*, void*>, LockStack> lockorders;
|
||||
static boost::thread_specific_ptr<LockStack> lockstack;
|
||||
|
||||
|
||||
static void potential_deadlock_detected(const std::pair<void*, void*>& mismatch, const LockStack& s1, const LockStack& s2)
|
||||
{
|
||||
printf("POTENTIAL DEADLOCK DETECTED\n");
|
||||
printf("Previous lock order was:\n");
|
||||
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s2)
|
||||
{
|
||||
if (i.first == mismatch.first) printf(" (1)");
|
||||
if (i.first == mismatch.second) printf(" (2)");
|
||||
printf(" %s\n", i.second.ToString().c_str());
|
||||
}
|
||||
printf("Current lock order is:\n");
|
||||
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, s1)
|
||||
{
|
||||
if (i.first == mismatch.first) printf(" (1)");
|
||||
if (i.first == mismatch.second) printf(" (2)");
|
||||
printf(" %s\n", i.second.ToString().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
static void push_lock(void* c, const CLockLocation& locklocation, bool fTry)
|
||||
{
|
||||
if (lockstack.get() == NULL)
|
||||
lockstack.reset(new LockStack);
|
||||
|
||||
if (fDebug) printf("Locking: %s\n", locklocation.ToString().c_str());
|
||||
dd_mutex.lock();
|
||||
|
||||
(*lockstack).push_back(std::make_pair(c, locklocation));
|
||||
|
||||
if (!fTry) {
|
||||
BOOST_FOREACH(const PAIRTYPE(void*, CLockLocation)& i, (*lockstack)) {
|
||||
if (i.first == c) break;
|
||||
|
||||
std::pair<void*, void*> p1 = std::make_pair(i.first, c);
|
||||
if (lockorders.count(p1))
|
||||
continue;
|
||||
lockorders[p1] = (*lockstack);
|
||||
|
||||
std::pair<void*, void*> p2 = std::make_pair(c, i.first);
|
||||
if (lockorders.count(p2))
|
||||
{
|
||||
potential_deadlock_detected(p1, lockorders[p2], lockorders[p1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
dd_mutex.unlock();
|
||||
}
|
||||
|
||||
static void pop_lock()
|
||||
{
|
||||
if (fDebug)
|
||||
{
|
||||
const CLockLocation& locklocation = (*lockstack).rbegin()->second;
|
||||
printf("Unlocked: %s\n", locklocation.ToString().c_str());
|
||||
}
|
||||
dd_mutex.lock();
|
||||
(*lockstack).pop_back();
|
||||
dd_mutex.unlock();
|
||||
}
|
||||
|
||||
void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry)
|
||||
{
|
||||
push_lock(cs, CLockLocation(pszName, pszFile, nLine), fTry);
|
||||
}
|
||||
|
||||
void LeaveCritical()
|
||||
{
|
||||
pop_lock();
|
||||
}
|
||||
|
||||
#endif /* DEBUG_LOCKORDER */
|
269
src/txdb.cpp
269
src/txdb.cpp
|
@ -1,269 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2011-2013 PPCoin developers
|
||||
// Copyright (c) 2013 The Primecoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "txdb.h"
|
||||
#include "main.h"
|
||||
#include "hash.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
void static BatchWriteCoins(CLevelDBBatch &batch, const uint256 &hash, const CCoins &coins) {
|
||||
if (coins.IsPruned())
|
||||
batch.Erase(make_pair('c', hash));
|
||||
else
|
||||
batch.Write(make_pair('c', hash), coins);
|
||||
}
|
||||
|
||||
void static BatchWriteHashBestChain(CLevelDBBatch &batch, const uint256 &hash) {
|
||||
batch.Write('B', hash);
|
||||
}
|
||||
|
||||
CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) {
|
||||
}
|
||||
|
||||
bool CCoinsViewDB::GetCoins(const uint256 &txid, CCoins &coins) {
|
||||
return db.Read(make_pair('c', txid), coins);
|
||||
}
|
||||
|
||||
bool CCoinsViewDB::SetCoins(const uint256 &txid, const CCoins &coins) {
|
||||
CLevelDBBatch batch;
|
||||
BatchWriteCoins(batch, txid, coins);
|
||||
return db.WriteBatch(batch);
|
||||
}
|
||||
|
||||
bool CCoinsViewDB::HaveCoins(const uint256 &txid) {
|
||||
return db.Exists(make_pair('c', txid));
|
||||
}
|
||||
|
||||
CBlockIndex *CCoinsViewDB::GetBestBlock() {
|
||||
uint256 hashBestChain;
|
||||
if (!db.Read('B', hashBestChain))
|
||||
return NULL;
|
||||
std::map<uint256, CBlockIndex*>::iterator it = mapBlockIndex.find(hashBestChain);
|
||||
if (it == mapBlockIndex.end())
|
||||
return NULL;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
bool CCoinsViewDB::SetBestBlock(CBlockIndex *pindex) {
|
||||
CLevelDBBatch batch;
|
||||
BatchWriteHashBestChain(batch, pindex->GetBlockHash());
|
||||
return db.WriteBatch(batch);
|
||||
}
|
||||
|
||||
bool CCoinsViewDB::BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex) {
|
||||
printf("Committing %u changed transactions to coin database...\n", (unsigned int)mapCoins.size());
|
||||
|
||||
CLevelDBBatch batch;
|
||||
for (std::map<uint256, CCoins>::const_iterator it = mapCoins.begin(); it != mapCoins.end(); it++)
|
||||
BatchWriteCoins(batch, it->first, it->second);
|
||||
if (pindex)
|
||||
BatchWriteHashBestChain(batch, pindex->GetBlockHash());
|
||||
|
||||
return db.WriteBatch(batch);
|
||||
}
|
||||
|
||||
CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDB(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) {
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
|
||||
{
|
||||
return Write(make_pair('b', blockindex.GetBlockHash()), blockindex);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadBestInvalidWork(CBigNum& bnBestInvalidWork)
|
||||
{
|
||||
return Read('I', bnBestInvalidWork);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteBestInvalidWork(const CBigNum& bnBestInvalidWork)
|
||||
{
|
||||
return Write('I', bnBestInvalidWork);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo &info) {
|
||||
return Write(make_pair('f', nFile), info);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo &info) {
|
||||
return Read(make_pair('f', nFile), info);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteLastBlockFile(int nFile) {
|
||||
return Write('l', nFile);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteReindexing(bool fReindexing) {
|
||||
if (fReindexing)
|
||||
return Write('R', '1');
|
||||
else
|
||||
return Erase('R');
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadReindexing(bool &fReindexing) {
|
||||
fReindexing = Exists('R');
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadLastBlockFile(int &nFile) {
|
||||
return Read('l', nFile);
|
||||
}
|
||||
|
||||
bool CCoinsViewDB::GetStats(CCoinsStats &stats) {
|
||||
leveldb::Iterator *pcursor = db.NewIterator();
|
||||
pcursor->SeekToFirst();
|
||||
|
||||
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
|
||||
stats.hashBlock = GetBestBlock()->GetBlockHash();
|
||||
ss << stats.hashBlock;
|
||||
int64 nTotalAmount = 0;
|
||||
while (pcursor->Valid()) {
|
||||
boost::this_thread::interruption_point();
|
||||
try {
|
||||
leveldb::Slice slKey = pcursor->key();
|
||||
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
|
||||
char chType;
|
||||
ssKey >> chType;
|
||||
if (chType == 'c') {
|
||||
leveldb::Slice slValue = pcursor->value();
|
||||
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
|
||||
CCoins coins;
|
||||
ssValue >> coins;
|
||||
uint256 txhash;
|
||||
ssKey >> txhash;
|
||||
ss << txhash;
|
||||
ss << VARINT(coins.nVersion);
|
||||
ss << (coins.fCoinBase ? 'c' : 'n');
|
||||
ss << VARINT(coins.nHeight);
|
||||
stats.nTransactions++;
|
||||
for (unsigned int i=0; i<coins.vout.size(); i++) {
|
||||
const CTxOut &out = coins.vout[i];
|
||||
if (!out.IsNull()) {
|
||||
stats.nTransactionOutputs++;
|
||||
ss << VARINT(i+1);
|
||||
ss << out;
|
||||
nTotalAmount += out.nValue;
|
||||
}
|
||||
}
|
||||
stats.nSerializedSize += 32 + slValue.size();
|
||||
ss << VARINT(0);
|
||||
}
|
||||
pcursor->Next();
|
||||
} catch (std::exception &e) {
|
||||
return error("%s() : deserialize error", __PRETTY_FUNCTION__);
|
||||
}
|
||||
}
|
||||
delete pcursor;
|
||||
stats.nHeight = GetBestBlock()->nHeight;
|
||||
stats.hashSerialized = ss.GetHash();
|
||||
stats.nTotalAmount = nTotalAmount;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadTxIndex(const uint256 &txid, CDiskTxPos &pos) {
|
||||
return Read(make_pair('t', txid), pos);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >&vect) {
|
||||
CLevelDBBatch batch;
|
||||
for (std::vector<std::pair<uint256,CDiskTxPos> >::const_iterator it=vect.begin(); it!=vect.end(); it++)
|
||||
batch.Write(make_pair('t', it->first), it->second);
|
||||
return WriteBatch(batch);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteFlag(const std::string &name, bool fValue) {
|
||||
return Write(std::make_pair('F', name), fValue ? '1' : '0');
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadFlag(const std::string &name, bool &fValue) {
|
||||
char ch;
|
||||
if (!Read(std::make_pair('F', name), ch))
|
||||
return false;
|
||||
fValue = ch == '1';
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::LoadBlockIndexGuts()
|
||||
{
|
||||
leveldb::Iterator *pcursor = NewIterator();
|
||||
|
||||
CDataStream ssKeySet(SER_DISK, CLIENT_VERSION);
|
||||
ssKeySet << make_pair('b', uint256(0));
|
||||
pcursor->Seek(ssKeySet.str());
|
||||
|
||||
// Load mapBlockIndex
|
||||
while (pcursor->Valid()) {
|
||||
boost::this_thread::interruption_point();
|
||||
try {
|
||||
leveldb::Slice slKey = pcursor->key();
|
||||
CDataStream ssKey(slKey.data(), slKey.data()+slKey.size(), SER_DISK, CLIENT_VERSION);
|
||||
char chType;
|
||||
ssKey >> chType;
|
||||
if (chType == 'b') {
|
||||
leveldb::Slice slValue = pcursor->value();
|
||||
CDataStream ssValue(slValue.data(), slValue.data()+slValue.size(), SER_DISK, CLIENT_VERSION);
|
||||
CDiskBlockIndex diskindex;
|
||||
ssValue >> diskindex;
|
||||
|
||||
// Construct block index object
|
||||
CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash());
|
||||
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
|
||||
pindexNew->nPrimeChainType = diskindex.nPrimeChainType;
|
||||
pindexNew->nPrimeChainLength = diskindex.nPrimeChainLength;
|
||||
pindexNew->nMoneySupply = diskindex.nMoneySupply;
|
||||
pindexNew->nHeight = diskindex.nHeight;
|
||||
pindexNew->nFile = diskindex.nFile;
|
||||
pindexNew->nDataPos = diskindex.nDataPos;
|
||||
pindexNew->nUndoPos = diskindex.nUndoPos;
|
||||
pindexNew->nVersion = diskindex.nVersion;
|
||||
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
|
||||
pindexNew->nTime = diskindex.nTime;
|
||||
pindexNew->nBits = diskindex.nBits;
|
||||
pindexNew->nNonce = diskindex.nNonce;
|
||||
pindexNew->nStatus = diskindex.nStatus;
|
||||
pindexNew->nTx = diskindex.nTx;
|
||||
|
||||
// Watch for genesis block
|
||||
if (pindexGenesisBlock == NULL && diskindex.GetBlockHash() == hashGenesisBlock)
|
||||
pindexGenesisBlock = pindexNew;
|
||||
|
||||
if (!pindexNew->CheckIndex())
|
||||
return error("LoadBlockIndex() : CheckIndex failed: %s", pindexNew->ToString().c_str());
|
||||
|
||||
pcursor->Next();
|
||||
} else {
|
||||
break; // if shutdown requested or finished loading block index
|
||||
}
|
||||
} catch (std::exception &e) {
|
||||
return error("%s() : deserialize error", __PRETTY_FUNCTION__);
|
||||
}
|
||||
}
|
||||
delete pcursor;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
|
||||
{
|
||||
return Read(string("hashSyncCheckpoint"), hashCheckpoint);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
|
||||
{
|
||||
return Write(string("hashSyncCheckpoint"), hashCheckpoint);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::ReadCheckpointPubKey(string& strPubKey)
|
||||
{
|
||||
return Read(string("strCheckpointPubKey"), strPubKey);
|
||||
}
|
||||
|
||||
bool CBlockTreeDB::WriteCheckpointPubKey(const string& strPubKey)
|
||||
{
|
||||
return Write(string("strCheckpointPubKey"), strPubKey);
|
||||
}
|
||||
|
61
src/txdb.h
61
src/txdb.h
|
@ -1,61 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2011-2013 PPCoin developers
|
||||
// Copyright (c) 2013 Primecoin developers
|
||||
// Distributed under conditional MIT/X11 software license,
|
||||
// see the accompanying file COPYING.
|
||||
#ifndef BITCOIN_TXDB_LEVELDB_H
|
||||
#define BITCOIN_TXDB_LEVELDB_H
|
||||
|
||||
#include "main.h"
|
||||
#include "leveldb.h"
|
||||
|
||||
/** CCoinsView backed by the LevelDB coin database (chainstate/) */
|
||||
class CCoinsViewDB : public CCoinsView
|
||||
{
|
||||
protected:
|
||||
CLevelDB db;
|
||||
public:
|
||||
CCoinsViewDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
|
||||
|
||||
bool GetCoins(const uint256 &txid, CCoins &coins);
|
||||
bool SetCoins(const uint256 &txid, const CCoins &coins);
|
||||
bool HaveCoins(const uint256 &txid);
|
||||
CBlockIndex *GetBestBlock();
|
||||
bool SetBestBlock(CBlockIndex *pindex);
|
||||
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
|
||||
bool GetStats(CCoinsStats &stats);
|
||||
};
|
||||
|
||||
/** Access to the block database (blocks/index/) */
|
||||
class CBlockTreeDB : public CLevelDB
|
||||
{
|
||||
public:
|
||||
CBlockTreeDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
|
||||
private:
|
||||
CBlockTreeDB(const CBlockTreeDB&);
|
||||
void operator=(const CBlockTreeDB&);
|
||||
public:
|
||||
bool WriteBlockIndex(const CDiskBlockIndex& blockindex);
|
||||
bool ReadBestInvalidWork(CBigNum& bnBestInvalidWork);
|
||||
bool WriteBestInvalidWork(const CBigNum& bnBestInvalidWork);
|
||||
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo);
|
||||
bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo);
|
||||
bool ReadLastBlockFile(int &nFile);
|
||||
bool WriteLastBlockFile(int nFile);
|
||||
bool WriteReindexing(bool fReindex);
|
||||
bool ReadReindexing(bool &fReindex);
|
||||
bool ReadTxIndex(const uint256 &txid, CDiskTxPos &pos);
|
||||
bool WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> > &list);
|
||||
bool WriteFlag(const std::string &name, bool fValue);
|
||||
bool ReadFlag(const std::string &name, bool &fValue);
|
||||
bool LoadBlockIndexGuts();
|
||||
|
||||
// ppcoin sync checkpoint related data
|
||||
bool ReadSyncCheckpoint(uint256& hashCheckpoint);
|
||||
bool WriteSyncCheckpoint(uint256 hashCheckpoint);
|
||||
bool ReadCheckpointPubKey(std::string& strPubKey);
|
||||
bool WriteCheckpointPubKey(const std::string& strPubKey);
|
||||
};
|
||||
|
||||
#endif // BITCOIN_TXDB_LEVELDB_H
|
|
@ -1,110 +0,0 @@
|
|||
// Copyright (c) 2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_UI_INTERFACE_H
|
||||
#define BITCOIN_UI_INTERFACE_H
|
||||
|
||||
#include <string>
|
||||
#include "util.h" // for int64
|
||||
#include <boost/signals2/signal.hpp>
|
||||
#include <boost/signals2/last_value.hpp>
|
||||
|
||||
class CBasicKeyStore;
|
||||
class CWallet;
|
||||
class uint256;
|
||||
|
||||
/** General change type (added, updated, removed). */
|
||||
enum ChangeType
|
||||
{
|
||||
CT_NEW,
|
||||
CT_UPDATED,
|
||||
CT_DELETED
|
||||
};
|
||||
|
||||
/** Signals for UI communication. */
|
||||
class CClientUIInterface
|
||||
{
|
||||
public:
|
||||
/** Flags for CClientUIInterface::ThreadSafeMessageBox */
|
||||
enum MessageBoxFlags
|
||||
{
|
||||
ICON_INFORMATION = 0,
|
||||
ICON_WARNING = (1U << 0),
|
||||
ICON_ERROR = (1U << 1),
|
||||
/**
|
||||
* Mask of all available icons in CClientUIInterface::MessageBoxFlags
|
||||
* This needs to be updated, when icons are changed there!
|
||||
*/
|
||||
ICON_MASK = (ICON_INFORMATION | ICON_WARNING | ICON_ERROR),
|
||||
|
||||
/** These values are taken from qmessagebox.h "enum StandardButton" to be directly usable */
|
||||
BTN_OK = 0x00000400U, // QMessageBox::Ok
|
||||
BTN_YES = 0x00004000U, // QMessageBox::Yes
|
||||
BTN_NO = 0x00010000U, // QMessageBox::No
|
||||
BTN_ABORT = 0x00040000U, // QMessageBox::Abort
|
||||
BTN_RETRY = 0x00080000U, // QMessageBox::Retry
|
||||
BTN_IGNORE = 0x00100000U, // QMessageBox::Ignore
|
||||
BTN_CLOSE = 0x00200000U, // QMessageBox::Close
|
||||
BTN_CANCEL = 0x00400000U, // QMessageBox::Cancel
|
||||
BTN_DISCARD = 0x00800000U, // QMessageBox::Discard
|
||||
BTN_HELP = 0x01000000U, // QMessageBox::Help
|
||||
BTN_APPLY = 0x02000000U, // QMessageBox::Apply
|
||||
BTN_RESET = 0x04000000U, // QMessageBox::Reset
|
||||
/**
|
||||
* Mask of all available buttons in CClientUIInterface::MessageBoxFlags
|
||||
* This needs to be updated, when buttons are changed there!
|
||||
*/
|
||||
BTN_MASK = (BTN_OK | BTN_YES | BTN_NO | BTN_ABORT | BTN_RETRY | BTN_IGNORE |
|
||||
BTN_CLOSE | BTN_CANCEL | BTN_DISCARD | BTN_HELP | BTN_APPLY | BTN_RESET),
|
||||
|
||||
/** Force blocking, modal message box dialog (not just OS notification) */
|
||||
MODAL = 0x10000000U,
|
||||
|
||||
/** Predefined combinations for certain default usage cases */
|
||||
MSG_INFORMATION = ICON_INFORMATION,
|
||||
MSG_WARNING = (ICON_WARNING | BTN_OK | MODAL),
|
||||
MSG_ERROR = (ICON_ERROR | BTN_OK | MODAL)
|
||||
};
|
||||
|
||||
/** Show message box. */
|
||||
boost::signals2::signal<bool (const std::string& message, const std::string& caption, unsigned int style), boost::signals2::last_value<bool> > ThreadSafeMessageBox;
|
||||
|
||||
/** Ask the user whether they want to pay a fee or not. */
|
||||
boost::signals2::signal<bool (int64 nFeeRequired), boost::signals2::last_value<bool> > ThreadSafeAskFee;
|
||||
|
||||
/** Handle a URL passed at the command line. */
|
||||
boost::signals2::signal<void (const std::string& strURI)> ThreadSafeHandleURI;
|
||||
|
||||
/** Progress message during initialization. */
|
||||
boost::signals2::signal<void (const std::string &message)> InitMessage;
|
||||
|
||||
/** Translate a message to the native language of the user. */
|
||||
boost::signals2::signal<std::string (const char* psz)> Translate;
|
||||
|
||||
/** Block chain changed. */
|
||||
boost::signals2::signal<void ()> NotifyBlocksChanged;
|
||||
|
||||
/** Number of network connections changed. */
|
||||
boost::signals2::signal<void (int newNumConnections)> NotifyNumConnectionsChanged;
|
||||
|
||||
/**
|
||||
* New, updated or cancelled alert.
|
||||
* @note called with lock cs_mapAlerts held.
|
||||
*/
|
||||
boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged;
|
||||
};
|
||||
|
||||
extern CClientUIInterface uiInterface;
|
||||
|
||||
/**
|
||||
* Translation function: Call Translate signal on UI interface, which returns a boost::optional result.
|
||||
* If no translation slot is registered, nothing is returned, and simply return the input.
|
||||
*/
|
||||
inline std::string _(const char* psz)
|
||||
{
|
||||
boost::optional<std::string> rv = uiInterface.Translate(psz);
|
||||
return rv ? (*rv) : psz;
|
||||
}
|
||||
|
||||
#endif
|
57
src/util.cpp
57
src/util.cpp
|
@ -15,9 +15,8 @@
|
|||
#endif
|
||||
|
||||
#include "util.h"
|
||||
#include "sync.h"
|
||||
#include "version.h"
|
||||
#include "ui_interface.h"
|
||||
#include "allocators.h"
|
||||
#include <boost/algorithm/string/join.hpp>
|
||||
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
|
||||
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
|
||||
|
@ -68,6 +67,7 @@ namespace boost {
|
|||
#endif
|
||||
|
||||
using namespace std;
|
||||
using namespace boost;
|
||||
|
||||
map<string, string> mapArgs;
|
||||
map<string, vector<string> > mapMultiArgs;
|
||||
|
@ -1302,59 +1302,6 @@ int64 GetAdjustedTime()
|
|||
return GetTime() + GetTimeOffset();
|
||||
}
|
||||
|
||||
void AddTimeData(const CNetAddr& ip, int64 nTime)
|
||||
{
|
||||
int64 nOffsetSample = nTime - GetTime();
|
||||
|
||||
// Ignore duplicates
|
||||
static set<CNetAddr> setKnown;
|
||||
if (!setKnown.insert(ip).second)
|
||||
return;
|
||||
|
||||
// Add data
|
||||
vTimeOffsets.input(nOffsetSample);
|
||||
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
|
||||
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
|
||||
{
|
||||
int64 nMedian = vTimeOffsets.median();
|
||||
std::vector<int64> vSorted = vTimeOffsets.sorted();
|
||||
// Only let other nodes change our time by so much
|
||||
if (abs64(nMedian) < 70 * 60)
|
||||
{
|
||||
nTimeOffset = nMedian;
|
||||
}
|
||||
else
|
||||
{
|
||||
nTimeOffset = 0;
|
||||
|
||||
static bool fDone;
|
||||
if (!fDone)
|
||||
{
|
||||
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
|
||||
bool fMatch = false;
|
||||
BOOST_FOREACH(int64 nOffset, vSorted)
|
||||
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
|
||||
fMatch = true;
|
||||
|
||||
if (!fMatch)
|
||||
{
|
||||
fDone = true;
|
||||
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Primecoin will not work properly.");
|
||||
strMiscWarning = strMessage;
|
||||
printf("*** %s\n", strMessage.c_str());
|
||||
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (fDebug) {
|
||||
BOOST_FOREACH(int64 n, vSorted)
|
||||
printf("%+"PRI64d" ", n);
|
||||
printf("| ");
|
||||
}
|
||||
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t insecure_rand_Rz = 11;
|
||||
uint32_t insecure_rand_Rw = 11;
|
||||
void seed_insecure_rand(bool fDeterministic)
|
||||
|
|
|
@ -7,6 +7,7 @@
|
|||
#define BITCOIN_UTIL_H
|
||||
|
||||
#include "uint256.h"
|
||||
#include "sync.h"
|
||||
|
||||
#include <stdarg.h>
|
||||
|
||||
|
|
1886
src/wallet.cpp
1886
src/wallet.cpp
File diff suppressed because it is too large
Load Diff
862
src/wallet.h
862
src/wallet.h
|
@ -1,862 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_WALLET_H
|
||||
#define BITCOIN_WALLET_H
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "main.h"
|
||||
#include "key.h"
|
||||
#include "keystore.h"
|
||||
#include "script.h"
|
||||
#include "ui_interface.h"
|
||||
#include "util.h"
|
||||
#include "walletdb.h"
|
||||
|
||||
class CAccountingEntry;
|
||||
class CWalletTx;
|
||||
class CReserveKey;
|
||||
class COutput;
|
||||
|
||||
/** (client) version numbers for particular wallet features */
|
||||
enum WalletFeature
|
||||
{
|
||||
FEATURE_BASE = 10500, // the earliest version new wallets supports (only useful for getinfo's clientversion output)
|
||||
|
||||
FEATURE_WALLETCRYPT = 40000, // wallet encryption
|
||||
FEATURE_COMPRPUBKEY = 60000, // compressed public keys
|
||||
|
||||
FEATURE_LATEST = 60000
|
||||
};
|
||||
|
||||
|
||||
/** A key pool entry */
|
||||
class CKeyPool
|
||||
{
|
||||
public:
|
||||
int64 nTime;
|
||||
CPubKey vchPubKey;
|
||||
|
||||
CKeyPool()
|
||||
{
|
||||
nTime = GetTime();
|
||||
}
|
||||
|
||||
CKeyPool(const CPubKey& vchPubKeyIn)
|
||||
{
|
||||
nTime = GetTime();
|
||||
vchPubKey = vchPubKeyIn;
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
if (!(nType & SER_GETHASH))
|
||||
READWRITE(nVersion);
|
||||
READWRITE(nTime);
|
||||
READWRITE(vchPubKey);
|
||||
)
|
||||
};
|
||||
|
||||
/** A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,
|
||||
* and provides the ability to create new transactions.
|
||||
*/
|
||||
class CWallet : public CCryptoKeyStore
|
||||
{
|
||||
private:
|
||||
bool SelectCoins(int64 nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
|
||||
|
||||
CWalletDB *pwalletdbEncryption;
|
||||
|
||||
// the current wallet version: clients below this version are not able to load the wallet
|
||||
int nWalletVersion;
|
||||
|
||||
// the maximum wallet format version: memory-only variable that specifies to what version this wallet may be upgraded
|
||||
int nWalletMaxVersion;
|
||||
|
||||
public:
|
||||
mutable CCriticalSection cs_wallet;
|
||||
|
||||
bool fFileBacked;
|
||||
std::string strWalletFile;
|
||||
|
||||
std::set<int64> setKeyPool;
|
||||
|
||||
|
||||
typedef std::map<unsigned int, CMasterKey> MasterKeyMap;
|
||||
MasterKeyMap mapMasterKeys;
|
||||
unsigned int nMasterKeyMaxID;
|
||||
|
||||
CWallet()
|
||||
{
|
||||
nWalletVersion = FEATURE_BASE;
|
||||
nWalletMaxVersion = FEATURE_BASE;
|
||||
fFileBacked = false;
|
||||
nMasterKeyMaxID = 0;
|
||||
pwalletdbEncryption = NULL;
|
||||
nOrderPosNext = 0;
|
||||
}
|
||||
CWallet(std::string strWalletFileIn)
|
||||
{
|
||||
nWalletVersion = FEATURE_BASE;
|
||||
nWalletMaxVersion = FEATURE_BASE;
|
||||
strWalletFile = strWalletFileIn;
|
||||
fFileBacked = true;
|
||||
nMasterKeyMaxID = 0;
|
||||
pwalletdbEncryption = NULL;
|
||||
nOrderPosNext = 0;
|
||||
}
|
||||
|
||||
std::map<uint256, CWalletTx> mapWallet;
|
||||
int64 nOrderPosNext;
|
||||
std::map<uint256, int> mapRequestCount;
|
||||
|
||||
std::map<CTxDestination, std::string> mapAddressBook;
|
||||
|
||||
CPubKey vchDefaultKey;
|
||||
|
||||
std::set<COutPoint> setLockedCoins;
|
||||
|
||||
// check whether we are allowed to upgrade (or already support) to the named feature
|
||||
bool CanSupportFeature(enum WalletFeature wf) { return nWalletMaxVersion >= wf; }
|
||||
|
||||
void AvailableCoins(std::vector<COutput>& vCoins, bool fOnlyConfirmed=true) const;
|
||||
bool SelectCoinsMinConf(int64 nTargetValue, int nConfMine, int nConfTheirs, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const;
|
||||
bool IsLockedCoin(uint256 hash, unsigned int n) const;
|
||||
void LockCoin(COutPoint& output);
|
||||
void UnlockCoin(COutPoint& output);
|
||||
void UnlockAllCoins();
|
||||
void ListLockedCoins(std::vector<COutPoint>& vOutpts);
|
||||
|
||||
// keystore implementation
|
||||
// Generate a new key
|
||||
CPubKey GenerateNewKey();
|
||||
// Adds a key to the store, and saves it to disk.
|
||||
bool AddKey(const CKey& key);
|
||||
// Adds a key to the store, without saving it to disk (used by LoadWallet)
|
||||
bool LoadKey(const CKey& key) { return CCryptoKeyStore::AddKey(key); }
|
||||
|
||||
bool LoadMinVersion(int nVersion) { nWalletVersion = nVersion; nWalletMaxVersion = std::max(nWalletMaxVersion, nVersion); return true; }
|
||||
|
||||
// Adds an encrypted key to the store, and saves it to disk.
|
||||
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
|
||||
// Adds an encrypted key to the store, without saving it to disk (used by LoadWallet)
|
||||
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
|
||||
bool AddCScript(const CScript& redeemScript);
|
||||
bool LoadCScript(const CScript& redeemScript) { return CCryptoKeyStore::AddCScript(redeemScript); }
|
||||
|
||||
bool Unlock(const SecureString& strWalletPassphrase);
|
||||
bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase);
|
||||
bool EncryptWallet(const SecureString& strWalletPassphrase);
|
||||
|
||||
/** Increment the next transaction order id
|
||||
@return next transaction order id
|
||||
*/
|
||||
int64 IncOrderPosNext(CWalletDB *pwalletdb = NULL);
|
||||
|
||||
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
|
||||
typedef std::multimap<int64, TxPair > TxItems;
|
||||
|
||||
/** Get the wallet's activity log
|
||||
@return multimap of ordered transactions and accounting entries
|
||||
@warning Returned pointers are *only* valid within the scope of passed acentries
|
||||
*/
|
||||
TxItems OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount = "");
|
||||
|
||||
void MarkDirty();
|
||||
bool AddToWallet(const CWalletTx& wtxIn);
|
||||
bool AddToWalletIfInvolvingMe(const uint256 &hash, const CTransaction& tx, const CBlock* pblock, bool fUpdate = false, bool fFindBlock = false);
|
||||
bool EraseFromWallet(uint256 hash);
|
||||
void WalletUpdateSpent(const CTransaction& prevout);
|
||||
int ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate = false);
|
||||
void ReacceptWalletTransactions();
|
||||
void ResendWalletTransactions();
|
||||
int64 GetBalance() const;
|
||||
int64 GetUnconfirmedBalance() const;
|
||||
int64 GetImmatureBalance() const;
|
||||
bool CreateTransaction(const std::vector<std::pair<CScript, int64> >& vecSend,
|
||||
CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
|
||||
bool CreateTransaction(CScript scriptPubKey, int64 nValue,
|
||||
CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, std::string& strFailReason);
|
||||
bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey);
|
||||
std::string SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
|
||||
std::string SendMoneyToDestination(const CTxDestination &address, int64 nValue, CWalletTx& wtxNew, bool fAskFee=false);
|
||||
|
||||
bool NewKeyPool();
|
||||
bool TopUpKeyPool();
|
||||
int64 AddReserveKey(const CKeyPool& keypool);
|
||||
void ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool);
|
||||
void KeepKey(int64 nIndex);
|
||||
void ReturnKey(int64 nIndex);
|
||||
bool GetKeyFromPool(CPubKey &key, bool fAllowReuse=true);
|
||||
int64 GetOldestKeyPoolTime();
|
||||
void GetAllReserveKeys(std::set<CKeyID>& setAddress);
|
||||
|
||||
std::set< std::set<CTxDestination> > GetAddressGroupings();
|
||||
std::map<CTxDestination, int64> GetAddressBalances();
|
||||
|
||||
bool IsMine(const CTxIn& txin) const;
|
||||
int64 GetDebit(const CTxIn& txin) const;
|
||||
bool IsMine(const CTxOut& txout) const
|
||||
{
|
||||
return ::IsMine(*this, txout.scriptPubKey);
|
||||
}
|
||||
int64 GetCredit(const CTxOut& txout) const
|
||||
{
|
||||
if (!MoneyRange(txout.nValue))
|
||||
throw std::runtime_error("CWallet::GetCredit() : value out of range");
|
||||
return (IsMine(txout) ? txout.nValue : 0);
|
||||
}
|
||||
bool IsChange(const CTxOut& txout) const;
|
||||
int64 GetChange(const CTxOut& txout) const
|
||||
{
|
||||
if (!MoneyRange(txout.nValue))
|
||||
throw std::runtime_error("CWallet::GetChange() : value out of range");
|
||||
return (IsChange(txout) ? txout.nValue : 0);
|
||||
}
|
||||
bool IsMine(const CTransaction& tx) const
|
||||
{
|
||||
BOOST_FOREACH(const CTxOut& txout, tx.vout)
|
||||
if (IsMine(txout))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
bool IsFromMe(const CTransaction& tx) const
|
||||
{
|
||||
return (GetDebit(tx) > 0);
|
||||
}
|
||||
int64 GetDebit(const CTransaction& tx) const
|
||||
{
|
||||
int64 nDebit = 0;
|
||||
BOOST_FOREACH(const CTxIn& txin, tx.vin)
|
||||
{
|
||||
nDebit += GetDebit(txin);
|
||||
if (!MoneyRange(nDebit))
|
||||
throw std::runtime_error("CWallet::GetDebit() : value out of range");
|
||||
}
|
||||
return nDebit;
|
||||
}
|
||||
int64 GetCredit(const CTransaction& tx) const
|
||||
{
|
||||
int64 nCredit = 0;
|
||||
BOOST_FOREACH(const CTxOut& txout, tx.vout)
|
||||
{
|
||||
nCredit += GetCredit(txout);
|
||||
if (!MoneyRange(nCredit))
|
||||
throw std::runtime_error("CWallet::GetCredit() : value out of range");
|
||||
}
|
||||
return nCredit;
|
||||
}
|
||||
int64 GetChange(const CTransaction& tx) const
|
||||
{
|
||||
int64 nChange = 0;
|
||||
BOOST_FOREACH(const CTxOut& txout, tx.vout)
|
||||
{
|
||||
nChange += GetChange(txout);
|
||||
if (!MoneyRange(nChange))
|
||||
throw std::runtime_error("CWallet::GetChange() : value out of range");
|
||||
}
|
||||
return nChange;
|
||||
}
|
||||
void SetBestChain(const CBlockLocator& loc);
|
||||
|
||||
DBErrors LoadWallet(bool& fFirstRunRet);
|
||||
|
||||
bool SetAddressBookName(const CTxDestination& address, const std::string& strName);
|
||||
|
||||
bool DelAddressBookName(const CTxDestination& address);
|
||||
|
||||
void UpdatedTransaction(const uint256 &hashTx);
|
||||
|
||||
void PrintWallet(const CBlock& block);
|
||||
|
||||
void Inventory(const uint256 &hash)
|
||||
{
|
||||
{
|
||||
LOCK(cs_wallet);
|
||||
std::map<uint256, int>::iterator mi = mapRequestCount.find(hash);
|
||||
if (mi != mapRequestCount.end())
|
||||
(*mi).second++;
|
||||
}
|
||||
}
|
||||
|
||||
int GetKeyPoolSize()
|
||||
{
|
||||
return setKeyPool.size();
|
||||
}
|
||||
|
||||
bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx);
|
||||
|
||||
bool SetDefaultKey(const CPubKey &vchPubKey);
|
||||
|
||||
// signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVersion if those are lower
|
||||
bool SetMinVersion(enum WalletFeature, CWalletDB* pwalletdbIn = NULL, bool fExplicit = false);
|
||||
|
||||
// change which version we're allowed to upgrade to (note that this does not immediately imply upgrading to that format)
|
||||
bool SetMaxVersion(int nVersion);
|
||||
|
||||
// get the current wallet format (the oldest client version guaranteed to understand this wallet)
|
||||
int GetVersion() { return nWalletVersion; }
|
||||
|
||||
/** Address book entry changed.
|
||||
* @note called with lock cs_wallet held.
|
||||
*/
|
||||
boost::signals2::signal<void (CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)> NotifyAddressBookChanged;
|
||||
|
||||
/** Wallet transaction added, removed or updated.
|
||||
* @note called with lock cs_wallet held.
|
||||
*/
|
||||
boost::signals2::signal<void (CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged;
|
||||
};
|
||||
|
||||
/** A key allocated from the key pool. */
|
||||
class CReserveKey
|
||||
{
|
||||
protected:
|
||||
CWallet* pwallet;
|
||||
int64 nIndex;
|
||||
CPubKey vchPubKey;
|
||||
public:
|
||||
CReserveKey(CWallet* pwalletIn)
|
||||
{
|
||||
nIndex = -1;
|
||||
pwallet = pwalletIn;
|
||||
}
|
||||
|
||||
~CReserveKey()
|
||||
{
|
||||
ReturnKey();
|
||||
}
|
||||
|
||||
void ReturnKey();
|
||||
bool GetReservedKey(CPubKey &pubkey);
|
||||
void KeepKey();
|
||||
};
|
||||
|
||||
|
||||
typedef std::map<std::string, std::string> mapValue_t;
|
||||
|
||||
|
||||
static void ReadOrderPos(int64& nOrderPos, mapValue_t& mapValue)
|
||||
{
|
||||
if (!mapValue.count("n"))
|
||||
{
|
||||
nOrderPos = -1; // TODO: calculate elsewhere
|
||||
return;
|
||||
}
|
||||
nOrderPos = atoi64(mapValue["n"].c_str());
|
||||
}
|
||||
|
||||
|
||||
static void WriteOrderPos(const int64& nOrderPos, mapValue_t& mapValue)
|
||||
{
|
||||
if (nOrderPos == -1)
|
||||
return;
|
||||
mapValue["n"] = i64tostr(nOrderPos);
|
||||
}
|
||||
|
||||
|
||||
/** A transaction with a bunch of additional info that only the owner cares about.
|
||||
* It includes any unrecorded transactions needed to link it back to the block chain.
|
||||
*/
|
||||
class CWalletTx : public CMerkleTx
|
||||
{
|
||||
private:
|
||||
const CWallet* pwallet;
|
||||
|
||||
public:
|
||||
std::vector<CMerkleTx> vtxPrev;
|
||||
mapValue_t mapValue;
|
||||
std::vector<std::pair<std::string, std::string> > vOrderForm;
|
||||
unsigned int fTimeReceivedIsTxTime;
|
||||
unsigned int nTimeReceived; // time received by this node
|
||||
unsigned int nTimeSmart;
|
||||
char fFromMe;
|
||||
std::string strFromAccount;
|
||||
std::vector<char> vfSpent; // which outputs are already spent
|
||||
int64 nOrderPos; // position in ordered transaction list
|
||||
|
||||
// memory only
|
||||
mutable bool fDebitCached;
|
||||
mutable bool fCreditCached;
|
||||
mutable bool fImmatureCreditCached;
|
||||
mutable bool fAvailableCreditCached;
|
||||
mutable bool fChangeCached;
|
||||
mutable int64 nDebitCached;
|
||||
mutable int64 nCreditCached;
|
||||
mutable int64 nImmatureCreditCached;
|
||||
mutable int64 nAvailableCreditCached;
|
||||
mutable int64 nChangeCached;
|
||||
|
||||
CWalletTx()
|
||||
{
|
||||
Init(NULL);
|
||||
}
|
||||
|
||||
CWalletTx(const CWallet* pwalletIn)
|
||||
{
|
||||
Init(pwalletIn);
|
||||
}
|
||||
|
||||
CWalletTx(const CWallet* pwalletIn, const CMerkleTx& txIn) : CMerkleTx(txIn)
|
||||
{
|
||||
Init(pwalletIn);
|
||||
}
|
||||
|
||||
CWalletTx(const CWallet* pwalletIn, const CTransaction& txIn) : CMerkleTx(txIn)
|
||||
{
|
||||
Init(pwalletIn);
|
||||
}
|
||||
|
||||
void Init(const CWallet* pwalletIn)
|
||||
{
|
||||
pwallet = pwalletIn;
|
||||
vtxPrev.clear();
|
||||
mapValue.clear();
|
||||
vOrderForm.clear();
|
||||
fTimeReceivedIsTxTime = false;
|
||||
nTimeReceived = 0;
|
||||
nTimeSmart = 0;
|
||||
fFromMe = false;
|
||||
strFromAccount.clear();
|
||||
vfSpent.clear();
|
||||
fDebitCached = false;
|
||||
fCreditCached = false;
|
||||
fImmatureCreditCached = false;
|
||||
fAvailableCreditCached = false;
|
||||
fChangeCached = false;
|
||||
nDebitCached = 0;
|
||||
nCreditCached = 0;
|
||||
nImmatureCreditCached = 0;
|
||||
nAvailableCreditCached = 0;
|
||||
nChangeCached = 0;
|
||||
nOrderPos = -1;
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
CWalletTx* pthis = const_cast<CWalletTx*>(this);
|
||||
if (fRead)
|
||||
pthis->Init(NULL);
|
||||
char fSpent = false;
|
||||
|
||||
if (!fRead)
|
||||
{
|
||||
pthis->mapValue["fromaccount"] = pthis->strFromAccount;
|
||||
|
||||
std::string str;
|
||||
BOOST_FOREACH(char f, vfSpent)
|
||||
{
|
||||
str += (f ? '1' : '0');
|
||||
if (f)
|
||||
fSpent = true;
|
||||
}
|
||||
pthis->mapValue["spent"] = str;
|
||||
|
||||
WriteOrderPos(pthis->nOrderPos, pthis->mapValue);
|
||||
|
||||
if (nTimeSmart)
|
||||
pthis->mapValue["timesmart"] = strprintf("%u", nTimeSmart);
|
||||
}
|
||||
|
||||
nSerSize += SerReadWrite(s, *(CMerkleTx*)this, nType, nVersion,ser_action);
|
||||
READWRITE(vtxPrev);
|
||||
READWRITE(mapValue);
|
||||
READWRITE(vOrderForm);
|
||||
READWRITE(fTimeReceivedIsTxTime);
|
||||
READWRITE(nTimeReceived);
|
||||
READWRITE(fFromMe);
|
||||
READWRITE(fSpent);
|
||||
|
||||
if (fRead)
|
||||
{
|
||||
pthis->strFromAccount = pthis->mapValue["fromaccount"];
|
||||
|
||||
if (mapValue.count("spent"))
|
||||
BOOST_FOREACH(char c, pthis->mapValue["spent"])
|
||||
pthis->vfSpent.push_back(c != '0');
|
||||
else
|
||||
pthis->vfSpent.assign(vout.size(), fSpent);
|
||||
|
||||
ReadOrderPos(pthis->nOrderPos, pthis->mapValue);
|
||||
|
||||
pthis->nTimeSmart = mapValue.count("timesmart") ? (unsigned int)atoi64(pthis->mapValue["timesmart"]) : 0;
|
||||
}
|
||||
|
||||
pthis->mapValue.erase("fromaccount");
|
||||
pthis->mapValue.erase("version");
|
||||
pthis->mapValue.erase("spent");
|
||||
pthis->mapValue.erase("n");
|
||||
pthis->mapValue.erase("timesmart");
|
||||
)
|
||||
|
||||
// marks certain txout's as spent
|
||||
// returns true if any update took place
|
||||
bool UpdateSpent(const std::vector<char>& vfNewSpent)
|
||||
{
|
||||
bool fReturn = false;
|
||||
for (unsigned int i = 0; i < vfNewSpent.size(); i++)
|
||||
{
|
||||
if (i == vfSpent.size())
|
||||
break;
|
||||
|
||||
if (vfNewSpent[i] && !vfSpent[i])
|
||||
{
|
||||
vfSpent[i] = true;
|
||||
fReturn = true;
|
||||
fAvailableCreditCached = false;
|
||||
}
|
||||
}
|
||||
return fReturn;
|
||||
}
|
||||
|
||||
// make sure balances are recalculated
|
||||
void MarkDirty()
|
||||
{
|
||||
fCreditCached = false;
|
||||
fAvailableCreditCached = false;
|
||||
fDebitCached = false;
|
||||
fChangeCached = false;
|
||||
}
|
||||
|
||||
void BindWallet(CWallet *pwalletIn)
|
||||
{
|
||||
pwallet = pwalletIn;
|
||||
MarkDirty();
|
||||
}
|
||||
|
||||
void MarkSpent(unsigned int nOut)
|
||||
{
|
||||
if (nOut >= vout.size())
|
||||
throw std::runtime_error("CWalletTx::MarkSpent() : nOut out of range");
|
||||
vfSpent.resize(vout.size());
|
||||
if (!vfSpent[nOut])
|
||||
{
|
||||
vfSpent[nOut] = true;
|
||||
fAvailableCreditCached = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool IsSpent(unsigned int nOut) const
|
||||
{
|
||||
if (nOut >= vout.size())
|
||||
throw std::runtime_error("CWalletTx::IsSpent() : nOut out of range");
|
||||
if (nOut >= vfSpent.size())
|
||||
return false;
|
||||
return (!!vfSpent[nOut]);
|
||||
}
|
||||
|
||||
int64 GetDebit() const
|
||||
{
|
||||
if (vin.empty())
|
||||
return 0;
|
||||
if (fDebitCached)
|
||||
return nDebitCached;
|
||||
nDebitCached = pwallet->GetDebit(*this);
|
||||
fDebitCached = true;
|
||||
return nDebitCached;
|
||||
}
|
||||
|
||||
int64 GetCredit(bool fUseCache=true) const
|
||||
{
|
||||
// Must wait until coinbase is safely deep enough in the chain before valuing it
|
||||
if (IsCoinBase() && GetBlocksToMaturity() > 0)
|
||||
return 0;
|
||||
|
||||
// GetBalance can assume transactions in mapWallet won't change
|
||||
if (fUseCache && fCreditCached)
|
||||
return nCreditCached;
|
||||
nCreditCached = pwallet->GetCredit(*this);
|
||||
fCreditCached = true;
|
||||
return nCreditCached;
|
||||
}
|
||||
|
||||
int64 GetImmatureCredit(bool fUseCache=true) const
|
||||
{
|
||||
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
|
||||
{
|
||||
if (fUseCache && fImmatureCreditCached)
|
||||
return nImmatureCreditCached;
|
||||
nImmatureCreditCached = pwallet->GetCredit(*this);
|
||||
fImmatureCreditCached = true;
|
||||
return nImmatureCreditCached;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int64 GetAvailableCredit(bool fUseCache=true) const
|
||||
{
|
||||
// Must wait until coinbase is safely deep enough in the chain before valuing it
|
||||
if (IsCoinBase() && GetBlocksToMaturity() > 0)
|
||||
return 0;
|
||||
|
||||
if (fUseCache && fAvailableCreditCached)
|
||||
return nAvailableCreditCached;
|
||||
|
||||
int64 nCredit = 0;
|
||||
for (unsigned int i = 0; i < vout.size(); i++)
|
||||
{
|
||||
if (!IsSpent(i))
|
||||
{
|
||||
const CTxOut &txout = vout[i];
|
||||
nCredit += pwallet->GetCredit(txout);
|
||||
if (!MoneyRange(nCredit))
|
||||
throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
|
||||
}
|
||||
}
|
||||
|
||||
nAvailableCreditCached = nCredit;
|
||||
fAvailableCreditCached = true;
|
||||
return nCredit;
|
||||
}
|
||||
|
||||
|
||||
int64 GetChange() const
|
||||
{
|
||||
if (fChangeCached)
|
||||
return nChangeCached;
|
||||
nChangeCached = pwallet->GetChange(*this);
|
||||
fChangeCached = true;
|
||||
return nChangeCached;
|
||||
}
|
||||
|
||||
void GetAmounts(std::list<std::pair<CTxDestination, int64> >& listReceived,
|
||||
std::list<std::pair<CTxDestination, int64> >& listSent, int64& nFee, std::string& strSentAccount) const;
|
||||
|
||||
void GetAccountAmounts(const std::string& strAccount, int64& nReceived,
|
||||
int64& nSent, int64& nFee) const;
|
||||
|
||||
bool IsFromMe() const
|
||||
{
|
||||
return (GetDebit() > 0);
|
||||
}
|
||||
|
||||
bool IsConfirmed() const
|
||||
{
|
||||
// Quick answer in most cases
|
||||
if (!IsFinal())
|
||||
return false;
|
||||
if (GetDepthInMainChain() >= 1)
|
||||
return true;
|
||||
if (!IsFromMe()) // using wtx's cached debit
|
||||
return false;
|
||||
|
||||
// If no confirmations but it's from us, we can still
|
||||
// consider it confirmed if all dependencies are confirmed
|
||||
std::map<uint256, const CMerkleTx*> mapPrev;
|
||||
std::vector<const CMerkleTx*> vWorkQueue;
|
||||
vWorkQueue.reserve(vtxPrev.size()+1);
|
||||
vWorkQueue.push_back(this);
|
||||
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
|
||||
{
|
||||
const CMerkleTx* ptx = vWorkQueue[i];
|
||||
|
||||
if (!ptx->IsFinal())
|
||||
return false;
|
||||
if (ptx->GetDepthInMainChain() >= 1)
|
||||
continue;
|
||||
if (!pwallet->IsFromMe(*ptx))
|
||||
return false;
|
||||
|
||||
if (mapPrev.empty())
|
||||
{
|
||||
BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
|
||||
mapPrev[tx.GetHash()] = &tx;
|
||||
}
|
||||
|
||||
BOOST_FOREACH(const CTxIn& txin, ptx->vin)
|
||||
{
|
||||
if (!mapPrev.count(txin.prevout.hash))
|
||||
return false;
|
||||
vWorkQueue.push_back(mapPrev[txin.prevout.hash]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WriteToDisk();
|
||||
|
||||
int64 GetTxTime() const;
|
||||
int GetRequestCount() const;
|
||||
|
||||
void AddSupportingTransactions();
|
||||
bool AcceptWalletTransaction(bool fCheckInputs=true);
|
||||
void RelayWalletTransaction();
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
class COutput
|
||||
{
|
||||
public:
|
||||
const CWalletTx *tx;
|
||||
int i;
|
||||
int nDepth;
|
||||
|
||||
COutput(const CWalletTx *txIn, int iIn, int nDepthIn)
|
||||
{
|
||||
tx = txIn; i = iIn; nDepth = nDepthIn;
|
||||
}
|
||||
|
||||
std::string ToString() const
|
||||
{
|
||||
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString().c_str(), i, nDepth, FormatMoney(tx->vout[i].nValue).c_str());
|
||||
}
|
||||
|
||||
void print() const
|
||||
{
|
||||
printf("%s\n", ToString().c_str());
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
/** Private key that includes an expiration date in case it never gets used. */
|
||||
class CWalletKey
|
||||
{
|
||||
public:
|
||||
CPrivKey vchPrivKey;
|
||||
int64 nTimeCreated;
|
||||
int64 nTimeExpires;
|
||||
std::string strComment;
|
||||
//// todo: add something to note what created it (user, getnewaddress, change)
|
||||
//// maybe should have a map<string, string> property map
|
||||
|
||||
CWalletKey(int64 nExpires=0)
|
||||
{
|
||||
nTimeCreated = (nExpires ? GetTime() : 0);
|
||||
nTimeExpires = nExpires;
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
if (!(nType & SER_GETHASH))
|
||||
READWRITE(nVersion);
|
||||
READWRITE(vchPrivKey);
|
||||
READWRITE(nTimeCreated);
|
||||
READWRITE(nTimeExpires);
|
||||
READWRITE(strComment);
|
||||
)
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/** Account information.
|
||||
* Stored in wallet with key "acc"+string account name.
|
||||
*/
|
||||
class CAccount
|
||||
{
|
||||
public:
|
||||
CPubKey vchPubKey;
|
||||
|
||||
CAccount()
|
||||
{
|
||||
SetNull();
|
||||
}
|
||||
|
||||
void SetNull()
|
||||
{
|
||||
vchPubKey = CPubKey();
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
if (!(nType & SER_GETHASH))
|
||||
READWRITE(nVersion);
|
||||
READWRITE(vchPubKey);
|
||||
)
|
||||
};
|
||||
|
||||
|
||||
|
||||
/** Internal transfers.
|
||||
* Database key is acentry<account><counter>.
|
||||
*/
|
||||
class CAccountingEntry
|
||||
{
|
||||
public:
|
||||
std::string strAccount;
|
||||
int64 nCreditDebit;
|
||||
int64 nTime;
|
||||
std::string strOtherAccount;
|
||||
std::string strComment;
|
||||
mapValue_t mapValue;
|
||||
int64 nOrderPos; // position in ordered transaction list
|
||||
uint64 nEntryNo;
|
||||
|
||||
CAccountingEntry()
|
||||
{
|
||||
SetNull();
|
||||
}
|
||||
|
||||
void SetNull()
|
||||
{
|
||||
nCreditDebit = 0;
|
||||
nTime = 0;
|
||||
strAccount.clear();
|
||||
strOtherAccount.clear();
|
||||
strComment.clear();
|
||||
nOrderPos = -1;
|
||||
}
|
||||
|
||||
IMPLEMENT_SERIALIZE
|
||||
(
|
||||
CAccountingEntry& me = *const_cast<CAccountingEntry*>(this);
|
||||
if (!(nType & SER_GETHASH))
|
||||
READWRITE(nVersion);
|
||||
// Note: strAccount is serialized as part of the key, not here.
|
||||
READWRITE(nCreditDebit);
|
||||
READWRITE(nTime);
|
||||
READWRITE(strOtherAccount);
|
||||
|
||||
if (!fRead)
|
||||
{
|
||||
WriteOrderPos(nOrderPos, me.mapValue);
|
||||
|
||||
if (!(mapValue.empty() && _ssExtra.empty()))
|
||||
{
|
||||
CDataStream ss(nType, nVersion);
|
||||
ss.insert(ss.begin(), '\0');
|
||||
ss << mapValue;
|
||||
ss.insert(ss.end(), _ssExtra.begin(), _ssExtra.end());
|
||||
me.strComment.append(ss.str());
|
||||
}
|
||||
}
|
||||
|
||||
READWRITE(strComment);
|
||||
|
||||
size_t nSepPos = strComment.find("\0", 0, 1);
|
||||
if (fRead)
|
||||
{
|
||||
me.mapValue.clear();
|
||||
if (std::string::npos != nSepPos)
|
||||
{
|
||||
CDataStream ss(std::vector<char>(strComment.begin() + nSepPos + 1, strComment.end()), nType, nVersion);
|
||||
ss >> me.mapValue;
|
||||
me._ssExtra = std::vector<char>(ss.begin(), ss.end());
|
||||
}
|
||||
ReadOrderPos(me.nOrderPos, me.mapValue);
|
||||
}
|
||||
if (std::string::npos != nSepPos)
|
||||
me.strComment.erase(nSepPos);
|
||||
|
||||
me.mapValue.erase("n");
|
||||
)
|
||||
|
||||
private:
|
||||
std::vector<char> _ssExtra;
|
||||
};
|
||||
|
||||
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
|
||||
|
||||
#endif
|
679
src/walletdb.cpp
679
src/walletdb.cpp
|
@ -1,679 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Copyright (c) 2013 The Primecoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
|
||||
#include "walletdb.h"
|
||||
#include "wallet.h"
|
||||
#include <boost/filesystem.hpp>
|
||||
|
||||
using namespace std;
|
||||
using namespace boost;
|
||||
|
||||
|
||||
static uint64 nAccountingEntryNumber = 0;
|
||||
|
||||
//
|
||||
// CWalletDB
|
||||
//
|
||||
|
||||
bool CWalletDB::WriteName(const string& strAddress, const string& strName)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(make_pair(string("name"), strAddress), strName);
|
||||
}
|
||||
|
||||
bool CWalletDB::EraseName(const string& strAddress)
|
||||
{
|
||||
// This should only be used for sending addresses, never for receiving addresses,
|
||||
// receiving addresses must always have an address book entry if they're not change return.
|
||||
nWalletDBUpdated++;
|
||||
return Erase(make_pair(string("name"), strAddress));
|
||||
}
|
||||
|
||||
bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account)
|
||||
{
|
||||
account.SetNull();
|
||||
return Read(make_pair(string("acc"), strAccount), account);
|
||||
}
|
||||
|
||||
bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account)
|
||||
{
|
||||
return Write(make_pair(string("acc"), strAccount), account);
|
||||
}
|
||||
|
||||
bool CWalletDB::WriteAccountingEntry(const uint64 nAccEntryNum, const CAccountingEntry& acentry)
|
||||
{
|
||||
return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry);
|
||||
}
|
||||
|
||||
bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry)
|
||||
{
|
||||
return WriteAccountingEntry(++nAccountingEntryNumber, acentry);
|
||||
}
|
||||
|
||||
int64 CWalletDB::GetAccountCreditDebit(const string& strAccount)
|
||||
{
|
||||
list<CAccountingEntry> entries;
|
||||
ListAccountCreditDebit(strAccount, entries);
|
||||
|
||||
int64 nCreditDebit = 0;
|
||||
BOOST_FOREACH (const CAccountingEntry& entry, entries)
|
||||
nCreditDebit += entry.nCreditDebit;
|
||||
|
||||
return nCreditDebit;
|
||||
}
|
||||
|
||||
void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries)
|
||||
{
|
||||
bool fAllAccounts = (strAccount == "*");
|
||||
|
||||
Dbc* pcursor = GetCursor();
|
||||
if (!pcursor)
|
||||
throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor");
|
||||
unsigned int fFlags = DB_SET_RANGE;
|
||||
loop
|
||||
{
|
||||
// Read next record
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
if (fFlags == DB_SET_RANGE)
|
||||
ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0));
|
||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||
int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags);
|
||||
fFlags = DB_NEXT;
|
||||
if (ret == DB_NOTFOUND)
|
||||
break;
|
||||
else if (ret != 0)
|
||||
{
|
||||
pcursor->close();
|
||||
throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB");
|
||||
}
|
||||
|
||||
// Unserialize
|
||||
string strType;
|
||||
ssKey >> strType;
|
||||
if (strType != "acentry")
|
||||
break;
|
||||
CAccountingEntry acentry;
|
||||
ssKey >> acentry.strAccount;
|
||||
if (!fAllAccounts && acentry.strAccount != strAccount)
|
||||
break;
|
||||
|
||||
ssValue >> acentry;
|
||||
ssKey >> acentry.nEntryNo;
|
||||
entries.push_back(acentry);
|
||||
}
|
||||
|
||||
pcursor->close();
|
||||
}
|
||||
|
||||
|
||||
DBErrors
|
||||
CWalletDB::ReorderTransactions(CWallet* pwallet)
|
||||
{
|
||||
LOCK(pwallet->cs_wallet);
|
||||
// Old wallets didn't have any defined order for transactions
|
||||
// Probably a bad idea to change the output of this
|
||||
|
||||
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
|
||||
typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
|
||||
typedef multimap<int64, TxPair > TxItems;
|
||||
TxItems txByTime;
|
||||
|
||||
for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it)
|
||||
{
|
||||
CWalletTx* wtx = &((*it).second);
|
||||
txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
|
||||
}
|
||||
list<CAccountingEntry> acentries;
|
||||
ListAccountCreditDebit("", acentries);
|
||||
BOOST_FOREACH(CAccountingEntry& entry, acentries)
|
||||
{
|
||||
txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
|
||||
}
|
||||
|
||||
int64& nOrderPosNext = pwallet->nOrderPosNext;
|
||||
nOrderPosNext = 0;
|
||||
std::vector<int64> nOrderPosOffsets;
|
||||
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
|
||||
{
|
||||
CWalletTx *const pwtx = (*it).second.first;
|
||||
CAccountingEntry *const pacentry = (*it).second.second;
|
||||
int64& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
|
||||
|
||||
if (nOrderPos == -1)
|
||||
{
|
||||
nOrderPos = nOrderPosNext++;
|
||||
nOrderPosOffsets.push_back(nOrderPos);
|
||||
|
||||
if (pacentry)
|
||||
// Have to write accounting regardless, since we don't keep it in memory
|
||||
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
|
||||
return DB_LOAD_FAIL;
|
||||
}
|
||||
else
|
||||
{
|
||||
int64 nOrderPosOff = 0;
|
||||
BOOST_FOREACH(const int64& nOffsetStart, nOrderPosOffsets)
|
||||
{
|
||||
if (nOrderPos >= nOffsetStart)
|
||||
++nOrderPosOff;
|
||||
}
|
||||
nOrderPos += nOrderPosOff;
|
||||
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
|
||||
|
||||
if (!nOrderPosOff)
|
||||
continue;
|
||||
|
||||
// Since we're changing the order, write it back
|
||||
if (pwtx)
|
||||
{
|
||||
if (!WriteTx(pwtx->GetHash(), *pwtx))
|
||||
return DB_LOAD_FAIL;
|
||||
}
|
||||
else
|
||||
if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
|
||||
return DB_LOAD_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
return DB_LOAD_OK;
|
||||
}
|
||||
|
||||
|
||||
bool
|
||||
ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue,
|
||||
int& nFileVersion, vector<uint256>& vWalletUpgrade,
|
||||
bool& fIsEncrypted, bool& fAnyUnordered, string& strType, string& strErr)
|
||||
{
|
||||
try {
|
||||
// Unserialize
|
||||
// Taking advantage of the fact that pair serialization
|
||||
// is just the two items serialized one after the other
|
||||
ssKey >> strType;
|
||||
if (strType == "name")
|
||||
{
|
||||
string strAddress;
|
||||
ssKey >> strAddress;
|
||||
ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()];
|
||||
}
|
||||
else if (strType == "tx")
|
||||
{
|
||||
uint256 hash;
|
||||
ssKey >> hash;
|
||||
CWalletTx& wtx = pwallet->mapWallet[hash];
|
||||
ssValue >> wtx;
|
||||
CValidationState state;
|
||||
if (wtx.CheckTransaction(state) && (wtx.GetHash() == hash) && state.IsValid())
|
||||
wtx.BindWallet(pwallet);
|
||||
else
|
||||
{
|
||||
pwallet->mapWallet.erase(hash);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Undo serialize changes in 31600
|
||||
if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703)
|
||||
{
|
||||
if (!ssValue.empty())
|
||||
{
|
||||
char fTmp;
|
||||
char fUnused;
|
||||
ssValue >> fTmp >> fUnused >> wtx.strFromAccount;
|
||||
strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s",
|
||||
wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str());
|
||||
wtx.fTimeReceivedIsTxTime = fTmp;
|
||||
}
|
||||
else
|
||||
{
|
||||
strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str());
|
||||
wtx.fTimeReceivedIsTxTime = 0;
|
||||
}
|
||||
vWalletUpgrade.push_back(hash);
|
||||
}
|
||||
|
||||
if (wtx.nOrderPos == -1)
|
||||
fAnyUnordered = true;
|
||||
|
||||
//// debug print
|
||||
//printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str());
|
||||
//printf(" %12"PRI64d" %s %s %s\n",
|
||||
// wtx.vout[0].nValue,
|
||||
// DateTimeStrFormat("%Y-%m-%d %H:%M:%S", wtx.GetBlockTime()).c_str(),
|
||||
// wtx.hashBlock.ToString().c_str(),
|
||||
// wtx.mapValue["message"].c_str());
|
||||
}
|
||||
else if (strType == "acentry")
|
||||
{
|
||||
string strAccount;
|
||||
ssKey >> strAccount;
|
||||
uint64 nNumber;
|
||||
ssKey >> nNumber;
|
||||
if (nNumber > nAccountingEntryNumber)
|
||||
nAccountingEntryNumber = nNumber;
|
||||
|
||||
if (!fAnyUnordered)
|
||||
{
|
||||
CAccountingEntry acentry;
|
||||
ssValue >> acentry;
|
||||
if (acentry.nOrderPos == -1)
|
||||
fAnyUnordered = true;
|
||||
}
|
||||
}
|
||||
else if (strType == "key" || strType == "wkey")
|
||||
{
|
||||
vector<unsigned char> vchPubKey;
|
||||
ssKey >> vchPubKey;
|
||||
CKey key;
|
||||
if (strType == "key")
|
||||
{
|
||||
CPrivKey pkey;
|
||||
ssValue >> pkey;
|
||||
key.SetPubKey(vchPubKey);
|
||||
if (!key.SetPrivKey(pkey))
|
||||
{
|
||||
strErr = "Error reading wallet database: CPrivKey corrupt";
|
||||
return false;
|
||||
}
|
||||
if (key.GetPubKey() != vchPubKey)
|
||||
{
|
||||
strErr = "Error reading wallet database: CPrivKey pubkey inconsistency";
|
||||
return false;
|
||||
}
|
||||
if (!key.IsValid())
|
||||
{
|
||||
strErr = "Error reading wallet database: invalid CPrivKey";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CWalletKey wkey;
|
||||
ssValue >> wkey;
|
||||
key.SetPubKey(vchPubKey);
|
||||
if (!key.SetPrivKey(wkey.vchPrivKey))
|
||||
{
|
||||
strErr = "Error reading wallet database: CPrivKey corrupt";
|
||||
return false;
|
||||
}
|
||||
if (key.GetPubKey() != vchPubKey)
|
||||
{
|
||||
strErr = "Error reading wallet database: CWalletKey pubkey inconsistency";
|
||||
return false;
|
||||
}
|
||||
if (!key.IsValid())
|
||||
{
|
||||
strErr = "Error reading wallet database: invalid CWalletKey";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!pwallet->LoadKey(key))
|
||||
{
|
||||
strErr = "Error reading wallet database: LoadKey failed";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (strType == "mkey")
|
||||
{
|
||||
unsigned int nID;
|
||||
ssKey >> nID;
|
||||
CMasterKey kMasterKey;
|
||||
ssValue >> kMasterKey;
|
||||
if(pwallet->mapMasterKeys.count(nID) != 0)
|
||||
{
|
||||
strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID);
|
||||
return false;
|
||||
}
|
||||
pwallet->mapMasterKeys[nID] = kMasterKey;
|
||||
if (pwallet->nMasterKeyMaxID < nID)
|
||||
pwallet->nMasterKeyMaxID = nID;
|
||||
}
|
||||
else if (strType == "ckey")
|
||||
{
|
||||
vector<unsigned char> vchPubKey;
|
||||
ssKey >> vchPubKey;
|
||||
vector<unsigned char> vchPrivKey;
|
||||
ssValue >> vchPrivKey;
|
||||
if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey))
|
||||
{
|
||||
strErr = "Error reading wallet database: LoadCryptedKey failed";
|
||||
return false;
|
||||
}
|
||||
fIsEncrypted = true;
|
||||
}
|
||||
else if (strType == "defaultkey")
|
||||
{
|
||||
ssValue >> pwallet->vchDefaultKey;
|
||||
}
|
||||
else if (strType == "pool")
|
||||
{
|
||||
int64 nIndex;
|
||||
ssKey >> nIndex;
|
||||
pwallet->setKeyPool.insert(nIndex);
|
||||
}
|
||||
else if (strType == "version")
|
||||
{
|
||||
ssValue >> nFileVersion;
|
||||
if (nFileVersion == 10300)
|
||||
nFileVersion = 300;
|
||||
}
|
||||
else if (strType == "cscript")
|
||||
{
|
||||
uint160 hash;
|
||||
ssKey >> hash;
|
||||
CScript script;
|
||||
ssValue >> script;
|
||||
if (!pwallet->LoadCScript(script))
|
||||
{
|
||||
strErr = "Error reading wallet database: LoadCScript failed";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else if (strType == "orderposnext")
|
||||
{
|
||||
ssValue >> pwallet->nOrderPosNext;
|
||||
}
|
||||
} catch (...)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool IsKeyType(string strType)
|
||||
{
|
||||
return (strType== "key" || strType == "wkey" ||
|
||||
strType == "mkey" || strType == "ckey");
|
||||
}
|
||||
|
||||
DBErrors CWalletDB::LoadWallet(CWallet* pwallet)
|
||||
{
|
||||
pwallet->vchDefaultKey = CPubKey();
|
||||
int nFileVersion = 0;
|
||||
vector<uint256> vWalletUpgrade;
|
||||
bool fIsEncrypted = false;
|
||||
bool fAnyUnordered = false;
|
||||
bool fNoncriticalErrors = false;
|
||||
DBErrors result = DB_LOAD_OK;
|
||||
|
||||
try {
|
||||
LOCK(pwallet->cs_wallet);
|
||||
int nMinVersion = 0;
|
||||
if (Read((string)"minversion", nMinVersion))
|
||||
{
|
||||
if (nMinVersion > CLIENT_VERSION)
|
||||
return DB_TOO_NEW;
|
||||
pwallet->LoadMinVersion(nMinVersion);
|
||||
}
|
||||
|
||||
// Get cursor
|
||||
Dbc* pcursor = GetCursor();
|
||||
if (!pcursor)
|
||||
{
|
||||
printf("Error getting wallet database cursor\n");
|
||||
return DB_CORRUPT;
|
||||
}
|
||||
|
||||
loop
|
||||
{
|
||||
// Read next record
|
||||
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
|
||||
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
|
||||
int ret = ReadAtCursor(pcursor, ssKey, ssValue);
|
||||
if (ret == DB_NOTFOUND)
|
||||
break;
|
||||
else if (ret != 0)
|
||||
{
|
||||
printf("Error reading next record from wallet database\n");
|
||||
return DB_CORRUPT;
|
||||
}
|
||||
|
||||
// Try to be tolerant of single corrupt records:
|
||||
string strType, strErr;
|
||||
if (!ReadKeyValue(pwallet, ssKey, ssValue, nFileVersion,
|
||||
vWalletUpgrade, fIsEncrypted, fAnyUnordered, strType, strErr))
|
||||
{
|
||||
// losing keys is considered a catastrophic error, anything else
|
||||
// we assume the user can live with:
|
||||
if (IsKeyType(strType))
|
||||
result = DB_CORRUPT;
|
||||
else
|
||||
{
|
||||
// Leave other errors alone, if we try to fix them we might make things worse.
|
||||
fNoncriticalErrors = true; // ... but do warn the user there is something wrong.
|
||||
if (strType == "tx")
|
||||
// Rescan if there is a bad transaction record:
|
||||
SoftSetBoolArg("-rescan", true);
|
||||
}
|
||||
}
|
||||
if (!strErr.empty())
|
||||
printf("%s\n", strErr.c_str());
|
||||
}
|
||||
pcursor->close();
|
||||
}
|
||||
catch (boost::thread_interrupted) {
|
||||
throw;
|
||||
}
|
||||
catch (...) {
|
||||
result = DB_CORRUPT;
|
||||
}
|
||||
|
||||
if (fNoncriticalErrors && result == DB_LOAD_OK)
|
||||
result = DB_NONCRITICAL_ERROR;
|
||||
|
||||
// Any wallet corruption at all: skip any rewriting or
|
||||
// upgrading, we don't want to make it worse.
|
||||
if (result != DB_LOAD_OK)
|
||||
return result;
|
||||
|
||||
printf("nFileVersion = %d\n", nFileVersion);
|
||||
|
||||
BOOST_FOREACH(uint256 hash, vWalletUpgrade)
|
||||
WriteTx(hash, pwallet->mapWallet[hash]);
|
||||
|
||||
// Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc:
|
||||
if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000))
|
||||
return DB_NEED_REWRITE;
|
||||
|
||||
if (nFileVersion < CLIENT_VERSION) // Update
|
||||
WriteVersion(CLIENT_VERSION);
|
||||
|
||||
if (fAnyUnordered)
|
||||
result = ReorderTransactions(pwallet);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void ThreadFlushWalletDB(const string& strFile)
|
||||
{
|
||||
// Make this thread recognisable as the wallet flushing thread
|
||||
RenameThread("primecoin-wallet");
|
||||
|
||||
static bool fOneThread;
|
||||
if (fOneThread)
|
||||
return;
|
||||
fOneThread = true;
|
||||
if (!GetBoolArg("-flushwallet", true))
|
||||
return;
|
||||
|
||||
unsigned int nLastSeen = nWalletDBUpdated;
|
||||
unsigned int nLastFlushed = nWalletDBUpdated;
|
||||
int64 nLastWalletUpdate = GetTime();
|
||||
while (true)
|
||||
{
|
||||
MilliSleep(500);
|
||||
|
||||
if (nLastSeen != nWalletDBUpdated)
|
||||
{
|
||||
nLastSeen = nWalletDBUpdated;
|
||||
nLastWalletUpdate = GetTime();
|
||||
}
|
||||
|
||||
if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2)
|
||||
{
|
||||
TRY_LOCK(bitdb.cs_db,lockDb);
|
||||
if (lockDb)
|
||||
{
|
||||
// Don't do this if any databases are in use
|
||||
int nRefCount = 0;
|
||||
map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
|
||||
while (mi != bitdb.mapFileUseCount.end())
|
||||
{
|
||||
nRefCount += (*mi).second;
|
||||
mi++;
|
||||
}
|
||||
|
||||
if (nRefCount == 0)
|
||||
{
|
||||
boost::this_thread::interruption_point();
|
||||
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
|
||||
if (mi != bitdb.mapFileUseCount.end())
|
||||
{
|
||||
printf("Flushing wallet.dat\n");
|
||||
nLastFlushed = nWalletDBUpdated;
|
||||
int64 nStart = GetTimeMillis();
|
||||
|
||||
// Flush wallet.dat so it's self contained
|
||||
bitdb.CloseDb(strFile);
|
||||
bitdb.CheckpointLSN(strFile);
|
||||
|
||||
bitdb.mapFileUseCount.erase(mi++);
|
||||
printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool BackupWallet(const CWallet& wallet, const string& strDest)
|
||||
{
|
||||
if (!wallet.fFileBacked)
|
||||
return false;
|
||||
while (true)
|
||||
{
|
||||
{
|
||||
LOCK(bitdb.cs_db);
|
||||
if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0)
|
||||
{
|
||||
// Flush log data to the dat file
|
||||
bitdb.CloseDb(wallet.strWalletFile);
|
||||
bitdb.CheckpointLSN(wallet.strWalletFile);
|
||||
bitdb.mapFileUseCount.erase(wallet.strWalletFile);
|
||||
|
||||
// Copy wallet.dat
|
||||
filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile;
|
||||
filesystem::path pathDest(strDest);
|
||||
if (filesystem::is_directory(pathDest))
|
||||
pathDest /= wallet.strWalletFile;
|
||||
|
||||
try {
|
||||
#if BOOST_VERSION >= 104000
|
||||
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
|
||||
#else
|
||||
filesystem::copy_file(pathSrc, pathDest);
|
||||
#endif
|
||||
printf("copied wallet.dat to %s\n", pathDest.string().c_str());
|
||||
return true;
|
||||
} catch(const filesystem::filesystem_error &e) {
|
||||
printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
MilliSleep(100);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//
|
||||
// Try to (very carefully!) recover wallet.dat if there is a problem.
|
||||
//
|
||||
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
|
||||
{
|
||||
// Recovery procedure:
|
||||
// move wallet.dat to wallet.timestamp.bak
|
||||
// Call Salvage with fAggressive=true to
|
||||
// get as much data as possible.
|
||||
// Rewrite salvaged data to wallet.dat
|
||||
// Set -rescan so any missing transactions will be
|
||||
// found.
|
||||
int64 now = GetTime();
|
||||
std::string newFilename = strprintf("wallet.%"PRI64d".bak", now);
|
||||
|
||||
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
|
||||
newFilename.c_str(), DB_AUTO_COMMIT);
|
||||
if (result == 0)
|
||||
printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str());
|
||||
else
|
||||
{
|
||||
printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<CDBEnv::KeyValPair> salvagedData;
|
||||
bool allOK = dbenv.Salvage(newFilename, true, salvagedData);
|
||||
if (salvagedData.empty())
|
||||
{
|
||||
printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
|
||||
return false;
|
||||
}
|
||||
printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
|
||||
|
||||
bool fSuccess = allOK;
|
||||
Db* pdbCopy = new Db(&dbenv.dbenv, 0);
|
||||
int ret = pdbCopy->open(NULL, // Txn pointer
|
||||
filename.c_str(), // Filename
|
||||
"main", // Logical db name
|
||||
DB_BTREE, // Database type
|
||||
DB_CREATE, // Flags
|
||||
0);
|
||||
if (ret > 0)
|
||||
{
|
||||
printf("Cannot create database file %s\n", filename.c_str());
|
||||
return false;
|
||||
}
|
||||
CWallet dummyWallet;
|
||||
int nFileVersion = 0;
|
||||
vector<uint256> vWalletUpgrade;
|
||||
bool fIsEncrypted = false;
|
||||
bool fAnyUnordered = false;
|
||||
|
||||
DbTxn* ptxn = dbenv.TxnBegin();
|
||||
BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData)
|
||||
{
|
||||
if (fOnlyKeys)
|
||||
{
|
||||
CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION);
|
||||
CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION);
|
||||
string strType, strErr;
|
||||
bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue,
|
||||
nFileVersion, vWalletUpgrade,
|
||||
fIsEncrypted, fAnyUnordered,
|
||||
strType, strErr);
|
||||
if (!IsKeyType(strType))
|
||||
continue;
|
||||
if (!fReadOK)
|
||||
{
|
||||
printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Dbt datKey(&row.first[0], row.first.size());
|
||||
Dbt datValue(&row.second[0], row.second.size());
|
||||
int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE);
|
||||
if (ret2 > 0)
|
||||
fSuccess = false;
|
||||
}
|
||||
ptxn->commit(0);
|
||||
pdbCopy->close(0);
|
||||
delete pdbCopy;
|
||||
|
||||
return fSuccess;
|
||||
}
|
||||
|
||||
bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename)
|
||||
{
|
||||
return CWalletDB::Recover(dbenv, filename, false);
|
||||
}
|
163
src/walletdb.h
163
src/walletdb.h
|
@ -1,163 +0,0 @@
|
|||
// Copyright (c) 2009-2010 Satoshi Nakamoto
|
||||
// Copyright (c) 2009-2012 The Bitcoin developers
|
||||
// Distributed under the MIT/X11 software license, see the accompanying
|
||||
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
||||
#ifndef BITCOIN_WALLETDB_H
|
||||
#define BITCOIN_WALLETDB_H
|
||||
|
||||
#include "db.h"
|
||||
#include "base58.h"
|
||||
|
||||
class CKeyPool;
|
||||
class CAccount;
|
||||
class CAccountingEntry;
|
||||
|
||||
/** Error statuses for the wallet database */
|
||||
enum DBErrors
|
||||
{
|
||||
DB_LOAD_OK,
|
||||
DB_CORRUPT,
|
||||
DB_NONCRITICAL_ERROR,
|
||||
DB_TOO_NEW,
|
||||
DB_LOAD_FAIL,
|
||||
DB_NEED_REWRITE
|
||||
};
|
||||
|
||||
/** Access to the wallet database (wallet.dat) */
|
||||
class CWalletDB : public CDB
|
||||
{
|
||||
public:
|
||||
CWalletDB(std::string strFilename, const char* pszMode="r+") : CDB(strFilename.c_str(), pszMode)
|
||||
{
|
||||
}
|
||||
private:
|
||||
CWalletDB(const CWalletDB&);
|
||||
void operator=(const CWalletDB&);
|
||||
public:
|
||||
bool WriteName(const std::string& strAddress, const std::string& strName);
|
||||
|
||||
bool EraseName(const std::string& strAddress);
|
||||
|
||||
bool WriteTx(uint256 hash, const CWalletTx& wtx)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::make_pair(std::string("tx"), hash), wtx);
|
||||
}
|
||||
|
||||
bool EraseTx(uint256 hash)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Erase(std::make_pair(std::string("tx"), hash));
|
||||
}
|
||||
|
||||
bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::make_pair(std::string("key"), vchPubKey.Raw()), vchPrivKey, false);
|
||||
}
|
||||
|
||||
bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret, bool fEraseUnencryptedKey = true)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
if (!Write(std::make_pair(std::string("ckey"), vchPubKey.Raw()), vchCryptedSecret, false))
|
||||
return false;
|
||||
if (fEraseUnencryptedKey)
|
||||
{
|
||||
Erase(std::make_pair(std::string("key"), vchPubKey.Raw()));
|
||||
Erase(std::make_pair(std::string("wkey"), vchPubKey.Raw()));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::make_pair(std::string("mkey"), nID), kMasterKey, true);
|
||||
}
|
||||
|
||||
bool WriteCScript(const uint160& hash, const CScript& redeemScript)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::make_pair(std::string("cscript"), hash), redeemScript, false);
|
||||
}
|
||||
|
||||
bool WriteBestBlock(const CBlockLocator& locator)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::string("bestblock"), locator);
|
||||
}
|
||||
|
||||
bool ReadBestBlock(CBlockLocator& locator)
|
||||
{
|
||||
return Read(std::string("bestblock"), locator);
|
||||
}
|
||||
|
||||
bool WriteOrderPosNext(int64 nOrderPosNext)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::string("orderposnext"), nOrderPosNext);
|
||||
}
|
||||
|
||||
bool WriteDefaultKey(const CPubKey& vchPubKey)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::string("defaultkey"), vchPubKey.Raw());
|
||||
}
|
||||
|
||||
bool ReadPool(int64 nPool, CKeyPool& keypool)
|
||||
{
|
||||
return Read(std::make_pair(std::string("pool"), nPool), keypool);
|
||||
}
|
||||
|
||||
bool WritePool(int64 nPool, const CKeyPool& keypool)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::make_pair(std::string("pool"), nPool), keypool);
|
||||
}
|
||||
|
||||
bool ErasePool(int64 nPool)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Erase(std::make_pair(std::string("pool"), nPool));
|
||||
}
|
||||
|
||||
// Settings are no longer stored in wallet.dat; these are
|
||||
// used only for backwards compatibility:
|
||||
template<typename T>
|
||||
bool ReadSetting(const std::string& strKey, T& value)
|
||||
{
|
||||
return Read(std::make_pair(std::string("setting"), strKey), value);
|
||||
}
|
||||
template<typename T>
|
||||
bool WriteSetting(const std::string& strKey, const T& value)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Write(std::make_pair(std::string("setting"), strKey), value);
|
||||
}
|
||||
bool EraseSetting(const std::string& strKey)
|
||||
{
|
||||
nWalletDBUpdated++;
|
||||
return Erase(std::make_pair(std::string("setting"), strKey));
|
||||
}
|
||||
|
||||
bool WriteMinVersion(int nVersion)
|
||||
{
|
||||
return Write(std::string("minversion"), nVersion);
|
||||
}
|
||||
|
||||
bool ReadAccount(const std::string& strAccount, CAccount& account);
|
||||
bool WriteAccount(const std::string& strAccount, const CAccount& account);
|
||||
private:
|
||||
bool WriteAccountingEntry(const uint64 nAccEntryNum, const CAccountingEntry& acentry);
|
||||
public:
|
||||
bool WriteAccountingEntry(const CAccountingEntry& acentry);
|
||||
int64 GetAccountCreditDebit(const std::string& strAccount);
|
||||
void ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& acentries);
|
||||
|
||||
DBErrors ReorderTransactions(CWallet*);
|
||||
DBErrors LoadWallet(CWallet* pwallet);
|
||||
static bool Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys);
|
||||
static bool Recover(CDBEnv& dbenv, std::string filename);
|
||||
};
|
||||
|
||||
#endif // BITCOIN_WALLETDB_H
|
Loading…
Reference in New Issue