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