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