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