// 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 )
- ( 12661, 0x5d84115du )
- (143990, 0x9c592c78u )
- (149000, 0x48f2bdc4u )
- (160000, 0x789df0f0u )
- (200000, 0x01ec1503u )
- ;
+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)
//
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
return true;
}
-// Precompute hashing state for static part of kernel
-void GetKernelMidstate(uint64_t nStakeModifier, uint32_t nBlockTime, uint32_t nTxOffset, uint32_t nInputTxTime, uint32_t nOut, SHA256_CTX &ctx)
+// 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)
{
- // Build static part of kernel
- CDataStream ssKernel(SER_GETHASH, 0);
- ssKernel << nStakeModifier;
- ssKernel << nBlockTime << nTxOffset << nInputTxTime << nOut;
- CDataStream::const_iterator it = ssKernel.begin();
-
- // Init sha256 context and update it
- // with first 24 bytes of kernel
- SHA256_Init(&ctx);
- SHA256_Update(&ctx, (unsigned char*)&it[0], 8 + 16);
-}
-
-
-class ScanMidstateWorker
-{
-public:
- ScanMidstateWorker()
- { }
- ScanMidstateWorker(SHA256_CTX ctx, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, uint32_t nIntervalBegin, uint32_t nIntervalEnd)
- {
- workerSolutions = vector<std::pair<uint256,uint32_t> >();
-
- workerCtx = ctx;
- this->nBits = nBits;
- this->nInputTxTime = nInputTxTime;
- this->nValueIn = nValueIn;
- this->nIntervalBegin = nIntervalBegin;
- this->nIntervalEnd = nIntervalEnd;
- }
-
- void Do()
+ solutions.clear();
{
- SetThreadPriority(THREAD_PRIORITY_LOWEST);
-
- CBigNum bnTargetPerCoinDay;
- bnTargetPerCoinDay.SetCompact(nBits);
+ using namespace boost;
- // Get maximum possible target to filter out the majority of obviously insufficient hashes
- CBigNum bnMaxTargetPerCoinDay = bnTargetPerCoinDay * CBigNum(nValueIn) * nStakeMaxAge / COIN / (24 * 60 * 60);
- uint256 maxTarget = bnMaxTargetPerCoinDay.getuint256();
-
- SHA256_CTX ctx = workerCtx;
+ 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 forward in time from the given timestamp
- // Stopping search in case of shutting down
- for (uint32_t nTimeTx=nIntervalBegin; nTimeTx<nIntervalEnd && !fShutdown; nTimeTx++)
+ for(size_t i = 0; i < vWorkers.size(); i++)
{
- // Complete first hashing iteration
- uint256 hash1;
- SHA256_Update(&ctx, (unsigned char*)&nTimeTx, 4);
- SHA256_Final((unsigned char*)&hash1, &ctx);
-
- // Restore context
- ctx = workerCtx;
-
- // Finally, calculate kernel hash
- uint256 hashProofOfStake;
- SHA256((unsigned char*)&hash1, sizeof(hashProofOfStake), (unsigned char*)&hashProofOfStake);
-
+ auto nBegin = SearchInterval.first + nPart * i;
+ auto nEnd = SearchInterval.first + nPart * (i + 1);
- // Skip if hash doesn't satisfy the maximum target
- if (hashProofOfStake > maxTarget)
- continue;
-
- CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)nInputTxTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
- CBigNum bnTargetProofOfStake = bnCoinDayWeight * bnTargetPerCoinDay;
-
- if (bnTargetProofOfStake >= CBigNum(hashProofOfStake))
- {
- workerSolutions.push_back(std::pair<uint256,uint32_t>(hashProofOfStake, nTimeTx));
- }
+ vWorkers[i] = KernelWorker(kernel, nBits, nInputTxTime, nValueIn, nBegin, nEnd);
+ auto workerFnc = bind(&KernelWorker::Do, &vWorkers[i]);
+ group.create_thread(workerFnc);
}
- }
-
- vector<std::pair<uint256,uint32_t> >& GetSolutions()
- {
- return workerSolutions;
- }
-
-private:
- SHA256_CTX workerCtx;
- std::vector<std::pair<uint256,uint32_t> > workerSolutions;
-
- uint32_t nBits;
- uint32_t nInputTxTime;
- int64_t nValueIn;
- uint32_t nIntervalBegin;
- uint32_t nIntervalEnd;
-};
-
-// Scan given midstate for solution
-bool ScanMidstateForward(SHA256_CTX &ctx, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, std::pair<uint32_t, uint32_t> &SearchInterval, std::vector<std::pair<uint256, uint32_t> > &solutions)
-{
- // TODO: custom threads amount
- uint32_t nThreads = boost::thread::hardware_concurrency();
- uint32_t nPart = (SearchInterval.second - SearchInterval.first) / nThreads;
+ group.join_all();
- ScanMidstateWorker *workers = new ScanMidstateWorker[nThreads];
-
- boost::thread_group group;
- for(size_t i = 0; i < nThreads; i++)
- {
- uint32_t nBegin = SearchInterval.first + nPart * i;
- uint32_t nEnd = SearchInterval.first + nPart * (i + 1);
-
- workers[i] = ScanMidstateWorker(ctx, nBits, nInputTxTime, nValueIn, nBegin, nEnd);
-
- boost::function<void()> workerFnc = boost::bind(&ScanMidstateWorker::Do, &workers[i]);
- group.create_thread(workerFnc);
- }
-
- group.join_all();
- solutions.clear();
-
- for(size_t i = 0; i < nThreads; i++)
- {
- std::vector<std::pair<uint256, uint32_t> > ws = workers[i].GetSolutions();
- solutions.insert(solutions.end(), ws.begin(), ws.end());
- }
-
- delete [] workers;
-
- if (solutions.size() == 0)
- {
- // no solutions
- return false;
- }
-
- return true;
-}
-
-// Scan given midstate for solution
-bool ScanMidstateBackward(SHA256_CTX &ctx, uint32_t nBits, uint32_t nInputTxTime, int64_t nValueIn, std::pair<uint32_t, uint32_t> &SearchInterval, std::pair<uint256, uint32_t> &solution)
-{
- CBigNum bnTargetPerCoinDay;
- bnTargetPerCoinDay.SetCompact(nBits);
-
- // Get maximum possible target to filter out the majority of obviously insufficient hashes
- CBigNum bnMaxTargetPerCoinDay = bnTargetPerCoinDay * CBigNum(nValueIn) * nStakeMaxAge / COIN / (24 * 60 * 60);
- uint256 maxTarget = bnMaxTargetPerCoinDay.getuint256();
-
- SHA256_CTX ctxCopy = ctx;
-
- // Search backward in time from the given timestamp
- // Stopping search in case of shutting down
- for (uint32_t nTimeTx=SearchInterval.first; nTimeTx>SearchInterval.second && !fShutdown; nTimeTx--)
- {
- // Complete first hashing iteration
- uint256 hash1;
- SHA256_Update(&ctxCopy, (unsigned char*)&nTimeTx, 4);
- SHA256_Final((unsigned char*)&hash1, &ctxCopy);
-
- // Restore context
- ctxCopy = ctx;
-
- // Finally, calculate kernel hash
- uint256 hashProofOfStake;
- SHA256((unsigned char*)&hash1, sizeof(hashProofOfStake), (unsigned char*)&hashProofOfStake);
-
- // Skip if hash doesn't satisfy the maximum target
- if (hashProofOfStake > maxTarget)
- continue;
-
- CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)nInputTxTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
- CBigNum bnTargetProofOfStake = bnCoinDayWeight * bnTargetPerCoinDay;
-
- if (bnTargetProofOfStake >= CBigNum(hashProofOfStake))
+ for(auto& worker : vWorkers)
{
- solution.first = hashProofOfStake;
- solution.second = nTimeTx;
-
- return true;
+ 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 static_cast<uint32_t>(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;