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