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 // Protocol switch time for fixed kernel modifier interval
16 unsigned int nModifierSwitchTime = 1402531200; // Thu, 12 Jun 2014 00:00:00 GMT
17 unsigned int nModifierTestSwitchTime = 1397520000; // Tue, 15 Apr 2014 00:00:00 GMT
19 // Note: user must upgrade before the protocol switch deadline, otherwise it's required to
20 // re-download the blockchain. The timestamp of upgrade is recorded in the blockchain
22 unsigned int nModifierUpgradeTime = 0;
24 typedef std::map<int, unsigned int> MapModifierCheckpoints;
26 // Hard checkpoints of stake modifiers to ensure they are deterministic
27 static std::map<int, unsigned int> mapStakeModifierCheckpoints =
28 boost::assign::map_list_of
30 ( 68600, 0x73a8cc4cu )
31 ( 92161, 0xe21a911au )
32 ( 98661, 0xd20c44d4u )
35 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
36 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
37 boost::assign::map_list_of
42 int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
44 // Kernel hash weight starts from 0 at the 30-day min age
45 // this change increases active coins participating the hash and helps
46 // to secure the network when proof-of-stake difficulty is low
48 // Maximum TimeWeight is 90 days.
50 return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
53 // Whether the given block is subject to new modifier protocol
54 bool IsFixedModifierInterval(unsigned int nTimeBlock)
56 return (nTimeBlock >= (fTestNet? nModifierTestSwitchTime : nModifierSwitchTime));
59 // Get the last stake modifier and its generation time from a given block
60 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
63 return error("GetLastStakeModifier: null pindex");
64 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
65 pindex = pindex->pprev;
66 if (!pindex->GeneratedStakeModifier())
67 return error("GetLastStakeModifier: no generation at genesis block");
68 nStakeModifier = pindex->nStakeModifier;
69 nModifierTime = pindex->GetBlockTime();
73 // Get selection interval section (in seconds)
74 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
76 assert (nSection >= 0 && nSection < 64);
77 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
80 // Get stake modifier selection interval (in seconds)
81 static int64 GetStakeModifierSelectionInterval()
83 int64 nSelectionInterval = 0;
84 for (int nSection=0; nSection<64; nSection++)
85 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
86 return nSelectionInterval;
89 // select a block from the candidate blocks in vSortedByTimestamp, excluding
90 // already selected blocks in vSelectedBlocks, and with timestamp up to
91 // nSelectionIntervalStop.
92 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
93 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
95 bool fSelected = false;
97 *pindexSelected = (const CBlockIndex*) 0;
98 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
100 if (!mapBlockIndex.count(item.second))
101 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
102 const CBlockIndex* pindex = mapBlockIndex[item.second];
103 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
105 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
107 // compute the selection hash by hashing its proof-hash and the
108 // previous proof-of-stake modifier
109 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
110 CDataStream ss(SER_GETHASH, 0);
111 ss << hashProof << nStakeModifierPrev;
112 uint256 hashSelection = Hash(ss.begin(), ss.end());
113 // the selection hash is divided by 2**32 so that proof-of-stake block
114 // is always favored over proof-of-work block. this is to preserve
115 // the energy efficiency property
116 if (pindex->IsProofOfStake())
117 hashSelection >>= 32;
118 if (fSelected && hashSelection < hashBest)
120 hashBest = hashSelection;
121 *pindexSelected = (const CBlockIndex*) pindex;
126 hashBest = hashSelection;
127 *pindexSelected = (const CBlockIndex*) pindex;
130 if (fDebug && GetBoolArg("-printstakemodifier"))
131 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
135 // Stake Modifier (hash modifier of proof-of-stake):
136 // The purpose of stake modifier is to prevent a txout (coin) owner from
137 // computing future proof-of-stake generated by this txout at the time
138 // of transaction confirmation. To meet kernel protocol, the txout
139 // must hash with a future stake modifier to generate the proof.
140 // Stake modifier consists of bits each of which is contributed from a
141 // selected block of a given block group in the past.
142 // The selection of a block is based on a hash of the block's proof-hash and
143 // the previous stake modifier.
144 // Stake modifier is recomputed at a fixed time interval instead of every
145 // block. This is to make it difficult for an attacker to gain control of
146 // additional bits in the stake modifier, even after generating a chain of
148 bool ComputeNextStakeModifier(const CBlockIndex* pindexCurrent, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
151 fGeneratedStakeModifier = false;
152 const CBlockIndex* pindexPrev = pindexCurrent->pprev;
155 fGeneratedStakeModifier = true;
156 return true; // genesis block's modifier is 0
159 // First find current stake modifier and its generation block time
160 // if it's not old enough, return the same stake modifier
161 int64 nModifierTime = 0;
162 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
163 return error("ComputeNextStakeModifier: unable to get last modifier");
166 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s epoch=%u\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str(), (unsigned int)nModifierTime);
168 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
172 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexPrev nHeight=%d nTime=%u\n", pindexPrev->nHeight, (unsigned int)pindexPrev->GetBlockTime());
176 if (nModifierTime / nModifierInterval >= pindexCurrent->GetBlockTime() / nModifierInterval)
178 // fixed interval protocol requires current block timestamp also be in a different modifier interval
179 if (IsFixedModifierInterval(pindexCurrent->nTime))
183 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
191 printf("ComputeNextStakeModifier: old modifier at block %s not meeting fixed modifier interval: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->GetBlockHash().ToString().c_str(), pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
196 // Sort candidate blocks by timestamp
197 vector<pair<int64, uint256> > vSortedByTimestamp;
198 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
199 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
200 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
201 const CBlockIndex* pindex = pindexPrev;
202 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
204 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
205 pindex = pindex->pprev;
207 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
208 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
209 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
211 // Select 64 blocks from candidate blocks to generate stake modifier
212 uint64 nStakeModifierNew = 0;
213 int64 nSelectionIntervalStop = nSelectionIntervalStart;
214 map<uint256, const CBlockIndex*> mapSelectedBlocks;
215 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
217 // add an interval section to the current selection round
218 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
219 // select a block from the candidates of current round
220 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
221 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
222 // write the entropy bit of the selected block
223 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
224 // add the selected block from candidates to selected list
225 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
226 if (fDebug && GetBoolArg("-printstakemodifier"))
227 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
230 // Print selection map for visualization of the selected blocks
231 if (fDebug && GetBoolArg("-printstakemodifier"))
233 string strSelectionMap = "";
234 // '-' indicates proof-of-work blocks not selected
235 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
237 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
239 // '=' indicates proof-of-stake blocks not selected
240 if (pindex->IsProofOfStake())
241 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
242 pindex = pindex->pprev;
244 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
246 // 'S' indicates selected proof-of-stake blocks
247 // 'W' indicates selected proof-of-work blocks
248 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
250 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
254 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
257 nStakeModifier = nStakeModifierNew;
258 fGeneratedStakeModifier = true;
262 // The stake modifier used to hash for a stake kernel is chosen as the stake
263 // modifier about a selection interval later than the coin generating the kernel
264 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
267 if (!mapBlockIndex.count(hashBlockFrom))
268 return error("GetKernelStakeModifier() : block not indexed");
269 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
270 nStakeModifierHeight = pindexFrom->nHeight;
271 nStakeModifierTime = pindexFrom->GetBlockTime();
272 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
273 const CBlockIndex* pindex = pindexFrom;
274 // loop to find the stake modifier later by a selection interval
275 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
278 { // reached best block; may happen if node is behind on block chain
279 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
280 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
281 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
285 pindex = pindex->pnext;
286 if (pindex->GeneratedStakeModifier())
288 nStakeModifierHeight = pindex->nHeight;
289 nStakeModifierTime = pindex->GetBlockTime();
292 nStakeModifier = pindex->nStakeModifier;
296 // ppcoin kernel protocol
297 // coinstake must meet hash target according to the protocol:
298 // kernel (input 0) must meet the formula
299 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
300 // this ensures that the chance of getting a coinstake is proportional to the
301 // amount of coin age one owns.
302 // The reason this hash is chosen is the following:
303 // nStakeModifier: scrambles computation to make it very difficult to precompute
304 // future proof-of-stake at the time of the coin's confirmation
305 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
306 // generate transaction for future advantage
307 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
308 // nodes generating coinstake at the same time
309 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
311 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
312 // generating coinstake at the same time
313 // block/tx hash should not be used here as they can be generated in vast
314 // quantities so as to generate blocks faster, degrading the system back into
315 // a proof-of-work situation.
317 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& fFatal, bool fMiner, bool fPrintProofOfStake)
319 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
322 return error("CheckStakeKernelHash() : nTime violation");
325 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
326 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
329 return error("CheckStakeKernelHash() : min age violation");
332 CBigNum bnTargetPerCoinDay;
333 bnTargetPerCoinDay.SetCompact(nBits);
334 int64 nValueIn = txPrev.vout[prevout.n].nValue;
336 uint256 hashBlockFrom = blockFrom.GetHash();
338 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
339 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
342 CDataStream ss(SER_GETHASH, 0);
343 uint64 nStakeModifier = 0;
344 int nStakeModifierHeight = 0;
345 int64 nStakeModifierTime = 0;
347 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
349 ss << nStakeModifier;
351 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
352 hashProofOfStake = Hash(ss.begin(), ss.end());
354 if (fPrintProofOfStake)
356 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
357 nStakeModifier, nStakeModifierHeight,
358 DateTimeStrFormat(nStakeModifierTime).c_str(),
359 mapBlockIndex[hashBlockFrom]->nHeight,
360 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
361 printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
363 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
364 hashProofOfStake.ToString().c_str());
367 // Now check if proof-of-stake hash meets target protocol
368 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
371 return !fMiner? error("CheckStakeKernelHash() : proof-of-stake not meeting target") : false;
374 if (fDebug && !fPrintProofOfStake)
376 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
377 nStakeModifier, nStakeModifierHeight,
378 DateTimeStrFormat(nStakeModifierTime).c_str(),
379 mapBlockIndex[hashBlockFrom]->nHeight,
380 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
381 printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
383 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
384 hashProofOfStake.ToString().c_str());
389 // Check kernel hash target and coinstake signature
390 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake, bool& fFatal, bool fMiner)
392 if (!tx.IsCoinStake())
395 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
398 // Kernel (input 0) must match the stake hash target per coin age (nBits)
399 const CTxIn& txin = tx.vin[0];
404 CCoinsViewCache &view = *pcoinsTip;
406 if (!view.GetCoinsReadOnly(txin.prevout.hash, coins))
407 return fDebug? error("CheckProofOfStake() : INFO: read coins for txPrev failed") : false; // previous transaction not in main chain, may occur during initial download
409 CBlockIndex* pindex = FindBlockByHeight(coins.nHeight);
411 // Read block and scan it to find txPrev
413 if (block.ReadFromDisk(pindex)) {
414 nTxPos = GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
415 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
416 if (tx.GetHash() == txin.prevout.hash) {
420 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
424 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
426 const CTxOut& txout = txPrev.vout[txin.prevout.n];
428 // Check transaction consistency
429 if (txin.prevout.n >= txPrev.vout.size())
432 return error("CheckProofOfStake() : invalid prevout found in coinstake %s", tx.GetHash().ToString().c_str());
436 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, tx, 0, true, false, 0))
439 return error("CheckProofOfStake() : VerifyScript failed on coinstake %s", tx.GetHash().ToString().c_str());
442 if (!CheckStakeKernelHash(nBits, block, nTxPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fFatal, fMiner, fDebug))
446 // may occur during initial download or if behind on block chain sync
447 return fDebug? error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str()) : false;
453 // Check whether the coinstake timestamp meets protocol
454 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
457 return (nTimeBlock == nTimeTx);
460 // Get stake modifier checksum
461 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
463 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
464 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
465 CDataStream ss(SER_GETHASH, 0);
467 ss << pindex->pprev->nStakeModifierChecksum;
468 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
469 uint256 hashChecksum = Hash(ss.begin(), ss.end());
470 hashChecksum >>= (256 - 32);
471 return hashChecksum.Get64();
474 // Check stake modifier hard checkpoints
475 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
477 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
479 if (checkpoints.count(nHeight))
480 return nStakeModifierChecksum == checkpoints[nHeight];