123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310 |
- // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
- #include <boost/assign/list_of.hpp>
- #include "kernel.h"
- #include "txdb.h"
- using namespace std;
- extern int nStakeMaxAge;
- extern int nStakeTargetSpacing;
- typedef std::map<int, unsigned int> MapModifierCheckpoints;
- static std::map<int, unsigned int> mapStakeModifierCheckpoints =
- boost::assign::map_list_of
- ( 0, 0x0e00670b )
- ;
- static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
- boost::assign::map_list_of
- ( 0, 0x0e00670b )
- ;
- int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
- {
- return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
- }
- static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
- {
- if (!pindex)
- return error("GetLastStakeModifier: null pindex");
- while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
- pindex = pindex->pprev;
- if (!pindex->GeneratedStakeModifier())
- return error("GetLastStakeModifier: no generation at genesis block");
- nStakeModifier = pindex->nStakeModifier;
- nModifierTime = pindex->GetBlockTime();
- return true;
- }
- static int64 GetStakeModifierSelectionIntervalSection(int nSection)
- {
- assert (nSection >= 0 && nSection < 64);
- return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
- }
- static int64 GetStakeModifierSelectionInterval()
- {
- int64 nSelectionInterval = 0;
- for (int nSection=0; nSection<64; nSection++)
- nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
- return nSelectionInterval;
- }
- static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
- int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
- {
- bool fSelected = false;
- uint256 hashBest = 0;
- *pindexSelected = (const CBlockIndex*) 0;
- BOOST_FOREACH(const PAIRTYPE(int64, uint256)& 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];
- if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
- break;
- if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
- continue;
- uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
- CDataStream ss(SER_GETHASH, 0);
- ss << hashProof << nStakeModifierPrev;
- uint256 hashSelection = Hash(ss.begin(), ss.end());
- if (pindex->IsProofOfStake())
- hashSelection >>= 32;
- if (fSelected && hashSelection < hashBest)
- {
- hashBest = hashSelection;
- *pindexSelected = (const CBlockIndex*) pindex;
- }
- else if (!fSelected)
- {
- fSelected = true;
- hashBest = hashSelection;
- *pindexSelected = (const CBlockIndex*) pindex;
- }
- }
- if (fDebug && GetBoolArg("-printstakemodifier"))
- printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
- return fSelected;
- }
- bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
- {
- nStakeModifier = 0;
- fGeneratedStakeModifier = false;
- if (!pindexPrev)
- {
- fGeneratedStakeModifier = true;
- return true; // genesis block's modifier is 0
- }
- int64 nModifierTime = 0;
- if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
- return error("ComputeNextStakeModifier: unable to get last modifier");
- if (fDebug)
- {
- printf("ComputeNextStakeModifier: prev modifier=0x%016" PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
- }
- if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
- return true;
- vector<pair<int64, uint256> > vSortedByTimestamp;
- vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
- int64 nSelectionInterval = GetStakeModifierSelectionInterval();
- int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
- const CBlockIndex* pindex = pindexPrev;
- while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
- {
- vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
- pindex = pindex->pprev;
- }
- int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
- reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
- sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
- uint64 nStakeModifierNew = 0;
- int64 nSelectionIntervalStop = nSelectionIntervalStart;
- map<uint256, const CBlockIndex*> mapSelectedBlocks;
- for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
- {
- nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
- if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
- return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
- nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
- mapSelectedBlocks.insert(make_pair(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());
- }
- if (fDebug && GetBoolArg("-printstakemodifier"))
- {
- string strSelectionMap = "";
- strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
- pindex = pindexPrev;
- while (pindex && pindex->nHeight >= nHeightFirstCandidate)
- {
- if (pindex->IsProofOfStake())
- strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
- pindex = pindex->pprev;
- }
- BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
- {
- strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
- }
- printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
- }
- if (fDebug)
- {
- printf("ComputeNextStakeModifier: new modifier=0x%016" PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
- }
- nStakeModifier = nStakeModifierNew;
- fGeneratedStakeModifier = true;
- return true;
- }
- static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
- {
- nStakeModifier = 0;
- if (!mapBlockIndex.count(hashBlockFrom))
- return error("GetKernelStakeModifier() : block not indexed");
- const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
- nStakeModifierHeight = pindexFrom->nHeight;
- nStakeModifierTime = pindexFrom->GetBlockTime();
- int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
- const CBlockIndex* pindex = pindexFrom;
- while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
- {
- if (!pindex->pnext)
- { // reached best block; may happen if node is behind on block chain
- if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
- return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
- pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
- else
- return false;
- }
- pindex = pindex->pnext;
- if (pindex->GeneratedStakeModifier())
- {
- nStakeModifierHeight = pindex->nHeight;
- nStakeModifierTime = pindex->GetBlockTime();
- }
- }
- nStakeModifier = pindex->nStakeModifier;
- return true;
- }
- bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake)
- {
- if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
- return error("CheckStakeKernelHash() : nTime violation");
- unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
- if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
- return error("CheckStakeKernelHash() : min age violation");
- CBigNum bnTargetPerCoinDay;
- bnTargetPerCoinDay.SetCompact(nBits);
- int64 nValueIn = txPrev.vout[prevout.n].nValue;
- uint256 hashBlockFrom = blockFrom.GetHash();
- CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
- targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
- // Calculate hash
- CDataStream ss(SER_GETHASH, 0);
- uint64 nStakeModifier = 0;
- int nStakeModifierHeight = 0;
- int64 nStakeModifierTime = 0;
- if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
- return false;
- ss << nStakeModifier;
- ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
- hashProofOfStake = Hash(ss.begin(), ss.end());
- if (fPrintProofOfStake)
- {
- printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
- nStakeModifier, nStakeModifierHeight,
- DateTimeStrFormat(nStakeModifierTime).c_str(),
- mapBlockIndex[hashBlockFrom]->nHeight,
- DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
- printf("CheckStakeKernelHash() : check modifier=0x%016" PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
- nStakeModifier,
- nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
- hashProofOfStake.ToString().c_str());
- }
- if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
- return false;
- if (fDebug && !fPrintProofOfStake)
- {
- printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
- nStakeModifier, nStakeModifierHeight,
- DateTimeStrFormat(nStakeModifierTime).c_str(),
- mapBlockIndex[hashBlockFrom]->nHeight,
- DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
- printf("CheckStakeKernelHash() : pass modifier=0x%016" PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
- nStakeModifier,
- nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
- hashProofOfStake.ToString().c_str());
- }
- return true;
- }
- bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
- {
- if (!tx.IsCoinStake())
- return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
- const CTxIn& txin = tx.vin[0];
- CTxDB txdb("r");
- CTransaction txPrev;
- CTxIndex txindex;
- if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
- return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
- if (!VerifySignature(txPrev, tx, 0, true, 0))
- return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
- CBlock block;
- if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
- return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
- if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
- return tx.DoS(1, error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str())); // may occur during initial download or if behind on block chain sync
- return true;
- }
- bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
- {
- return (nTimeBlock == nTimeTx);
- }
- unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
- {
- assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
- CDataStream ss(SER_GETHASH, 0);
- if (pindex->pprev)
- ss << pindex->pprev->nStakeModifierChecksum;
- ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
- uint256 hashChecksum = Hash(ss.begin(), ss.end());
- hashChecksum >>= (256 - 32);
- return hashChecksum.Get64();
- }
- bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
- {
- MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
- if (checkpoints.count(nHeight)){
- return nStakeModifierChecksum == checkpoints[nHeight];
- }
- return true;
- }
|