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