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