Stake generation changes
[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         ( 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
284     // Kernel hash weight starts from 0 at the 30-day min age
285     // this change increases active coins participating the hash and helps
286     // to secure the network when proof-of-stake difficulty is low
287     //
288     if(fTestNet || (STAKEWEIGHT_SWITCH_TIME < nTimeTx))
289     {
290         // New rule since 01 Jan 2014: Maximum TimeWeight is 90 days.
291         nTimeWeight = min((int64)nTimeTx - txPrev.nTime - nStakeMinAge, (int64)nStakeMaxAge);
292     }
293     else
294     {
295         // Current rule: Maximum TimeWeight is 60 days.
296         nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
297     }
298
299     CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
300     targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
301
302     // Calculate hash
303     CDataStream ss(SER_GETHASH, 0);
304     uint64 nStakeModifier = 0;
305     int nStakeModifierHeight = 0;
306     int64 nStakeModifierTime = 0;
307
308     if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
309         return false;
310     ss << nStakeModifier;
311
312     ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
313     hashProofOfStake = Hash(ss.begin(), ss.end());
314     if (fPrintProofOfStake)
315     {
316         printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
317             nStakeModifier, nStakeModifierHeight,
318             DateTimeStrFormat(nStakeModifierTime).c_str(),
319             mapBlockIndex[blockFrom.GetHash()]->nHeight,
320             DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
321         printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
322             "0.3",
323             nStakeModifier,
324             nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
325             hashProofOfStake.ToString().c_str());
326     }
327
328     // Now check if proof-of-stake hash meets target protocol
329     if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
330         return false;
331     if (fDebug && !fPrintProofOfStake)
332     {
333         printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
334             nStakeModifier, nStakeModifierHeight, 
335             DateTimeStrFormat(nStakeModifierTime).c_str(),
336             mapBlockIndex[blockFrom.GetHash()]->nHeight,
337             DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
338         printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
339             "0.3",
340             nStakeModifier,
341             nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
342             hashProofOfStake.ToString().c_str());
343     }
344     return true;
345 }
346
347 // Check kernel hash target and coinstake signature
348 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
349 {
350     if (!tx.IsCoinStake())
351         return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
352
353     // Kernel (input 0) must match the stake hash target per coin age (nBits)
354     const CTxIn& txin = tx.vin[0];
355
356     // First try finding the previous transaction in database
357     CTxDB txdb("r");
358     CTransaction txPrev;
359     CTxIndex txindex;
360     if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
361         return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed"));  // previous transaction not in main chain, may occur during initial download
362     txdb.Close();
363
364     // Verify signature
365     if (!VerifySignature(txPrev, tx, 0, true, 0))
366         return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
367
368     // Read block header
369     CBlock block;
370     if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
371         return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
372
373     if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
374         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
375
376     return true;
377 }
378
379 // Check whether the coinstake timestamp meets protocol
380 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
381 {
382     // v0.3 protocol
383     return (nTimeBlock == nTimeTx);
384 }
385
386 // Get stake modifier checksum
387 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
388 {
389     assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
390     // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
391     CDataStream ss(SER_GETHASH, 0);
392     if (pindex->pprev)
393         ss << pindex->pprev->nStakeModifierChecksum;
394     ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
395     uint256 hashChecksum = Hash(ss.begin(), ss.end());
396     hashChecksum >>= (256 - 32);
397     return hashChecksum.Get64();
398 }
399
400 // Check stake modifier hard checkpoints
401 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
402 {
403     MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
404
405     if (checkpoints.count(nHeight))
406         return nStakeModifierChecksum == checkpoints[nHeight];
407     return true;
408 }