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