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