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