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