3b8e0517b6c82a1652499a74870ba9e935604d6a
[novacoin.git] / src / kernel.cpp
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.
4
5 #include <boost/assign/list_of.hpp>
6
7 #include "kernel.h"
8 #include "txdb.h"
9 #include "main.h"
10
11 using namespace std;
12
13
14 // Protocol switch time for fixed kernel modifier interval
15 unsigned int nModifierSwitchTime  = 1413763200;    // Mon, 20 Oct 2014 00:00:00 GMT
16 unsigned int nModifierTestSwitchTime = 1397520000; // Tue, 15 Apr 2014 00:00:00 GMT
17
18 // Note: user must upgrade before the protocol switch deadline, otherwise it's required to
19 //   re-download the blockchain. The timestamp of upgrade is recorded in the blockchain 
20 //   database.
21 unsigned int nModifierUpgradeTime = 0;
22
23 typedef std::map<int, unsigned int> MapModifierCheckpoints;
24
25 // Hard checkpoints of stake modifiers to ensure they are deterministic
26 static std::map<int, unsigned int> mapStakeModifierCheckpoints =
27     boost::assign::map_list_of
28         ( 0, 0x0e00670bu )
29         ( 9690, 0x97dcdafau )
30         ( 12661, 0x5d84115du )
31         ( 37092, 0xd230afccu )
32         ( 44200, 0x05370164u )
33         ( 65000, 0xc8e7be6au )
34         ( 68600, 0x73a8cc4cu )
35         ( 92161, 0xe21a911au )
36         ( 98661, 0xd20c44d4u )
37     ;
38
39 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
40 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
41     boost::assign::map_list_of
42         ( 0, 0x0e00670bu )
43     ;
44
45 // Whether the given block is subject to new modifier protocol
46 bool IsFixedModifierInterval(unsigned int nTimeBlock)
47 {
48     return (nTimeBlock >= (fTestNet? nModifierTestSwitchTime : nModifierSwitchTime));
49 }
50
51 // Get time weight
52 int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
53 {
54     // Kernel hash weight starts from 0 at the 30-day min age
55     // this change increases active coins participating the hash and helps
56     // to secure the network when proof-of-stake difficulty is low
57     //
58     // Maximum TimeWeight is 90 days.
59
60     return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
61 }
62
63 // Get the last stake modifier and its generation time from a given block
64 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
65 {
66     if (!pindex)
67         return error("GetLastStakeModifier: null pindex");
68     while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
69         pindex = pindex->pprev;
70     if (!pindex->GeneratedStakeModifier())
71         return error("GetLastStakeModifier: no generation at genesis block");
72     nStakeModifier = pindex->nStakeModifier;
73     nModifierTime = pindex->GetBlockTime();
74     return true;
75 }
76
77 // Get selection interval section (in seconds)
78 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
79 {
80     assert (nSection >= 0 && nSection < 64);
81     return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
82 }
83
84 // Get stake modifier selection interval (in seconds)
85 static int64 GetStakeModifierSelectionInterval()
86 {
87     int64 nSelectionInterval = 0;
88     for (int nSection=0; nSection<64; nSection++)
89         nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
90     return nSelectionInterval;
91 }
92
93 // select a block from the candidate blocks in vSortedByTimestamp, excluding
94 // already selected blocks in vSelectedBlocks, and with timestamp up to
95 // nSelectionIntervalStop.
96 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
97     int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
98 {
99     bool fSelected = false;
100     uint256 hashBest = 0;
101     *pindexSelected = (const CBlockIndex*) 0;
102     BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
103     {
104         if (!mapBlockIndex.count(item.second))
105             return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
106         const CBlockIndex* pindex = mapBlockIndex[item.second];
107         if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
108             break;
109         if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
110             continue;
111         // compute the selection hash by hashing its proof-hash and the
112         // previous proof-of-stake modifier
113         uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
114         CDataStream ss(SER_GETHASH, 0);
115         ss << hashProof << nStakeModifierPrev;
116         uint256 hashSelection = Hash(ss.begin(), ss.end());
117         // the selection hash is divided by 2**32 so that proof-of-stake block
118         // is always favored over proof-of-work block. this is to preserve
119         // the energy efficiency property
120         if (pindex->IsProofOfStake())
121             hashSelection >>= 32;
122         if (fSelected && hashSelection < hashBest)
123         {
124             hashBest = hashSelection;
125             *pindexSelected = (const CBlockIndex*) pindex;
126         }
127         else if (!fSelected)
128         {
129             fSelected = true;
130             hashBest = hashSelection;
131             *pindexSelected = (const CBlockIndex*) pindex;
132         }
133     }
134     if (fDebug && GetBoolArg("-printstakemodifier"))
135         printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
136     return fSelected;
137 }
138
139 // Stake Modifier (hash modifier of proof-of-stake):
140 // The purpose of stake modifier is to prevent a txout (coin) owner from
141 // computing future proof-of-stake generated by this txout at the time
142 // of transaction confirmation. To meet kernel protocol, the txout
143 // must hash with a future stake modifier to generate the proof.
144 // Stake modifier consists of bits each of which is contributed from a
145 // selected block of a given block group in the past.
146 // The selection of a block is based on a hash of the block's proof-hash and
147 // the previous stake modifier.
148 // Stake modifier is recomputed at a fixed time interval instead of every 
149 // block. This is to make it difficult for an attacker to gain control of
150 // additional bits in the stake modifier, even after generating a chain of
151 // blocks.
152 bool ComputeNextStakeModifier(const CBlockIndex* pindexCurrent, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
153 {
154     nStakeModifier = 0;
155     fGeneratedStakeModifier = false;
156     const CBlockIndex* pindexPrev = pindexCurrent->pprev;
157     if (!pindexPrev)
158     {
159         fGeneratedStakeModifier = true;
160         return true;  // genesis block's modifier is 0
161     }
162
163     // First find current stake modifier and its generation block time
164     // if it's not old enough, return the same stake modifier
165     int64 nModifierTime = 0;
166     if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
167         return error("ComputeNextStakeModifier: unable to get last modifier");
168     if (fDebug)
169     {
170         printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s epoch=%u\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str(), (unsigned int)nModifierTime);
171     }
172     if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
173     {
174         if (fDebug)
175         {
176             printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexPrev nHeight=%d nTime=%u\n", pindexPrev->nHeight, (unsigned int)pindexPrev->GetBlockTime());
177         }
178         return true;
179     }
180     if (nModifierTime / nModifierInterval >= pindexCurrent->GetBlockTime() / nModifierInterval)
181     {
182         // fixed interval protocol requires current block timestamp also be in a different modifier interval
183         if (IsFixedModifierInterval(pindexCurrent->nTime))
184         {
185             if (fDebug)
186             {
187                 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
188             }
189             return true;
190         }
191         else
192         {
193             if (fDebug)
194             {
195                 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());
196             }
197         }
198     }
199
200     // Sort candidate blocks by timestamp
201     vector<pair<int64, uint256> > vSortedByTimestamp;
202     vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
203     int64 nSelectionInterval = GetStakeModifierSelectionInterval();
204     int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
205     const CBlockIndex* pindex = pindexPrev;
206     while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
207     {
208         vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
209         pindex = pindex->pprev;
210     }
211     int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
212     reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
213     sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
214
215     // Select 64 blocks from candidate blocks to generate stake modifier
216     uint64 nStakeModifierNew = 0;
217     int64 nSelectionIntervalStop = nSelectionIntervalStart;
218     map<uint256, const CBlockIndex*> mapSelectedBlocks;
219     for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
220     {
221         // add an interval section to the current selection round
222         nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
223         // select a block from the candidates of current round
224         if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
225             return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
226         // write the entropy bit of the selected block
227         nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
228         // add the selected block from candidates to selected list
229         mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
230         if (fDebug && GetBoolArg("-printstakemodifier"))
231             printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
232     }
233
234     // Print selection map for visualization of the selected blocks
235     if (fDebug && GetBoolArg("-printstakemodifier"))
236     {
237         string strSelectionMap = "";
238         // '-' indicates proof-of-work blocks not selected
239         strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
240         pindex = pindexPrev;
241         while (pindex && pindex->nHeight >= nHeightFirstCandidate)
242         {
243             // '=' indicates proof-of-stake blocks not selected
244             if (pindex->IsProofOfStake())
245                 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
246             pindex = pindex->pprev;
247         }
248         BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
249         {
250             // 'S' indicates selected proof-of-stake blocks
251             // 'W' indicates selected proof-of-work blocks
252             strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
253         }
254         printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
255     }
256     if (fDebug)
257     {
258         printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
259     }
260
261     nStakeModifier = nStakeModifierNew;
262     fGeneratedStakeModifier = true;
263     return true;
264 }
265
266 // The stake modifier used to hash for a stake kernel is chosen as the stake
267 // modifier about a selection interval later than the coin generating the kernel
268 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
269 {
270     nStakeModifier = 0;
271     if (!mapBlockIndex.count(hashBlockFrom))
272         return error("GetKernelStakeModifier() : block not indexed");
273     const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
274     nStakeModifierHeight = pindexFrom->nHeight;
275     nStakeModifierTime = pindexFrom->GetBlockTime();
276     int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
277     const CBlockIndex* pindex = pindexFrom;
278     // loop to find the stake modifier later by a selection interval
279     while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
280     {
281         if (!pindex->pnext)
282         {   // reached best block; may happen if node is behind on block chain
283             if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
284                 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
285                     pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
286             else
287                 return false;
288         }
289         pindex = pindex->pnext;
290         if (pindex->GeneratedStakeModifier())
291         {
292             nStakeModifierHeight = pindex->nHeight;
293             nStakeModifierTime = pindex->GetBlockTime();
294         }
295     }
296     nStakeModifier = pindex->nStakeModifier;
297     return true;
298 }
299
300 bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier)
301 {
302     int nStakeModifierHeight;
303     int64 nStakeModifierTime;
304
305     return GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, false);
306 }
307
308
309 // ppcoin kernel protocol
310 // coinstake must meet hash target according to the protocol:
311 // kernel (input 0) must meet the formula
312 //     hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
313 // this ensures that the chance of getting a coinstake is proportional to the
314 // amount of coin age one owns.
315 // The reason this hash is chosen is the following:
316 //   nStakeModifier: scrambles computation to make it very difficult to precompute
317 //                  future proof-of-stake at the time of the coin's confirmation
318 //   txPrev.block.nTime: prevent nodes from guessing a good timestamp to
319 //                       generate transaction for future advantage
320 //   txPrev.offset: offset of txPrev inside block, to reduce the chance of 
321 //                  nodes generating coinstake at the same time
322 //   txPrev.nTime: reduce the chance of nodes generating coinstake at the same
323 //                 time
324 //   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
325 //                  generating coinstake at the same time
326 //   block/tx hash should not be used here as they can be generated in vast
327 //   quantities so as to generate blocks faster, degrading the system back into
328 //   a proof-of-work situation.
329 //
330 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)
331 {
332     if (nTimeTx < txPrev.nTime)  // Transaction timestamp violation
333         return error("CheckStakeKernelHash() : nTime violation");
334
335     unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
336     if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
337         return error("CheckStakeKernelHash() : min age violation");
338
339     CBigNum bnTargetPerCoinDay;
340     bnTargetPerCoinDay.SetCompact(nBits);
341     int64 nValueIn = txPrev.vout[prevout.n].nValue;
342
343     uint256 hashBlockFrom = blockFrom.GetHash();
344
345     CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
346     targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
347
348     // Calculate hash
349     CDataStream ss(SER_GETHASH, 0);
350     uint64 nStakeModifier = 0;
351     int nStakeModifierHeight = 0;
352     int64 nStakeModifierTime = 0;
353
354     if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
355         return false;
356     ss << nStakeModifier;
357
358     ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
359     hashProofOfStake = Hash(ss.begin(), ss.end());
360     if (fPrintProofOfStake)
361     {
362         printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
363             nStakeModifier, nStakeModifierHeight,
364             DateTimeStrFormat(nStakeModifierTime).c_str(),
365             mapBlockIndex[hashBlockFrom]->nHeight,
366             DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
367         printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
368             nStakeModifier,
369             nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
370             hashProofOfStake.ToString().c_str());
371     }
372
373     // Now check if proof-of-stake hash meets target protocol
374     if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
375         return false;
376     if (fDebug && !fPrintProofOfStake)
377     {
378         printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
379             nStakeModifier, nStakeModifierHeight, 
380             DateTimeStrFormat(nStakeModifierTime).c_str(),
381             mapBlockIndex[hashBlockFrom]->nHeight,
382             DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
383         printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
384             nStakeModifier,
385             nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
386             hashProofOfStake.ToString().c_str());
387     }
388     return true;
389 }
390
391 // Scan given coins set for kernel solution
392 bool ScanForStakeKernelHash(MetaMap &mapMeta, KernelSearchSettings &settings, CoinsSet::value_type &kernelcoin, unsigned int &nTimeTx, unsigned int &nBlockTime)
393 {
394     uint256 hashProofOfStake = 0;
395
396     // txid => ((txindex, (tx, vout.n)), (block, modifier))
397     for(MetaMap::const_iterator meta_item = mapMeta.begin(); meta_item != mapMeta.end(); meta_item++)
398     {
399         if (!fCoinsDataActual)
400             break;
401
402         CTxIndex txindex = (*meta_item).second.first.first;
403         CBlock block = (*meta_item).second.second.first;
404         uint64 nStakeModifier = (*meta_item).second.second.second;
405
406         // Get coin
407         CoinsSet::value_type pcoin = meta_item->second.first.second;
408
409         static int nMaxStakeSearchInterval = 60;
410
411         // only count coins meeting min age requirement
412         if (nStakeMinAge + block.nTime > settings.nTime - nMaxStakeSearchInterval)
413             continue;
414
415         // Transaction offset inside block
416         unsigned int nTxOffset = txindex.pos.nTxPos - txindex.pos.nBlockPos;
417
418         // Current timestamp scanning interval
419         unsigned int nCurrentSearchInterval = min((int64)settings.nSearchInterval, (int64)nMaxStakeSearchInterval);
420
421         nBlockTime = block.nTime;
422         CBigNum bnTargetPerCoinDay;
423         bnTargetPerCoinDay.SetCompact(settings.nBits);
424         int64 nValueIn = pcoin.first->vout[pcoin.second].nValue;
425
426         // Search backward in time from the given timestamp 
427         // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
428         // Stopping search in case of shutting down or cache invalidation
429         for (unsigned int n=0; n<nCurrentSearchInterval && fCoinsDataActual && !fShutdown; n++)
430         {
431             nTimeTx = settings.nTime - n;
432             CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)pcoin.first->nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
433             CBigNum bnTargetProofOfStake = bnCoinDayWeight * bnTargetPerCoinDay;
434
435             // Build kernel
436             CDataStream ss(SER_GETHASH, 0);
437             ss << nStakeModifier;
438             ss << nBlockTime << nTxOffset << pcoin.first->nTime << pcoin.second << nTimeTx;
439
440             // Calculate kernel hash
441             hashProofOfStake = Hash(ss.begin(), ss.end());
442
443             if (bnTargetProofOfStake >= CBigNum(hashProofOfStake))
444             {
445                 if (fDebug)
446                     printf("nStakeModifier=0x%016"PRI64x", nBlockTime=%u nTxOffset=%u nTxPrevTime=%u nVout=%u nTimeTx=%u hashProofOfStake=%s Success=true\n",
447                         nStakeModifier, nBlockTime, nTxOffset, pcoin.first->nTime, pcoin.second, nTimeTx, hashProofOfStake.GetHex().c_str());
448
449                 kernelcoin = pcoin;
450                 return true;
451             }
452
453             if (fDebug)
454                 printf("nStakeModifier=0x%016"PRI64x", nBlockTime=%u nTxOffset=%u nTxPrevTime=%u nTxNumber=%u nTimeTx=%u hashProofOfStake=%s Success=false\n",
455                     nStakeModifier, nBlockTime, nTxOffset, pcoin.first->nTime, pcoin.second, nTimeTx, hashProofOfStake.GetHex().c_str());
456         }
457     }
458
459     return false;
460 }
461
462 // Check kernel hash target and coinstake signature
463 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
464 {
465     if (!tx.IsCoinStake())
466         return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
467
468     // Kernel (input 0) must match the stake hash target per coin age (nBits)
469     const CTxIn& txin = tx.vin[0];
470
471     // First try finding the previous transaction in database
472     CTxDB txdb("r");
473     CTransaction txPrev;
474     CTxIndex txindex;
475     if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
476         return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed"));  // previous transaction not in main chain, may occur during initial download
477
478 #ifndef USE_LEVELDB
479     txdb.Close();
480 #endif
481
482     // Verify signature
483     if (!VerifySignature(txPrev, tx, 0, MANDATORY_SCRIPT_VERIFY_FLAGS, 0))
484         return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
485
486     // Read block header
487     CBlock block;
488     if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
489         return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
490
491     if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
492         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
493
494     return true;
495 }
496
497 // Get stake modifier checksum
498 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
499 {
500     assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
501     // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
502     CDataStream ss(SER_GETHASH, 0);
503     if (pindex->pprev)
504         ss << pindex->pprev->nStakeModifierChecksum;
505     ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
506     uint256 hashChecksum = Hash(ss.begin(), ss.end());
507     hashChecksum >>= (256 - 32);
508     return hashChecksum.Get64();
509 }
510
511 // Check stake modifier hard checkpoints
512 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
513 {
514     MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
515
516     if (checkpoints.count(nHeight))
517         return nStakeModifierChecksum == checkpoints[nHeight];
518     return true;
519 }