kernel.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. // ECOin - Copyright (c) - 2014/2022 - GPLv3 - epsylon@riseup.net (https://03c8.net)
  2. #include <boost/assign/list_of.hpp>
  3. #include "kernel.h"
  4. #include "txdb.h"
  5. using namespace std;
  6. extern int nStakeMaxAge;
  7. extern int nStakeTargetSpacing;
  8. typedef std::map<int, unsigned int> MapModifierCheckpoints;
  9. static std::map<int, unsigned int> mapStakeModifierCheckpoints =
  10. boost::assign::map_list_of
  11. ( 0, 0x0e00670b )
  12. ;
  13. static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
  14. boost::assign::map_list_of
  15. ( 0, 0x0e00670b )
  16. ;
  17. int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
  18. {
  19. return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
  20. }
  21. static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
  22. {
  23. if (!pindex)
  24. return error("GetLastStakeModifier: null pindex");
  25. while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
  26. pindex = pindex->pprev;
  27. if (!pindex->GeneratedStakeModifier())
  28. return error("GetLastStakeModifier: no generation at genesis block");
  29. nStakeModifier = pindex->nStakeModifier;
  30. nModifierTime = pindex->GetBlockTime();
  31. return true;
  32. }
  33. static int64 GetStakeModifierSelectionIntervalSection(int nSection)
  34. {
  35. assert (nSection >= 0 && nSection < 64);
  36. return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
  37. }
  38. static int64 GetStakeModifierSelectionInterval()
  39. {
  40. int64 nSelectionInterval = 0;
  41. for (int nSection=0; nSection<64; nSection++)
  42. nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
  43. return nSelectionInterval;
  44. }
  45. static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
  46. int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
  47. {
  48. bool fSelected = false;
  49. uint256 hashBest = 0;
  50. *pindexSelected = (const CBlockIndex*) 0;
  51. BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
  52. {
  53. if (!mapBlockIndex.count(item.second))
  54. return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
  55. const CBlockIndex* pindex = mapBlockIndex[item.second];
  56. if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
  57. break;
  58. if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
  59. continue;
  60. uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
  61. CDataStream ss(SER_GETHASH, 0);
  62. ss << hashProof << nStakeModifierPrev;
  63. uint256 hashSelection = Hash(ss.begin(), ss.end());
  64. if (pindex->IsProofOfStake())
  65. hashSelection >>= 32;
  66. if (fSelected && hashSelection < hashBest)
  67. {
  68. hashBest = hashSelection;
  69. *pindexSelected = (const CBlockIndex*) pindex;
  70. }
  71. else if (!fSelected)
  72. {
  73. fSelected = true;
  74. hashBest = hashSelection;
  75. *pindexSelected = (const CBlockIndex*) pindex;
  76. }
  77. }
  78. if (fDebug && GetBoolArg("-printstakemodifier"))
  79. printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
  80. return fSelected;
  81. }
  82. bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
  83. {
  84. nStakeModifier = 0;
  85. fGeneratedStakeModifier = false;
  86. if (!pindexPrev)
  87. {
  88. fGeneratedStakeModifier = true;
  89. return true; // genesis block's modifier is 0
  90. }
  91. int64 nModifierTime = 0;
  92. if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
  93. return error("ComputeNextStakeModifier: unable to get last modifier");
  94. if (fDebug)
  95. {
  96. printf("ComputeNextStakeModifier: prev modifier=0x%016" PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
  97. }
  98. if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
  99. return true;
  100. vector<pair<int64, uint256> > vSortedByTimestamp;
  101. vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
  102. int64 nSelectionInterval = GetStakeModifierSelectionInterval();
  103. int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
  104. const CBlockIndex* pindex = pindexPrev;
  105. while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
  106. {
  107. vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
  108. pindex = pindex->pprev;
  109. }
  110. int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
  111. reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
  112. sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
  113. uint64 nStakeModifierNew = 0;
  114. int64 nSelectionIntervalStop = nSelectionIntervalStart;
  115. map<uint256, const CBlockIndex*> mapSelectedBlocks;
  116. for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
  117. {
  118. nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
  119. if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
  120. return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
  121. nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
  122. mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
  123. if (fDebug && GetBoolArg("-printstakemodifier"))
  124. printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
  125. }
  126. if (fDebug && GetBoolArg("-printstakemodifier"))
  127. {
  128. string strSelectionMap = "";
  129. strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
  130. pindex = pindexPrev;
  131. while (pindex && pindex->nHeight >= nHeightFirstCandidate)
  132. {
  133. if (pindex->IsProofOfStake())
  134. strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
  135. pindex = pindex->pprev;
  136. }
  137. BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
  138. {
  139. strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
  140. }
  141. printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
  142. }
  143. if (fDebug)
  144. {
  145. printf("ComputeNextStakeModifier: new modifier=0x%016" PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
  146. }
  147. nStakeModifier = nStakeModifierNew;
  148. fGeneratedStakeModifier = true;
  149. return true;
  150. }
  151. static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
  152. {
  153. nStakeModifier = 0;
  154. if (!mapBlockIndex.count(hashBlockFrom))
  155. return error("GetKernelStakeModifier() : block not indexed");
  156. const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
  157. nStakeModifierHeight = pindexFrom->nHeight;
  158. nStakeModifierTime = pindexFrom->GetBlockTime();
  159. int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
  160. const CBlockIndex* pindex = pindexFrom;
  161. while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
  162. {
  163. if (!pindex->pnext)
  164. { // reached best block; may happen if node is behind on block chain
  165. if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
  166. return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
  167. pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
  168. else
  169. return false;
  170. }
  171. pindex = pindex->pnext;
  172. if (pindex->GeneratedStakeModifier())
  173. {
  174. nStakeModifierHeight = pindex->nHeight;
  175. nStakeModifierTime = pindex->GetBlockTime();
  176. }
  177. }
  178. nStakeModifier = pindex->nStakeModifier;
  179. return true;
  180. }
  181. 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)
  182. {
  183. if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
  184. return error("CheckStakeKernelHash() : nTime violation");
  185. unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
  186. if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
  187. return error("CheckStakeKernelHash() : min age violation");
  188. CBigNum bnTargetPerCoinDay;
  189. bnTargetPerCoinDay.SetCompact(nBits);
  190. int64 nValueIn = txPrev.vout[prevout.n].nValue;
  191. uint256 hashBlockFrom = blockFrom.GetHash();
  192. CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
  193. targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
  194. // Calculate hash
  195. CDataStream ss(SER_GETHASH, 0);
  196. uint64 nStakeModifier = 0;
  197. int nStakeModifierHeight = 0;
  198. int64 nStakeModifierTime = 0;
  199. if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
  200. return false;
  201. ss << nStakeModifier;
  202. ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
  203. hashProofOfStake = Hash(ss.begin(), ss.end());
  204. if (fPrintProofOfStake)
  205. {
  206. printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
  207. nStakeModifier, nStakeModifierHeight,
  208. DateTimeStrFormat(nStakeModifierTime).c_str(),
  209. mapBlockIndex[hashBlockFrom]->nHeight,
  210. DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
  211. printf("CheckStakeKernelHash() : check modifier=0x%016" PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
  212. nStakeModifier,
  213. nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
  214. hashProofOfStake.ToString().c_str());
  215. }
  216. if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
  217. return false;
  218. if (fDebug && !fPrintProofOfStake)
  219. {
  220. printf("CheckStakeKernelHash() : using modifier 0x%016" PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
  221. nStakeModifier, nStakeModifierHeight,
  222. DateTimeStrFormat(nStakeModifierTime).c_str(),
  223. mapBlockIndex[hashBlockFrom]->nHeight,
  224. DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
  225. printf("CheckStakeKernelHash() : pass modifier=0x%016" PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
  226. nStakeModifier,
  227. nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
  228. hashProofOfStake.ToString().c_str());
  229. }
  230. return true;
  231. }
  232. bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
  233. {
  234. if (!tx.IsCoinStake())
  235. return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
  236. const CTxIn& txin = tx.vin[0];
  237. CTxDB txdb("r");
  238. CTransaction txPrev;
  239. CTxIndex txindex;
  240. if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
  241. return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
  242. if (!VerifySignature(txPrev, tx, 0, true, 0))
  243. return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
  244. CBlock block;
  245. if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
  246. return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
  247. if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
  248. 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
  249. return true;
  250. }
  251. bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
  252. {
  253. return (nTimeBlock == nTimeTx);
  254. }
  255. unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
  256. {
  257. assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
  258. CDataStream ss(SER_GETHASH, 0);
  259. if (pindex->pprev)
  260. ss << pindex->pprev->nStakeModifierChecksum;
  261. ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
  262. uint256 hashChecksum = Hash(ss.begin(), ss.end());
  263. hashChecksum >>= (256 - 32);
  264. return hashChecksum.Get64();
  265. }
  266. bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
  267. {
  268. MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
  269. if (checkpoints.count(nHeight)){
  270. return nStakeModifierChecksum == checkpoints[nHeight];
  271. }
  272. return true;
  273. }