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