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