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