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