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