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