1 // Copyright (c) 2012-2013 The PPCoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <boost/assign/list_of.hpp>
10 extern unsigned int nStakeMaxAge;
11 extern unsigned int nStakeTargetSpacing;
16 // Protocol switch time for fixed kernel modifier interval
17 unsigned int nModifierSwitchTime = 1413763200; // Mon, 20 Oct 2014 00:00:00 GMT
18 unsigned int nModifierTestSwitchTime = 1397520000; // Tue, 15 Apr 2014 00:00:00 GMT
20 // Note: user must upgrade before the protocol switch deadline, otherwise it's required to
21 // re-download the blockchain. The timestamp of upgrade is recorded in the blockchain
23 unsigned int nModifierUpgradeTime = 0;
25 typedef std::map<int, unsigned int> MapModifierCheckpoints;
27 // Hard checkpoints of stake modifiers to ensure they are deterministic
28 static std::map<int, unsigned int> mapStakeModifierCheckpoints =
29 boost::assign::map_list_of
31 ( 12661, 0x5d84115du )
32 (143990, 0x9c592c78u )
33 (149000, 0x48f2bdc4u )
34 (160000, 0x789df0f0u )
37 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
38 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
39 boost::assign::map_list_of
43 // Pregenerated entropy bits table (from genesis to #9689)
45 // Bits are packed into array of 256 bit integers:
47 // * array index calculated as nHeight / 256
48 // * position of bit is calculated as nHeight & 0xFF.
50 const uint256 entropyStore[] = {
51 uint256("0x4555b4dcc1d690ddd9b810c90c66e82b18bf4f43cc887246c418383ec120a5ab"),
52 uint256("0xaa6d1198412fa77608addf6549c9198a22155e8afd7a9ded6179f6b7cfc66b0c"),
53 uint256("0x9442fabfa4116fb14a9769c2eea003845a1f5c3a0260f36b497d68f3a3cd4078"),
54 uint256("0x0e769042a9a98e42388195d699574b822d06515f7053ad884c53d7ee059f05b1"),
55 uint256("0x7005aac20baf70251aebfe3f1b95987d83ef1e3e6963de8fed601d4dd07bf7cf"),
56 uint256("0x58952c5c3de188f2e33c38d3f53d7bf44f9bc545a4289d266696273fa821be66"),
57 uint256("0x50b6c2ed780c08aaec3f7665b1b6004206243e3866456fc910b83b52d07eeb63"),
58 uint256("0x563841eefca85ba3384986c58100408ae3f1ba2ac727e1ac910ce154a06c702f"),
59 uint256("0x79275b03938b3e27a9b01a7f7953c6c487c58355f5d4169accfbb800213ffd13"),
60 uint256("0xd783f2538b3ed18f135af90adc687c5646d93aeaeaabc6667be94f7aa0a2d366"),
61 uint256("0xb441d0c175c40c8e88b09d88ea008af79cbed2d28219427d2e72fda682974db8"),
62 uint256("0x3204c43bd41f2e19628af3b0c9aca3db15bca4c8705d51056e7b17a319c04715"),
63 uint256("0x7e80e6ab7857d8f2f261a0a49c783bd800b365b8c9b85cc0e13f73904b0dcaa9"),
64 uint256("0xefaaee60ed82d2ad145c0e347941fdb131eb8fd289a45eef07121a93f283c5f1"),
65 uint256("0x3efc86e4334da332c1fd4c12513c40cff689f3efdc7f9913230822adacdda4f9"),
66 uint256("0xf0d6b8f38599a017fa35d1fbbf9ef51eca5ebc5b286aadba40c4c3e1d9bace0c"),
67 uint256("0x286a67f27323486036a0a92d35382fc8963c0c00bad331723318b4b9fdb2b56e"),
68 uint256("0xecbfaaa6567c54f08c4d5bd0118a2d7b58740f42cbfc73aa1536c1f5f76de87c"),
69 uint256("0xf9a4de1c5c46520de5aaf10d3796cf0e27ddce98b3398357f5726a949664e308"),
70 uint256("0xd75e6c4dc4be08401e3478d2467d9ab96a62af4f255c04a82c41af0de0a487bb"),
71 uint256("0x1a82c3bc6ad6047294c16571b5e2b7316c97bf8813e7da15798b9820d67e39f2"),
72 uint256("0xb49be0080de564e01829ded7e7971979565a741c5975dc9978dcc020192d396c"),
73 uint256("0x0d8eed113be67663b5a15a0625a9b49792b5ea59c005c4f405914877acab7000"),
74 uint256("0x8f9d46e2bc05a218ffa942965b747056197d393b097085523640cd59e07fe7c7"),
75 uint256("0x7a63ab40bc7f40ac2ebe9ede438d97b45fa6ed6f8419016da8d5f7a670111dda"),
76 uint256("0x63fbcc080448c43d6cf915c958314feff7a95a52ba43a68c05fc281d3a522d25"),
77 uint256("0xf834cf824c326d3ea861ea1e85dc3289265e37045981e28208e7344a7f8081d7"),
78 uint256("0xb4edc22ec98cc49b2f5af5bae3f52f5e6058280f74f2c432c2dd89ae49acceb8"),
79 uint256("0x0fe596037dcf81bf5c64f39755261c404ed088af5c8c31dd7549b6657ee92365"),
80 uint256("0xbbad51a0aeba254b01d18c328de9e932b9b859b61e622c325d64e2211b5e413d"),
81 uint256("0xabf0194cc787be938bc51c7fdf1cae4ec79e65ebab8fa8b8f40541c44ef384b0"),
82 uint256("0x83bc12d6fdbd3e854cb91c4ca7dfba3c38e8714121af88c8a8abdb33e5002438"),
83 uint256("0x71a2513026cabaedcbe55aeb6dc8049e5b763a3f54f10c33dd333624f764b38c"),
84 uint256("0xee6725632ff5c025dff6a18cd059875dcae20f399b03bccba13d9d5fcf6d9d9a"),
85 uint256("0xa168a2741d1e7e50cc74b79f695c25ffd3576e6bd61353c2a20e569fd63b2dac"),
86 uint256("0x6e462d2a87bfde9398b6747f94a8ed6a01e4d96c5b4372df5c910c106c48bd13"),
87 uint256("0x8eeb696181957c4b22434028990f49cb30006827c73860e77e2eecf5c38be99d"),
88 uint256("0x3188aaa65877b166f05cdc48f55b1f77a7d6fb221c395596d990ae5647e9ba96")
91 // Whether the given block is subject to new modifier protocol
92 bool IsFixedModifierInterval(unsigned int nTimeBlock)
94 return (nTimeBlock >= (fTestNet? nModifierTestSwitchTime : nModifierSwitchTime));
98 int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
100 // Kernel hash weight starts from 0 at the 30-day min age
101 // this change increases active coins participating the hash and helps
102 // to secure the network when proof-of-stake difficulty is low
104 // Maximum TimeWeight is 90 days.
106 return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64_t)nStakeMaxAge);
109 // Get the last stake modifier and its generation time from a given block
110 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
113 return error("GetLastStakeModifier: null pindex");
114 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
115 pindex = pindex->pprev;
116 if (!pindex->GeneratedStakeModifier())
117 return error("GetLastStakeModifier: no generation at genesis block");
118 nStakeModifier = pindex->nStakeModifier;
119 nModifierTime = pindex->GetBlockTime();
123 // Get selection interval section (in seconds)
124 static int64_t GetStakeModifierSelectionIntervalSection(int nSection)
126 assert (nSection >= 0 && nSection < 64);
127 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
130 // Get stake modifier selection interval (in seconds)
131 static int64_t GetStakeModifierSelectionInterval()
133 int64_t nSelectionInterval = 0;
134 for (int nSection=0; nSection<64; nSection++)
135 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
136 return nSelectionInterval;
139 // select a block from the candidate blocks in vSortedByTimestamp, excluding
140 // already selected blocks in vSelectedBlocks, and with timestamp up to
141 // nSelectionIntervalStop.
142 static bool SelectBlockFromCandidates(vector<pair<int64_t, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
143 int64_t nSelectionIntervalStop, uint64_t nStakeModifierPrev, const CBlockIndex** pindexSelected)
145 bool fSelected = false;
146 uint256 hashBest = 0;
147 *pindexSelected = (const CBlockIndex*) 0;
148 BOOST_FOREACH(const PAIRTYPE(int64_t, uint256)& item, vSortedByTimestamp)
150 if (!mapBlockIndex.count(item.second))
151 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
152 const CBlockIndex* pindex = mapBlockIndex[item.second];
153 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
155 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
157 // compute the selection hash by hashing its proof-hash and the
158 // previous proof-of-stake modifier
159 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
160 CDataStream ss(SER_GETHASH, 0);
161 ss << hashProof << nStakeModifierPrev;
162 uint256 hashSelection = Hash(ss.begin(), ss.end());
163 // the selection hash is divided by 2**32 so that proof-of-stake block
164 // is always favored over proof-of-work block. this is to preserve
165 // the energy efficiency property
166 if (pindex->IsProofOfStake())
167 hashSelection >>= 32;
168 if (fSelected && hashSelection < hashBest)
170 hashBest = hashSelection;
171 *pindexSelected = (const CBlockIndex*) pindex;
176 hashBest = hashSelection;
177 *pindexSelected = (const CBlockIndex*) pindex;
180 if (fDebug && GetBoolArg("-printstakemodifier"))
181 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
185 // Stake Modifier (hash modifier of proof-of-stake):
186 // The purpose of stake modifier is to prevent a txout (coin) owner from
187 // computing future proof-of-stake generated by this txout at the time
188 // of transaction confirmation. To meet kernel protocol, the txout
189 // must hash with a future stake modifier to generate the proof.
190 // Stake modifier consists of bits each of which is contributed from a
191 // selected block of a given block group in the past.
192 // The selection of a block is based on a hash of the block's proof-hash and
193 // the previous stake modifier.
194 // Stake modifier is recomputed at a fixed time interval instead of every
195 // block. This is to make it difficult for an attacker to gain control of
196 // additional bits in the stake modifier, even after generating a chain of
198 bool ComputeNextStakeModifier(const CBlockIndex* pindexCurrent, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier)
201 fGeneratedStakeModifier = false;
202 const CBlockIndex* pindexPrev = pindexCurrent->pprev;
205 fGeneratedStakeModifier = true;
206 return true; // genesis block's modifier is 0
209 // First find current stake modifier and its generation block time
210 // if it's not old enough, return the same stake modifier
211 int64_t nModifierTime = 0;
212 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
213 return error("ComputeNextStakeModifier: unable to get last modifier");
216 printf("ComputeNextStakeModifier: prev modifier=0x%016" PRIx64 " time=%s epoch=%u\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str(), (unsigned int)nModifierTime);
218 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
222 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexPrev nHeight=%d nTime=%u\n", pindexPrev->nHeight, (unsigned int)pindexPrev->GetBlockTime());
226 if (nModifierTime / nModifierInterval >= pindexCurrent->GetBlockTime() / nModifierInterval)
228 // fixed interval protocol requires current block timestamp also be in a different modifier interval
229 if (IsFixedModifierInterval(pindexCurrent->nTime))
233 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
241 printf("ComputeNextStakeModifier: old modifier at block %s not meeting fixed modifier interval: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->GetBlockHash().ToString().c_str(), pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
246 // Sort candidate blocks by timestamp
247 vector<pair<int64_t, uint256> > vSortedByTimestamp;
248 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
249 int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
250 int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
251 const CBlockIndex* pindex = pindexPrev;
252 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
254 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
255 pindex = pindex->pprev;
257 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
258 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
259 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
261 // Select 64 blocks from candidate blocks to generate stake modifier
262 uint64_t nStakeModifierNew = 0;
263 int64_t nSelectionIntervalStop = nSelectionIntervalStart;
264 map<uint256, const CBlockIndex*> mapSelectedBlocks;
265 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
267 // add an interval section to the current selection round
268 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
269 // select a block from the candidates of current round
270 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
271 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
272 // write the entropy bit of the selected block
273 nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
274 // add the selected block from candidates to selected list
275 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
276 if (fDebug && GetBoolArg("-printstakemodifier"))
277 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
280 // Print selection map for visualization of the selected blocks
281 if (fDebug && GetBoolArg("-printstakemodifier"))
283 string strSelectionMap = "";
284 // '-' indicates proof-of-work blocks not selected
285 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
287 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
289 // '=' indicates proof-of-stake blocks not selected
290 if (pindex->IsProofOfStake())
291 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
292 pindex = pindex->pprev;
294 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
296 // 'S' indicates selected proof-of-stake blocks
297 // 'W' indicates selected proof-of-work blocks
298 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
300 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
304 printf("ComputeNextStakeModifier: new modifier=0x%016" PRIx64 " time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
307 nStakeModifier = nStakeModifierNew;
308 fGeneratedStakeModifier = true;
312 // The stake modifier used to hash for a stake kernel is chosen as the stake
313 // modifier about a selection interval later than the coin generating the kernel
314 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
317 if (!mapBlockIndex.count(hashBlockFrom))
318 return error("GetKernelStakeModifier() : block not indexed");
319 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
320 nStakeModifierHeight = pindexFrom->nHeight;
321 nStakeModifierTime = pindexFrom->GetBlockTime();
322 int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
323 const CBlockIndex* pindex = pindexFrom;
324 // loop to find the stake modifier later by a selection interval
325 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
328 { // reached best block; may happen if node is behind on block chain
329 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
330 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
331 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
335 pindex = pindex->pnext;
336 if (pindex->GeneratedStakeModifier())
338 nStakeModifierHeight = pindex->nHeight;
339 nStakeModifierTime = pindex->GetBlockTime();
342 nStakeModifier = pindex->nStakeModifier;
346 bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier)
348 int nStakeModifierHeight;
349 int64_t nStakeModifierTime;
351 return GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, false);
355 // ppcoin kernel protocol
356 // coinstake must meet hash target according to the protocol:
357 // kernel (input 0) must meet the formula
358 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
359 // this ensures that the chance of getting a coinstake is proportional to the
360 // amount of coin age one owns.
361 // The reason this hash is chosen is the following:
362 // nStakeModifier: scrambles computation to make it very difficult to precompute
363 // future proof-of-stake at the time of the coin's confirmation
364 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
365 // generate transaction for future advantage
366 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
367 // nodes generating coinstake at the same time
368 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
370 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
371 // generating coinstake at the same time
372 // block/tx hash should not be used here as they can be generated in vast
373 // quantities so as to generate blocks faster, degrading the system back into
374 // a proof-of-work situation.
376 bool CheckStakeKernelHash(uint32_t nBits, const CBlock& blockFrom, uint32_t nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, uint32_t nTimeTx, uint256& hashProofOfStake, uint256& targetProofOfStake, bool fPrintProofOfStake)
378 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
379 return error("CheckStakeKernelHash() : nTime violation");
381 uint32_t nTimeBlockFrom = blockFrom.GetBlockTime();
382 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
383 return error("CheckStakeKernelHash() : min age violation");
385 CBigNum bnTargetPerCoinDay;
386 bnTargetPerCoinDay.SetCompact(nBits);
387 int64_t nValueIn = txPrev.vout[prevout.n].nValue;
389 uint256 hashBlockFrom = blockFrom.GetHash();
391 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)txPrev.nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
392 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
395 CDataStream ss(SER_GETHASH, 0);
396 uint64_t nStakeModifier = 0;
397 int nStakeModifierHeight = 0;
398 int64_t nStakeModifierTime = 0;
400 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
402 ss << nStakeModifier;
404 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
405 hashProofOfStake = Hash(ss.begin(), ss.end());
406 if (fPrintProofOfStake)
408 printf("CheckStakeKernelHash() : using modifier 0x%016" PRIx64 " at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
409 nStakeModifier, nStakeModifierHeight,
410 DateTimeStrFormat(nStakeModifierTime).c_str(),
411 mapBlockIndex[hashBlockFrom]->nHeight,
412 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
413 printf("CheckStakeKernelHash() : check modifier=0x%016" PRIx64 " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
415 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
416 hashProofOfStake.ToString().c_str());
419 // Now check if proof-of-stake hash meets target protocol
420 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
422 if (fDebug && !fPrintProofOfStake)
424 printf("CheckStakeKernelHash() : using modifier 0x%016" PRIx64 " at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
425 nStakeModifier, nStakeModifierHeight,
426 DateTimeStrFormat(nStakeModifierTime).c_str(),
427 mapBlockIndex[hashBlockFrom]->nHeight,
428 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
429 printf("CheckStakeKernelHash() : pass modifier=0x%016" PRIx64 " nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
431 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
432 hashProofOfStake.ToString().c_str());
437 // Scan given coins set for kernel solution
438 bool ScanForStakeKernelHash(MetaMap &mapMeta, uint32_t nBits, uint32_t nTime, uint32_t nSearchInterval, CoinsSet::value_type &kernelcoin, uint32_t &nTimeTx, uint32_t &nBlockTime, uint64_t &nKernelsTried, uint64_t &nCoinDaysTried)
440 uint256 hashProofOfStake = 0;
442 // (txid, vout.n) => ((txindex, (tx, vout.n)), (block, modifier))
443 for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
445 if (!fCoinsDataActual)
448 CTxIndex txindex = (*meta_item).second.first.first;
449 CBlock block = (*meta_item).second.second.first;
450 uint64_t nStakeModifier = (*meta_item).second.second.second;
453 CoinsSet::value_type pcoin = meta_item->second.first.second;
455 static unsigned int nMaxStakeSearchInterval = 60;
457 // only count coins meeting min age requirement
458 if (nStakeMinAge + block.nTime > nTime - nMaxStakeSearchInterval)
461 // Transaction offset inside block
462 uint32_t nTxOffset = txindex.pos.nTxPos - txindex.pos.nBlockPos;
464 // Current timestamp scanning interval
465 unsigned int nCurrentSearchInterval = min(nSearchInterval, nMaxStakeSearchInterval);
467 nBlockTime = block.nTime;
468 CBigNum bnTargetPerCoinDay;
469 bnTargetPerCoinDay.SetCompact(nBits);
470 int64_t nValueIn = pcoin.first->vout[pcoin.second].nValue;
472 // Search backward in time from the given timestamp
473 // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
474 // Stopping search in case of shutting down or cache invalidation
475 for (unsigned int n=0; n<nCurrentSearchInterval && fCoinsDataActual && !fShutdown; n++)
478 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)pcoin.first->nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
479 CBigNum bnTargetProofOfStake = bnCoinDayWeight * bnTargetPerCoinDay;
482 CDataStream ss(SER_GETHASH, 0);
483 ss << nStakeModifier;
484 ss << nBlockTime << nTxOffset << pcoin.first->nTime << pcoin.second << nTimeTx;
486 // Calculate kernel hash
487 hashProofOfStake = Hash(ss.begin(), ss.end());
491 nCoinDaysTried += bnCoinDayWeight.getuint64();
493 if (bnTargetProofOfStake >= CBigNum(hashProofOfStake))
496 printf("nStakeModifier=0x%016" PRIx64 ", nBlockTime=%u nTxOffset=%u nTxPrevTime=%u nVout=%u nTimeTx=%u hashProofOfStake=%s Success=true\n",
497 nStakeModifier, nBlockTime, nTxOffset, pcoin.first->nTime, pcoin.second, nTimeTx, hashProofOfStake.GetHex().c_str());
504 printf("nStakeModifier=0x%016" PRIx64 ", nBlockTime=%u nTxOffset=%u nTxPrevTime=%u nTxNumber=%u nTimeTx=%u hashProofOfStake=%s Success=false\n",
505 nStakeModifier, nBlockTime, nTxOffset, pcoin.first->nTime, pcoin.second, nTimeTx, hashProofOfStake.GetHex().c_str());
512 // Scan given input for kernel solution
513 bool ScanInputForStakeKernelHash(CTransaction &tx, uint32_t nOut, uint32_t nBits, uint32_t nSearchInterval, std::pair<uint256, uint32_t> &solution)
520 // Load transaction index item
521 if (!txdb.ReadTxIndex(tx.GetHash(), txindex))
525 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
528 uint64_t nStakeModifier = 0;
529 if (!GetKernelStakeModifier(block.GetHash(), nStakeModifier))
532 uint32_t nTime = GetTime();
533 // Only count coins meeting min age requirement
534 if (nStakeMinAge + block.nTime > nTime)
535 nTime += (nStakeMinAge + block.nTime - nTime);
537 // Transaction offset inside block
538 uint32_t nTxOffset = txindex.pos.nTxPos - txindex.pos.nBlockPos;
539 int64_t nValueIn = tx.vout[nOut].nValue;
541 CBigNum bnTargetPerCoinDay;
542 bnTargetPerCoinDay.SetCompact(nBits);
544 // Get maximum possible target to filter out the majority of obviously insufficient hashes
545 CBigNum bnMaxTargetPerCoinDay = bnTargetPerCoinDay * CBigNum(nValueIn) * nStakeMaxAge / COIN / (24 * 60 * 60);
546 uint256 maxTarget = bnMaxTargetPerCoinDay.getuint256();
549 // Build static part of kernel
550 CDataStream ssKernel(SER_GETHASH, 0);
551 ssKernel << nStakeModifier;
552 ssKernel << block.nTime << nTxOffset << tx.nTime << nOut;
553 CDataStream::const_iterator it = ssKernel.begin();
555 // Init sha256 context and update it
556 // with first 16 bytes of kernel
557 SHA256_CTX ctxCurrent;
558 SHA256_Init(&ctxCurrent);
559 SHA256_Update(&ctxCurrent, (unsigned char*)&it[0], 8 + 16);
560 SHA256_CTX ctxCopy = ctxCurrent;
562 // Search forward in time from the given timestamp
563 // Stopping search in case of shutting down
564 for (uint32_t nTimeTx=nTime; nTimeTx<nTime+nSearchInterval && !fShutdown; nTimeTx++)
566 // Complete first hashing iteration
568 SHA256_Update(&ctxCurrent, (unsigned char*)&nTimeTx, 4);
569 SHA256_Final((unsigned char*)&hash1, &ctxCurrent);
571 // Restore old context
572 ctxCurrent = ctxCopy;
574 // Finally, calculate kernel hash
575 uint256 hashProofOfStake;
576 SHA256((unsigned char*)&hash1, sizeof(hashProofOfStake), (unsigned char*)&hashProofOfStake);
578 // Skip if hash doesn't satisfy the maximum target
579 if (hashProofOfStake > maxTarget)
582 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64_t)tx.nTime, (int64_t)nTimeTx) / COIN / (24 * 60 * 60);
583 CBigNum bnTargetProofOfStake = bnCoinDayWeight * bnTargetPerCoinDay;
585 if (bnTargetProofOfStake >= CBigNum(hashProofOfStake))
587 solution.first = hashProofOfStake;
588 solution.second = nTimeTx;
597 // Check kernel hash target and coinstake signature
598 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
600 if (!tx.IsCoinStake())
601 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
603 // Kernel (input 0) must match the stake hash target per coin age (nBits)
604 const CTxIn& txin = tx.vin[0];
606 // First try finding the previous transaction in database
610 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
611 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
618 if (!VerifySignature(txPrev, tx, 0, MANDATORY_SCRIPT_VERIFY_FLAGS, 0))
619 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
623 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
624 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
626 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
627 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
632 // Get stake modifier checksum
633 uint32_t GetStakeModifierChecksum(const CBlockIndex* pindex)
635 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
636 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
637 CDataStream ss(SER_GETHASH, 0);
639 ss << pindex->pprev->nStakeModifierChecksum;
640 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
641 uint256 hashChecksum = Hash(ss.begin(), ss.end());
642 hashChecksum >>= (256 - 32);
643 return hashChecksum.Get64();
646 // Check stake modifier hard checkpoints
647 bool CheckStakeModifierCheckpoints(int nHeight, uint32_t nStakeModifierChecksum)
649 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
651 if (checkpoints.count(nHeight))
652 return nStakeModifierChecksum == checkpoints[nHeight];