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