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