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.
5 #include <boost/assign/list_of.hpp>
12 extern int nStakeMaxAge;
13 extern int nStakeTargetSpacing;
15 typedef std::map<int, unsigned int> MapModifierCheckpoints;
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
22 ( 12661, 0x5d84115du )
23 ( 37092, 0xd230afccu )
26 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
27 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
28 boost::assign::map_list_of
32 // Get the last stake modifier and its generation time from a given block
33 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
36 return error("GetLastStakeModifier: null pindex");
37 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
38 pindex = pindex->pprev;
39 if (!pindex->GeneratedStakeModifier())
40 return error("GetLastStakeModifier: no generation at genesis block");
41 nStakeModifier = pindex->nStakeModifier;
42 nModifierTime = pindex->GetBlockTime();
46 // Get selection interval section (in seconds)
47 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
49 assert (nSection >= 0 && nSection < 64);
50 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
53 // Get stake modifier selection interval (in seconds)
54 static int64 GetStakeModifierSelectionInterval()
56 int64 nSelectionInterval = 0;
57 for (int nSection=0; nSection<64; nSection++)
58 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
59 return nSelectionInterval;
62 // select a block from the candidate blocks in vSortedByTimestamp, excluding
63 // already selected blocks in vSelectedBlocks, and with timestamp up to
64 // nSelectionIntervalStop.
65 static bool SelectBlockFromCandidates(
66 vector<pair<int64, uint256> >& vSortedByTimestamp,
67 map<uint256, const CBlockIndex*>& mapSelectedBlocks,
68 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
69 const CBlockIndex** pindexSelected)
71 bool fSelected = false;
73 *pindexSelected = (const CBlockIndex*) 0;
74 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
76 if (!mapBlockIndex.count(item.second))
77 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
78 const CBlockIndex* pindex = mapBlockIndex[item.second];
79 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
81 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
83 // compute the selection hash by hashing its proof-hash and the
84 // previous proof-of-stake modifier
85 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
86 CDataStream ss(SER_GETHASH, 0);
87 ss << hashProof << nStakeModifierPrev;
88 uint256 hashSelection = Hash(ss.begin(), ss.end());
89 // the selection hash is divided by 2**32 so that proof-of-stake block
90 // is always favored over proof-of-work block. this is to preserve
91 // the energy efficiency property
92 if (pindex->IsProofOfStake())
94 if (fSelected && hashSelection < hashBest)
96 hashBest = hashSelection;
97 *pindexSelected = (const CBlockIndex*) pindex;
102 hashBest = hashSelection;
103 *pindexSelected = (const CBlockIndex*) pindex;
106 if (fDebug && GetBoolArg("-printstakemodifier"))
107 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
111 // Stake Modifier (hash modifier of proof-of-stake):
112 // The purpose of stake modifier is to prevent a txout (coin) owner from
113 // computing future proof-of-stake generated by this txout at the time
114 // of transaction confirmation. To meet kernel protocol, the txout
115 // must hash with a future stake modifier to generate the proof.
116 // Stake modifier consists of bits each of which is contributed from a
117 // selected block of a given block group in the past.
118 // The selection of a block is based on a hash of the block's proof-hash and
119 // the previous stake modifier.
120 // Stake modifier is recomputed at a fixed time interval instead of every
121 // block. This is to make it difficult for an attacker to gain control of
122 // additional bits in the stake modifier, even after generating a chain of
124 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
127 fGeneratedStakeModifier = false;
130 fGeneratedStakeModifier = true;
131 return true; // genesis block's modifier is 0
133 // First find current stake modifier and its generation block time
134 // if it's not old enough, return the same stake modifier
135 int64 nModifierTime = 0;
136 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
137 return error("ComputeNextStakeModifier: unable to get last modifier");
140 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
142 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
145 // Sort candidate blocks by timestamp
146 vector<pair<int64, uint256> > vSortedByTimestamp;
147 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
148 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
149 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
150 const CBlockIndex* pindex = pindexPrev;
151 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
153 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
154 pindex = pindex->pprev;
156 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
157 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
158 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
160 // Select 64 blocks from candidate blocks to generate stake modifier
161 uint64 nStakeModifierNew = 0;
162 int64 nSelectionIntervalStop = nSelectionIntervalStart;
163 map<uint256, const CBlockIndex*> mapSelectedBlocks;
164 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
166 // add an interval section to the current selection round
167 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
168 // select a block from the candidates of current round
169 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
170 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
171 // write the entropy bit of the selected block
172 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
173 // add the selected block from candidates to selected list
174 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
175 if (fDebug && GetBoolArg("-printstakemodifier"))
176 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
177 nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
180 // Print selection map for visualization of the selected blocks
181 if (fDebug && GetBoolArg("-printstakemodifier"))
183 string strSelectionMap = "";
184 // '-' indicates proof-of-work blocks not selected
185 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
187 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
189 // '=' indicates proof-of-stake blocks not selected
190 if (pindex->IsProofOfStake())
191 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
192 pindex = pindex->pprev;
194 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
196 // 'S' indicates selected proof-of-stake blocks
197 // 'W' indicates selected proof-of-work blocks
198 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
200 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
204 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
207 nStakeModifier = nStakeModifierNew;
208 fGeneratedStakeModifier = true;
212 // The stake modifier used to hash for a stake kernel is chosen as the stake
213 // modifier about a selection interval later than the coin generating the kernel
214 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
217 if (!mapBlockIndex.count(hashBlockFrom))
218 return error("GetKernelStakeModifier() : block not indexed");
219 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
220 nStakeModifierHeight = pindexFrom->nHeight;
221 nStakeModifierTime = pindexFrom->GetBlockTime();
222 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
223 const CBlockIndex* pindex = pindexFrom;
224 // loop to find the stake modifier later by a selection interval
225 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
228 { // reached best block; may happen if node is behind on block chain
229 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
230 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
231 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
235 pindex = pindex->pnext;
236 if (pindex->GeneratedStakeModifier())
238 nStakeModifierHeight = pindex->nHeight;
239 nStakeModifierTime = pindex->GetBlockTime();
242 nStakeModifier = pindex->nStakeModifier;
246 // ppcoin kernel protocol
247 // coinstake must meet hash target according to the protocol:
248 // kernel (input 0) must meet the formula
249 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
250 // this ensures that the chance of getting a coinstake is proportional to the
251 // amount of coin age one owns.
252 // The reason this hash is chosen is the following:
254 // (v0.3) scrambles computation to make it very difficult to precompute
255 // future proof-of-stake at the time of the coin's confirmation
256 // (v0.2) nBits (deprecated): encodes all past block timestamps
257 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
258 // generate transaction for future advantage
259 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
260 // nodes generating coinstake at the same time
261 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
263 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
264 // generating coinstake at the same time
265 // block/tx hash should not be used here as they can be generated in vast
266 // quantities so as to generate blocks faster, degrading the system back into
267 // a proof-of-work situation.
269 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)
271 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
272 return error("CheckStakeKernelHash() : nTime violation");
274 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
275 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
276 return error("CheckStakeKernelHash() : min age violation");
278 CBigNum bnTargetPerCoinDay;
279 bnTargetPerCoinDay.SetCompact(nBits);
280 int64 nValueIn = txPrev.vout[prevout.n].nValue;
283 uint256 hashBlockFrom = blockFrom.GetHash();
285 // Kernel hash weight starts from 0 at the 30-day min age
286 // this change increases active coins participating the hash and helps
287 // to secure the network when proof-of-stake difficulty is low
289 if(fTestNet || (STAKEWEIGHT_SWITCH_TIME < nTimeTx))
291 // New rule since 01 Jan 2014: Maximum TimeWeight is 90 days.
292 nTimeWeight = min((int64)nTimeTx - txPrev.nTime - nStakeMinAge, (int64)nStakeMaxAge);
296 // Current rule: Maximum TimeWeight is 60 days.
297 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
300 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
301 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
304 CDataStream ss(SER_GETHASH, 0);
305 uint64 nStakeModifier = 0;
306 int nStakeModifierHeight = 0;
307 int64 nStakeModifierTime = 0;
309 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
311 ss << nStakeModifier;
313 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
314 hashProofOfStake = Hash(ss.begin(), ss.end());
315 if (fPrintProofOfStake)
317 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
318 nStakeModifier, nStakeModifierHeight,
319 DateTimeStrFormat(nStakeModifierTime).c_str(),
320 mapBlockIndex[hashBlockFrom]->nHeight,
321 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
322 printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
325 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
326 hashProofOfStake.ToString().c_str());
329 // Now check if proof-of-stake hash meets target protocol
330 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
332 if (fDebug && !fPrintProofOfStake)
334 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
335 nStakeModifier, nStakeModifierHeight,
336 DateTimeStrFormat(nStakeModifierTime).c_str(),
337 mapBlockIndex[hashBlockFrom]->nHeight,
338 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
339 printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
342 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
343 hashProofOfStake.ToString().c_str());
348 // Check kernel hash target and coinstake signature
349 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
351 if (!tx.IsCoinStake())
352 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
354 // Kernel (input 0) must match the stake hash target per coin age (nBits)
355 const CTxIn& txin = tx.vin[0];
357 // First try finding the previous transaction in database
361 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
362 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
369 if (!VerifySignature(txPrev, tx, 0, true, 0))
370 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
374 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
375 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
377 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
378 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
383 // Check whether the coinstake timestamp meets protocol
384 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
387 return (nTimeBlock == nTimeTx);
390 // Get stake modifier checksum
391 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
393 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
394 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
395 CDataStream ss(SER_GETHASH, 0);
397 ss << pindex->pprev->nStakeModifierChecksum;
398 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
399 uint256 hashChecksum = Hash(ss.begin(), ss.end());
400 hashChecksum >>= (256 - 32);
401 return hashChecksum.Get64();
404 // Check stake modifier hard checkpoints
405 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
407 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
409 if (checkpoints.count(nHeight))
410 return nStakeModifierChecksum == checkpoints[nHeight];