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 = 1413763200; // Mon, 20 Oct 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
31 ( 12661, 0x5d84115du )
32 ( 37092, 0xd230afccu )
33 ( 44200, 0x05370164u )
34 ( 65000, 0xc8e7be6au )
35 ( 68600, 0x73a8cc4cu )
36 ( 92161, 0xe21a911au )
37 ( 98661, 0xd20c44d4u )
40 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
41 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
42 boost::assign::map_list_of
46 // Whether the given block is subject to new modifier protocol
47 bool IsFixedModifierInterval(unsigned int nTimeBlock)
49 return (nTimeBlock >= (fTestNet? nModifierTestSwitchTime : nModifierSwitchTime));
53 int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
55 // Kernel hash weight starts from 0 at the 30-day min age
56 // this change increases active coins participating the hash and helps
57 // to secure the network when proof-of-stake difficulty is low
59 // Maximum TimeWeight is 90 days.
61 return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
64 // Get the last stake modifier and its generation time from a given block
65 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
68 return error("GetLastStakeModifier: null pindex");
69 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
70 pindex = pindex->pprev;
71 if (!pindex->GeneratedStakeModifier())
72 return error("GetLastStakeModifier: no generation at genesis block");
73 nStakeModifier = pindex->nStakeModifier;
74 nModifierTime = pindex->GetBlockTime();
78 // Get selection interval section (in seconds)
79 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
81 assert (nSection >= 0 && nSection < 64);
82 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
85 // Get stake modifier selection interval (in seconds)
86 static int64 GetStakeModifierSelectionInterval()
88 int64 nSelectionInterval = 0;
89 for (int nSection=0; nSection<64; nSection++)
90 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
91 return nSelectionInterval;
94 // select a block from the candidate blocks in vSortedByTimestamp, excluding
95 // already selected blocks in vSelectedBlocks, and with timestamp up to
96 // nSelectionIntervalStop.
97 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
98 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
100 bool fSelected = false;
101 uint256 hashBest = 0;
102 *pindexSelected = (const CBlockIndex*) 0;
103 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
105 if (!mapBlockIndex.count(item.second))
106 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
107 const CBlockIndex* pindex = mapBlockIndex[item.second];
108 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
110 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
112 // compute the selection hash by hashing its proof-hash and the
113 // previous proof-of-stake modifier
114 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
115 CDataStream ss(SER_GETHASH, 0);
116 ss << hashProof << nStakeModifierPrev;
117 uint256 hashSelection = Hash(ss.begin(), ss.end());
118 // the selection hash is divided by 2**32 so that proof-of-stake block
119 // is always favored over proof-of-work block. this is to preserve
120 // the energy efficiency property
121 if (pindex->IsProofOfStake())
122 hashSelection >>= 32;
123 if (fSelected && hashSelection < hashBest)
125 hashBest = hashSelection;
126 *pindexSelected = (const CBlockIndex*) pindex;
131 hashBest = hashSelection;
132 *pindexSelected = (const CBlockIndex*) pindex;
135 if (fDebug && GetBoolArg("-printstakemodifier"))
136 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
140 // Stake Modifier (hash modifier of proof-of-stake):
141 // The purpose of stake modifier is to prevent a txout (coin) owner from
142 // computing future proof-of-stake generated by this txout at the time
143 // of transaction confirmation. To meet kernel protocol, the txout
144 // must hash with a future stake modifier to generate the proof.
145 // Stake modifier consists of bits each of which is contributed from a
146 // selected block of a given block group in the past.
147 // The selection of a block is based on a hash of the block's proof-hash and
148 // the previous stake modifier.
149 // Stake modifier is recomputed at a fixed time interval instead of every
150 // block. This is to make it difficult for an attacker to gain control of
151 // additional bits in the stake modifier, even after generating a chain of
153 bool ComputeNextStakeModifier(const CBlockIndex* pindexCurrent, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
156 fGeneratedStakeModifier = false;
157 const CBlockIndex* pindexPrev = pindexCurrent->pprev;
160 fGeneratedStakeModifier = true;
161 return true; // genesis block's modifier is 0
164 // First find current stake modifier and its generation block time
165 // if it's not old enough, return the same stake modifier
166 int64 nModifierTime = 0;
167 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
168 return error("ComputeNextStakeModifier: unable to get last modifier");
171 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s epoch=%u\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str(), (unsigned int)nModifierTime);
173 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
177 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexPrev nHeight=%d nTime=%u\n", pindexPrev->nHeight, (unsigned int)pindexPrev->GetBlockTime());
181 if (nModifierTime / nModifierInterval >= pindexCurrent->GetBlockTime() / nModifierInterval)
183 // fixed interval protocol requires current block timestamp also be in a different modifier interval
184 if (IsFixedModifierInterval(pindexCurrent->nTime))
188 printf("ComputeNextStakeModifier: no new interval keep current modifier: pindexCurrent nHeight=%d nTime=%u\n", pindexCurrent->nHeight, (unsigned int)pindexCurrent->GetBlockTime());
196 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());
201 // Sort candidate blocks by timestamp
202 vector<pair<int64, uint256> > vSortedByTimestamp;
203 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
204 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
205 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
206 const CBlockIndex* pindex = pindexPrev;
207 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
209 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
210 pindex = pindex->pprev;
212 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
213 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
214 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
216 // Select 64 blocks from candidate blocks to generate stake modifier
217 uint64 nStakeModifierNew = 0;
218 int64 nSelectionIntervalStop = nSelectionIntervalStart;
219 map<uint256, const CBlockIndex*> mapSelectedBlocks;
220 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
222 // add an interval section to the current selection round
223 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
224 // select a block from the candidates of current round
225 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
226 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
227 // write the entropy bit of the selected block
228 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
229 // add the selected block from candidates to selected list
230 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
231 if (fDebug && GetBoolArg("-printstakemodifier"))
232 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
235 // Print selection map for visualization of the selected blocks
236 if (fDebug && GetBoolArg("-printstakemodifier"))
238 string strSelectionMap = "";
239 // '-' indicates proof-of-work blocks not selected
240 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
242 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
244 // '=' indicates proof-of-stake blocks not selected
245 if (pindex->IsProofOfStake())
246 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
247 pindex = pindex->pprev;
249 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
251 // 'S' indicates selected proof-of-stake blocks
252 // 'W' indicates selected proof-of-work blocks
253 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
255 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
259 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
262 nStakeModifier = nStakeModifierNew;
263 fGeneratedStakeModifier = true;
267 // The stake modifier used to hash for a stake kernel is chosen as the stake
268 // modifier about a selection interval later than the coin generating the kernel
269 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
272 if (!mapBlockIndex.count(hashBlockFrom))
273 return error("GetKernelStakeModifier() : block not indexed");
274 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
275 nStakeModifierHeight = pindexFrom->nHeight;
276 nStakeModifierTime = pindexFrom->GetBlockTime();
277 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
278 const CBlockIndex* pindex = pindexFrom;
279 // loop to find the stake modifier later by a selection interval
280 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
283 { // reached best block; may happen if node is behind on block chain
284 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
285 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
286 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
290 pindex = pindex->pnext;
291 if (pindex->GeneratedStakeModifier())
293 nStakeModifierHeight = pindex->nHeight;
294 nStakeModifierTime = pindex->GetBlockTime();
297 nStakeModifier = pindex->nStakeModifier;
301 // ppcoin kernel protocol
302 // coinstake must meet hash target according to the protocol:
303 // kernel (input 0) must meet the formula
304 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
305 // this ensures that the chance of getting a coinstake is proportional to the
306 // amount of coin age one owns.
307 // The reason this hash is chosen is the following:
308 // nStakeModifier: scrambles computation to make it very difficult to precompute
309 // future proof-of-stake at the time of the coin's confirmation
310 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
311 // generate transaction for future advantage
312 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
313 // nodes generating coinstake at the same time
314 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
316 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
317 // generating coinstake at the same time
318 // block/tx hash should not be used here as they can be generated in vast
319 // quantities so as to generate blocks faster, degrading the system back into
320 // a proof-of-work situation.
322 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)
324 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
325 return error("CheckStakeKernelHash() : nTime violation");
327 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
328 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
329 return error("CheckStakeKernelHash() : min age violation");
331 CBigNum bnTargetPerCoinDay;
332 bnTargetPerCoinDay.SetCompact(nBits);
333 int64 nValueIn = txPrev.vout[prevout.n].nValue;
335 uint256 hashBlockFrom = blockFrom.GetHash();
337 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
338 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
341 CDataStream ss(SER_GETHASH, 0);
342 uint64 nStakeModifier = 0;
343 int nStakeModifierHeight = 0;
344 int64 nStakeModifierTime = 0;
346 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
348 ss << nStakeModifier;
350 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
351 hashProofOfStake = Hash(ss.begin(), ss.end());
352 if (fPrintProofOfStake)
354 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
355 nStakeModifier, nStakeModifierHeight,
356 DateTimeStrFormat(nStakeModifierTime).c_str(),
357 mapBlockIndex[hashBlockFrom]->nHeight,
358 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
359 printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
361 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
362 hashProofOfStake.ToString().c_str());
365 // Now check if proof-of-stake hash meets target protocol
366 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
368 if (fDebug && !fPrintProofOfStake)
370 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
371 nStakeModifier, nStakeModifierHeight,
372 DateTimeStrFormat(nStakeModifierTime).c_str(),
373 mapBlockIndex[hashBlockFrom]->nHeight,
374 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
375 printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
377 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
378 hashProofOfStake.ToString().c_str());
383 // Check kernel hash target and coinstake signature
384 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
386 if (!tx.IsCoinStake())
387 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
389 // Kernel (input 0) must match the stake hash target per coin age (nBits)
390 const CTxIn& txin = tx.vin[0];
392 // First try finding the previous transaction in database
396 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
397 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
404 if (!VerifySignature(txPrev, tx, 0, MANDATORY_SCRIPT_VERIFY_FLAGS, 0))
405 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
409 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
410 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
412 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
413 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
418 // Get stake modifier checksum
419 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
421 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
422 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
423 CDataStream ss(SER_GETHASH, 0);
425 ss << pindex->pprev->nStakeModifierChecksum;
426 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
427 uint256 hashChecksum = Hash(ss.begin(), ss.end());
428 hashChecksum >>= (256 - 32);
429 return hashChecksum.Get64();
432 // Check stake modifier hard checkpoints
433 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
435 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
437 if (checkpoints.count(nHeight))
438 return nStakeModifierChecksum == checkpoints[nHeight];