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 )
24 ( 44200, 0x05370164u )
25 ( 65000, 0xc8e7be6au )
28 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
29 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
30 boost::assign::map_list_of
34 // Get the last stake modifier and its generation time from a given block
35 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
38 return error("GetLastStakeModifier: null pindex");
39 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
40 pindex = pindex->pprev;
41 if (!pindex->GeneratedStakeModifier())
42 return error("GetLastStakeModifier: no generation at genesis block");
43 nStakeModifier = pindex->nStakeModifier;
44 nModifierTime = pindex->GetBlockTime();
48 // Get selection interval section (in seconds)
49 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
51 assert (nSection >= 0 && nSection < 64);
52 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
55 // Get stake modifier selection interval (in seconds)
56 static int64 GetStakeModifierSelectionInterval()
58 int64 nSelectionInterval = 0;
59 for (int nSection=0; nSection<64; nSection++)
60 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
61 return nSelectionInterval;
64 // select a block from the candidate blocks in vSortedByTimestamp, excluding
65 // already selected blocks in vSelectedBlocks, and with timestamp up to
66 // nSelectionIntervalStop.
67 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
68 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
70 bool fSelected = false;
72 *pindexSelected = (const CBlockIndex*) 0;
73 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
75 if (!mapBlockIndex.count(item.second))
76 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
77 const CBlockIndex* pindex = mapBlockIndex[item.second];
78 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
80 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
82 // compute the selection hash by hashing its proof-hash and the
83 // previous proof-of-stake modifier
84 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
85 CDataStream ss(SER_GETHASH, 0);
86 ss << hashProof << nStakeModifierPrev;
87 uint256 hashSelection = Hash(ss.begin(), ss.end());
88 // the selection hash is divided by 2**32 so that proof-of-stake block
89 // is always favored over proof-of-work block. this is to preserve
90 // the energy efficiency property
91 if (pindex->IsProofOfStake())
93 if (fSelected && hashSelection < hashBest)
95 hashBest = hashSelection;
96 *pindexSelected = (const CBlockIndex*) pindex;
101 hashBest = hashSelection;
102 *pindexSelected = (const CBlockIndex*) pindex;
105 if (fDebug && GetBoolArg("-printstakemodifier"))
106 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
110 // Stake Modifier (hash modifier of proof-of-stake):
111 // The purpose of stake modifier is to prevent a txout (coin) owner from
112 // computing future proof-of-stake generated by this txout at the time
113 // of transaction confirmation. To meet kernel protocol, the txout
114 // must hash with a future stake modifier to generate the proof.
115 // Stake modifier consists of bits each of which is contributed from a
116 // selected block of a given block group in the past.
117 // The selection of a block is based on a hash of the block's proof-hash and
118 // the previous stake modifier.
119 // Stake modifier is recomputed at a fixed time interval instead of every
120 // block. This is to make it difficult for an attacker to gain control of
121 // additional bits in the stake modifier, even after generating a chain of
123 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
126 fGeneratedStakeModifier = false;
129 fGeneratedStakeModifier = true;
130 return true; // genesis block's modifier is 0
132 // First find current stake modifier and its generation block time
133 // if it's not old enough, return the same stake modifier
134 int64 nModifierTime = 0;
135 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
136 return error("ComputeNextStakeModifier: unable to get last modifier");
139 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
141 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
144 // Sort candidate blocks by timestamp
145 vector<pair<int64, uint256> > vSortedByTimestamp;
146 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
147 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
148 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
149 const CBlockIndex* pindex = pindexPrev;
150 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
152 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
153 pindex = pindex->pprev;
155 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
156 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
157 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
159 // Select 64 blocks from candidate blocks to generate stake modifier
160 uint64 nStakeModifierNew = 0;
161 int64 nSelectionIntervalStop = nSelectionIntervalStart;
162 map<uint256, const CBlockIndex*> mapSelectedBlocks;
163 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
165 // add an interval section to the current selection round
166 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
167 // select a block from the candidates of current round
168 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
169 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
170 // write the entropy bit of the selected block
171 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
172 // add the selected block from candidates to selected list
173 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
174 if (fDebug && GetBoolArg("-printstakemodifier"))
175 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
178 // Print selection map for visualization of the selected blocks
179 if (fDebug && GetBoolArg("-printstakemodifier"))
181 string strSelectionMap = "";
182 // '-' indicates proof-of-work blocks not selected
183 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
185 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
187 // '=' indicates proof-of-stake blocks not selected
188 if (pindex->IsProofOfStake())
189 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
190 pindex = pindex->pprev;
192 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
194 // 'S' indicates selected proof-of-stake blocks
195 // 'W' indicates selected proof-of-work blocks
196 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
198 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
202 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
205 nStakeModifier = nStakeModifierNew;
206 fGeneratedStakeModifier = true;
210 // The stake modifier used to hash for a stake kernel is chosen as the stake
211 // modifier about a selection interval later than the coin generating the kernel
212 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
215 if (!mapBlockIndex.count(hashBlockFrom))
216 return error("GetKernelStakeModifier() : block not indexed");
217 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
218 nStakeModifierHeight = pindexFrom->nHeight;
219 nStakeModifierTime = pindexFrom->GetBlockTime();
220 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
221 const CBlockIndex* pindex = pindexFrom;
222 // loop to find the stake modifier later by a selection interval
223 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
226 { // reached best block; may happen if node is behind on block chain
227 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
228 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
229 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
233 pindex = pindex->pnext;
234 if (pindex->GeneratedStakeModifier())
236 nStakeModifierHeight = pindex->nHeight;
237 nStakeModifierTime = pindex->GetBlockTime();
240 nStakeModifier = pindex->nStakeModifier;
244 // ppcoin kernel protocol
245 // coinstake must meet hash target according to the protocol:
246 // kernel (input 0) must meet the formula
247 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
248 // this ensures that the chance of getting a coinstake is proportional to the
249 // amount of coin age one owns.
250 // The reason this hash is chosen is the following:
251 // nStakeModifier: scrambles computation to make it very difficult to precompute
252 // future proof-of-stake at the time of the coin's confirmation
253 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
254 // generate transaction for future advantage
255 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
256 // nodes generating coinstake at the same time
257 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
259 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
260 // generating coinstake at the same time
261 // block/tx hash should not be used here as they can be generated in vast
262 // quantities so as to generate blocks faster, degrading the system back into
263 // a proof-of-work situation.
265 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)
267 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
268 return error("CheckStakeKernelHash() : nTime violation");
270 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
271 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
272 return error("CheckStakeKernelHash() : min age violation");
274 CBigNum bnTargetPerCoinDay;
275 bnTargetPerCoinDay.SetCompact(nBits);
276 int64 nValueIn = txPrev.vout[prevout.n].nValue;
279 uint256 hashBlockFrom = blockFrom.GetHash();
281 // Kernel hash weight starts from 0 at the 30-day min age
282 // this change increases active coins participating the hash and helps
283 // to secure the network when proof-of-stake difficulty is low
285 // Maximum TimeWeight is 90 days.
286 nTimeWeight = min((int64)nTimeTx - txPrev.nTime - nStakeMinAge, (int64)nStakeMaxAge);
288 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
289 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
292 CDataStream ss(SER_GETHASH, 0);
293 uint64 nStakeModifier = 0;
294 int nStakeModifierHeight = 0;
295 int64 nStakeModifierTime = 0;
297 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
299 ss << nStakeModifier;
301 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
302 hashProofOfStake = Hash(ss.begin(), ss.end());
303 if (fPrintProofOfStake)
305 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
306 nStakeModifier, nStakeModifierHeight,
307 DateTimeStrFormat(nStakeModifierTime).c_str(),
308 mapBlockIndex[hashBlockFrom]->nHeight,
309 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
310 printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
312 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
313 hashProofOfStake.ToString().c_str());
316 // Now check if proof-of-stake hash meets target protocol
317 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
319 if (fDebug && !fPrintProofOfStake)
321 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
322 nStakeModifier, nStakeModifierHeight,
323 DateTimeStrFormat(nStakeModifierTime).c_str(),
324 mapBlockIndex[hashBlockFrom]->nHeight,
325 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
326 printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
328 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
329 hashProofOfStake.ToString().c_str());
334 // Check kernel hash target and coinstake signature
335 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
337 if (!tx.IsCoinStake())
338 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
340 // Kernel (input 0) must match the stake hash target per coin age (nBits)
341 const CTxIn& txin = tx.vin[0];
343 // First try finding the previous transaction in database
347 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
348 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
355 if (!VerifySignature(txPrev, tx, 0, true, 0))
356 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
360 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
361 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
363 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
364 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
369 // Check whether the coinstake timestamp meets protocol
370 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
373 return (nTimeBlock == nTimeTx);
376 // Get stake modifier checksum
377 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
379 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
380 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
381 CDataStream ss(SER_GETHASH, 0);
383 ss << pindex->pprev->nStakeModifierChecksum;
384 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
385 uint256 hashChecksum = Hash(ss.begin(), ss.end());
386 hashChecksum >>= (256 - 32);
387 return hashChecksum.Get64();
390 // Check stake modifier hard checkpoints
391 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
393 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
395 if (checkpoints.count(nHeight))
396 return nStakeModifierChecksum == checkpoints[nHeight];