// Copyright (c) 2012-2013 The PPCoin developers
+// Copyright (c) 2013-2015 The Novacoin developers
+// Distributed under the MIT/X11 software license, see the accompanying
+// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// 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 "kernel.h"
+#include "kernel_worker.h"
#include "txdb.h"
-extern unsigned int nStakeMaxAge;
-extern unsigned int nStakeTargetSpacing;
+extern uint32_t nStakeTargetSpacing;
using namespace std;
+uint32_t nStakeMinAge = 30 * nOneDay; // 30 days as zero time weight
+uint32_t nStakeMaxAge = 90 * nOneDay; // 90 days as full weight
// Protocol switch time for fixed kernel modifier interval
-unsigned int nModifierSwitchTime = 1413763200; // Mon, 20 Oct 2014 00:00:00 GMT
-unsigned int nModifierTestSwitchTime = 1397520000; // Tue, 15 Apr 2014 00:00:00 GMT
+uint32_t nModifierSwitchTime = 1413763200; // Mon, 20 Oct 2014 00:00:00 GMT
+uint32_t nModifierTestSwitchTime = 1397520000; // Tue, 15 Apr 2014 00:00:00 GMT
// Note: user must upgrade before the protocol switch deadline, otherwise it's required to
// re-download the blockchain. The timestamp of upgrade is recorded in the blockchain
// database.
-unsigned int nModifierUpgradeTime = 0;
-
-typedef std::map<int, unsigned int> MapModifierCheckpoints;
+uint32_t nModifierUpgradeTime = 0;
// Hard checkpoints of stake modifiers to ensure they are deterministic
-static std::map<int, unsigned int> mapStakeModifierCheckpoints =
- boost::assign::map_list_of
- ( 0, 0x0e00670bu )
- ( 9690, 0x97dcdafau )
- ( 12661, 0x5d84115du )
- ( 37092, 0xd230afccu )
- ( 44200, 0x05370164u )
- ( 65000, 0xc8e7be6au )
- ( 68600, 0x73a8cc4cu )
- ( 92161, 0xe21a911au )
- ( 98661, 0xd20c44d4u )
- (143990, 0x9c592c78u )
- ;
+static map<int, uint32_t> mapStakeModifierCheckpoints =
+{
+ { 0, 0x0e00670bu },
+ { 12661, 0x5d84115du },
+ { 143990, 0x9c592c78u },
+ { 149000, 0x48f2bdc4u },
+ { 160000, 0x789df0f0u },
+ { 200000, 0x01ec1503u },
+ { 221047, 0x0b39ef50u },
+ { 243100, 0xe928d83au },
+};
// Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
-static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
- boost::assign::map_list_of
- ( 0, 0x0e00670bu )
- ;
+static map<int, uint32_t> mapStakeModifierCheckpointsTestNet =
+{
+ { 0, 0x0e00670bu }
+};
// Pregenerated entropy bits table (from genesis to #9689)
//
return (nTimeBlock >= (fTestNet? nModifierTestSwitchTime : nModifierSwitchTime));
}
-// Get time weight
-int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
-{
- // Kernel hash weight starts from 0 at the 30-day min age
- // this change increases active coins participating the hash and helps
- // to secure the network when proof-of-stake difficulty is low
- //
- // Maximum TimeWeight is 90 days.
-
- return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64_t)nStakeMaxAge);
-}
-
// Get the last stake modifier and its generation time from a given block
static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
{
bool fSelected = false;
uint256 hashBest = 0;
*pindexSelected = (const CBlockIndex*) 0;
- BOOST_FOREACH(const PAIRTYPE(int64_t, uint256)& item, vSortedByTimestamp)
+ for(const auto& item : vSortedByTimestamp)
{
if (!mapBlockIndex.count(item.second))
return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
- const CBlockIndex* pindex = mapBlockIndex[item.second];
+ auto pindex = mapBlockIndex[item.second];
if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
break;
if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
continue;
// compute the selection hash by hashing its proof-hash and the
// previous proof-of-stake modifier
- uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
+ auto hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
CDataStream ss(SER_GETHASH, 0);
ss << hashProof << nStakeModifierPrev;
- uint256 hashSelection = Hash(ss.begin(), ss.end());
+ auto hashSelection = Hash(ss.begin(), ss.end());
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
if (fSelected && hashSelection < hashBest)
{
hashBest = hashSelection;
- *pindexSelected = (const CBlockIndex*) pindex;
+ *pindexSelected = pindex;
}
else if (!fSelected)
{
fSelected = true;
hashBest = hashSelection;
- *pindexSelected = (const CBlockIndex*) pindex;
+ *pindexSelected = pindex;
}
}
if (fDebug && GetBoolArg("-printstakemodifier"))
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;
- const CBlockIndex* pindexPrev = pindexCurrent->pprev;
+ auto pindexPrev = pindexCurrent->pprev;
if (!pindexPrev)
{
fGeneratedStakeModifier = true;
// Sort candidate blocks by timestamp
vector<pair<int64_t, uint256> > vSortedByTimestamp;
vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
- int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
- int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
- const CBlockIndex* pindex = pindexPrev;
+ auto nSelectionInterval = GetStakeModifierSelectionInterval();
+ auto nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
+ const auto *pindex = pindexPrev;
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
{
- vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
+ vSortedByTimestamp.push_back({ pindex->GetBlockTime(), pindex->GetBlockHash() });
pindex = pindex->pprev;
}
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
// Select 64 blocks from candidate blocks to generate stake modifier
uint64_t nStakeModifierNew = 0;
- int64_t nSelectionIntervalStop = nSelectionIntervalStart;
+ auto nSelectionIntervalStop = nSelectionIntervalStart;
map<uint256, const CBlockIndex*> mapSelectedBlocks;
for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
{
// write the entropy bit of the selected block
nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
// add the selected block from candidates to selected list
- mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
+ mapSelectedBlocks.insert({ pindex->GetBlockHash(), pindex });
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
}
strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
pindex = pindex->pprev;
}
- BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
+ for(const auto& item : mapSelectedBlocks)
{
// 'S' indicates selected proof-of-stake blocks
// 'W' indicates selected proof-of-work blocks
// The stake modifier used to hash for a stake kernel is chosen as the stake
// modifier about a selection interval later than the coin generating the kernel
-static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
+static bool GetKernelStakeModifier(const uint256 &hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
{
nStakeModifier = 0;
if (!mapBlockIndex.count(hashBlockFrom))
return error("GetKernelStakeModifier() : block not indexed");
- const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
+ auto pindexFrom = mapBlockIndex[hashBlockFrom];
nStakeModifierHeight = pindexFrom->nHeight;
nStakeModifierTime = pindexFrom->GetBlockTime();
- int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
- const CBlockIndex* pindex = pindexFrom;
+ auto nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
+ auto pindex = pindexFrom;
// loop to find the stake modifier later by a selection interval
while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
{
return true;
}
-bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier)
+bool GetKernelStakeModifier(const uint256 &hashBlockFrom, uint64_t& nStakeModifier)
{
int nStakeModifierHeight;
int64_t nStakeModifierTime;
CBigNum bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
- int64_t nValueIn = txPrev.vout[prevout.n].nValue;
-
- uint256 hashBlockFrom = blockFrom.GetHash();
-
- CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)txPrev.nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
+ auto nValueIn = txPrev.vout[prevout.n].nValue;
+ auto hashBlockFrom = blockFrom.GetHash();
+ auto bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)txPrev.nTime, (int64_t)nTimeTx) / COIN / nOneDay;
targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
// Calculate hash
DateTimeStrFormat(nStakeModifierTime).c_str(),
mapBlockIndex[hashBlockFrom]->nHeight,
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
- printf("CheckStakeKernelHash() : check modifier=0x%016" PRIx64 " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
+ printf("CheckStakeKernelHash() : check modifier=0x%016" PRIx64 " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashTarget=%s hashProof=%s\n",
nStakeModifier,
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
- hashProofOfStake.ToString().c_str());
+ targetProofOfStake.ToString().c_str(), hashProofOfStake.ToString().c_str());
}
// Now check if proof-of-stake hash meets target protocol
DateTimeStrFormat(nStakeModifierTime).c_str(),
mapBlockIndex[hashBlockFrom]->nHeight,
DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
- printf("CheckStakeKernelHash() : pass modifier=0x%016" PRIx64 " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
+ printf("CheckStakeKernelHash() : pass modifier=0x%016" PRIx64 " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashTarget=%s hashProof=%s\n",
nStakeModifier,
nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
- hashProofOfStake.ToString().c_str());
+ targetProofOfStake.ToString().c_str(), hashProofOfStake.ToString().c_str());
}
return true;
}
-// Scan given coins set for kernel solution
-bool ScanForStakeKernelHash(MetaMap &mapMeta, KernelSearchSettings &settings, CoinsSet::value_type &kernelcoin, uint32_t &nTimeTx, uint32_t &nBlockTime, uint64_t &nKernelsTried, uint64_t &nCoinDaysTried)
+// Scan given kernel for solution
+bool ScanKernelForward(unsigned char *kernel, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, pair<uint32_t, uint32_t> &SearchInterval, vector<pair<uint256, uint32_t> > &solutions)
{
- uint256 hashProofOfStake = 0;
-
- // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
- for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
+ solutions.clear();
{
- if (!fCoinsDataActual)
- break;
-
- CTxIndex txindex = (*meta_item).second.first.first;
- CBlock block = (*meta_item).second.second.first;
- uint64_t nStakeModifier = (*meta_item).second.second.second;
-
- // Get coin
- CoinsSet::value_type pcoin = meta_item->second.first.second;
+ using namespace boost;
- static int nMaxStakeSearchInterval = 60;
-
- // only count coins meeting min age requirement
- if (nStakeMinAge + block.nTime > settings.nTime - nMaxStakeSearchInterval)
- continue;
-
- // Transaction offset inside block
- uint32_t nTxOffset = txindex.pos.nTxPos - txindex.pos.nBlockPos;
-
- // Current timestamp scanning interval
- unsigned int nCurrentSearchInterval = min((int64_t)settings.nSearchInterval, (int64_t)nMaxStakeSearchInterval);
-
- nBlockTime = block.nTime;
- CBigNum bnTargetPerCoinDay;
- bnTargetPerCoinDay.SetCompact(settings.nBits);
- int64_t nValueIn = pcoin.first->vout[pcoin.second].nValue;
+ auto nThreads = boost::thread::hardware_concurrency();
+ if (nThreads == 0) {
+ nThreads = 1;
+ printf("Warning: hardware_concurrency() failed in %s:%d\n", __FILE__, __LINE__);
+ }
+ auto vWorkers = vector<KernelWorker>(nThreads);
+ auto nPart = (SearchInterval.second - SearchInterval.first) / nThreads;
+ thread_group group;
- // Search backward in time from the given timestamp
- // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
- // Stopping search in case of shutting down or cache invalidation
- for (unsigned int n=0; n<nCurrentSearchInterval && fCoinsDataActual && !fShutdown; n++)
+ for(size_t i = 0; i < vWorkers.size(); i++)
{
- nTimeTx = settings.nTime - n;
- CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)pcoin.first->nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
- CBigNum bnTargetProofOfStake = bnCoinDayWeight * bnTargetPerCoinDay;
-
- // Build kernel
- CDataStream ss(SER_GETHASH, 0);
- ss << nStakeModifier;
- ss << nBlockTime << nTxOffset << pcoin.first->nTime << pcoin.second << nTimeTx;
-
- // Calculate kernel hash
- hashProofOfStake = Hash(ss.begin(), ss.end());
-
- // Update statistics
- nKernelsTried += 1;
- nCoinDaysTried += bnCoinDayWeight.getuint64();
+ auto nBegin = SearchInterval.first + nPart * i;
+ auto nEnd = SearchInterval.first + nPart * (i + 1);
- if (bnTargetProofOfStake >= CBigNum(hashProofOfStake))
- {
- if (fDebug)
- printf("nStakeModifier=0x%016" PRIx64 ", nBlockTime=%u nTxOffset=%u nTxPrevTime=%u nVout=%u nTimeTx=%u hashProofOfStake=%s Success=true\n",
- nStakeModifier, nBlockTime, nTxOffset, pcoin.first->nTime, pcoin.second, nTimeTx, hashProofOfStake.GetHex().c_str());
+ vWorkers[i] = KernelWorker(kernel, nBits, nInputTxTime, nValueIn, nBegin, nEnd);
+ auto workerFnc = bind(&KernelWorker::Do, &vWorkers[i]);
+ group.create_thread(workerFnc);
+ }
- kernelcoin = pcoin;
- return true;
- }
+ group.join_all();
- if (fDebug)
- printf("nStakeModifier=0x%016" PRIx64 ", nBlockTime=%u nTxOffset=%u nTxPrevTime=%u nTxNumber=%u nTimeTx=%u hashProofOfStake=%s Success=false\n",
- nStakeModifier, nBlockTime, nTxOffset, pcoin.first->nTime, pcoin.second, nTimeTx, hashProofOfStake.GetHex().c_str());
+ for(auto& worker : vWorkers)
+ {
+ auto ws = worker.GetSolutions();
+ solutions.insert(solutions.end(), ws.begin(), ws.end());
}
+
+ return (solutions.size() != 0);
}
- return false;
+ return true;
}
// Check kernel hash target and coinstake signature
return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
// Kernel (input 0) must match the stake hash target per coin age (nBits)
- const CTxIn& txin = tx.vin[0];
+ const auto& txin = tx.vin[0];
// First try finding the previous transaction in database
CTxDB txdb("r");
if (pindex->pprev)
ss << pindex->pprev->nStakeModifierChecksum;
ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
- uint256 hashChecksum = Hash(ss.begin(), ss.end());
+ auto hashChecksum = Hash(ss.begin(), ss.end());
hashChecksum >>= (256 - 32);
- return hashChecksum.Get64();
+ return hashChecksum.Get32();
}
// Check stake modifier hard checkpoints
bool CheckStakeModifierCheckpoints(int nHeight, uint32_t nStakeModifierChecksum)
{
- MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
-
+ auto& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
if (checkpoints.count(nHeight))
return nStakeModifierChecksum == checkpoints[nHeight];
return true;