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