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