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
35 int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
37 // Kernel hash weight starts from 0 at the 30-day min age
38 // this change increases active coins participating the hash and helps
39 // to secure the network when proof-of-stake difficulty is low
41 // Maximum TimeWeight is 90 days.
43 return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
46 // Get the last stake modifier and its generation time from a given block
47 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
50 return error("GetLastStakeModifier: null pindex");
51 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
52 pindex = pindex->pprev;
53 if (!pindex->GeneratedStakeModifier())
54 return error("GetLastStakeModifier: no generation at genesis block");
55 nStakeModifier = pindex->nStakeModifier;
56 nModifierTime = pindex->GetBlockTime();
60 // Get selection interval section (in seconds)
61 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
63 assert (nSection >= 0 && nSection < 64);
64 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
67 // Get stake modifier selection interval (in seconds)
68 static int64 GetStakeModifierSelectionInterval()
70 int64 nSelectionInterval = 0;
71 for (int nSection=0; nSection<64; nSection++)
72 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
73 return nSelectionInterval;
76 // select a block from the candidate blocks in vSortedByTimestamp, excluding
77 // already selected blocks in vSelectedBlocks, and with timestamp up to
78 // nSelectionIntervalStop.
79 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
80 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
82 bool fSelected = false;
84 *pindexSelected = (const CBlockIndex*) 0;
85 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
87 if (!mapBlockIndex.count(item.second))
88 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
89 const CBlockIndex* pindex = mapBlockIndex[item.second];
90 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
92 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
94 // compute the selection hash by hashing its proof-hash and the
95 // previous proof-of-stake modifier
96 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
97 CDataStream ss(SER_GETHASH, 0);
98 ss << hashProof << nStakeModifierPrev;
99 uint256 hashSelection = Hash(ss.begin(), ss.end());
100 // the selection hash is divided by 2**32 so that proof-of-stake block
101 // is always favored over proof-of-work block. this is to preserve
102 // the energy efficiency property
103 if (pindex->IsProofOfStake())
104 hashSelection >>= 32;
105 if (fSelected && hashSelection < hashBest)
107 hashBest = hashSelection;
108 *pindexSelected = (const CBlockIndex*) pindex;
113 hashBest = hashSelection;
114 *pindexSelected = (const CBlockIndex*) pindex;
117 if (fDebug && GetBoolArg("-printstakemodifier"))
118 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
122 // Stake Modifier (hash modifier of proof-of-stake):
123 // The purpose of stake modifier is to prevent a txout (coin) owner from
124 // computing future proof-of-stake generated by this txout at the time
125 // of transaction confirmation. To meet kernel protocol, the txout
126 // must hash with a future stake modifier to generate the proof.
127 // Stake modifier consists of bits each of which is contributed from a
128 // selected block of a given block group in the past.
129 // The selection of a block is based on a hash of the block's proof-hash and
130 // the previous stake modifier.
131 // Stake modifier is recomputed at a fixed time interval instead of every
132 // block. This is to make it difficult for an attacker to gain control of
133 // additional bits in the stake modifier, even after generating a chain of
135 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
138 fGeneratedStakeModifier = false;
141 fGeneratedStakeModifier = true;
142 return true; // genesis block's modifier is 0
144 // First find current stake modifier and its generation block time
145 // if it's not old enough, return the same stake modifier
146 int64 nModifierTime = 0;
147 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
148 return error("ComputeNextStakeModifier: unable to get last modifier");
151 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
153 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
156 // Sort candidate blocks by timestamp
157 vector<pair<int64, uint256> > vSortedByTimestamp;
158 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
159 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
160 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
161 const CBlockIndex* pindex = pindexPrev;
162 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
164 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
165 pindex = pindex->pprev;
167 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
168 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
169 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
171 // Select 64 blocks from candidate blocks to generate stake modifier
172 uint64 nStakeModifierNew = 0;
173 int64 nSelectionIntervalStop = nSelectionIntervalStart;
174 map<uint256, const CBlockIndex*> mapSelectedBlocks;
175 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
177 // add an interval section to the current selection round
178 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
179 // select a block from the candidates of current round
180 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
181 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
182 // write the entropy bit of the selected block
183 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
184 // add the selected block from candidates to selected list
185 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
186 if (fDebug && GetBoolArg("-printstakemodifier"))
187 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
190 // Print selection map for visualization of the selected blocks
191 if (fDebug && GetBoolArg("-printstakemodifier"))
193 string strSelectionMap = "";
194 // '-' indicates proof-of-work blocks not selected
195 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
197 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
199 // '=' indicates proof-of-stake blocks not selected
200 if (pindex->IsProofOfStake())
201 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
202 pindex = pindex->pprev;
204 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
206 // 'S' indicates selected proof-of-stake blocks
207 // 'W' indicates selected proof-of-work blocks
208 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
210 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
214 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
217 nStakeModifier = nStakeModifierNew;
218 fGeneratedStakeModifier = true;
222 // The stake modifier used to hash for a stake kernel is chosen as the stake
223 // modifier about a selection interval later than the coin generating the kernel
224 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
227 if (!mapBlockIndex.count(hashBlockFrom))
228 return error("GetKernelStakeModifier() : block not indexed");
229 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
230 nStakeModifierHeight = pindexFrom->nHeight;
231 nStakeModifierTime = pindexFrom->GetBlockTime();
232 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
233 const CBlockIndex* pindex = pindexFrom;
234 // loop to find the stake modifier later by a selection interval
235 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
238 { // reached best block; may happen if node is behind on block chain
239 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
240 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
241 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
245 pindex = pindex->pnext;
246 if (pindex->GeneratedStakeModifier())
248 nStakeModifierHeight = pindex->nHeight;
249 nStakeModifierTime = pindex->GetBlockTime();
252 nStakeModifier = pindex->nStakeModifier;
256 // ppcoin kernel protocol
257 // coinstake must meet hash target according to the protocol:
258 // kernel (input 0) must meet the formula
259 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
260 // this ensures that the chance of getting a coinstake is proportional to the
261 // amount of coin age one owns.
262 // The reason this hash is chosen is the following:
263 // nStakeModifier: scrambles computation to make it very difficult to precompute
264 // future proof-of-stake at the time of the coin's confirmation
265 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
266 // generate transaction for future advantage
267 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
268 // nodes generating coinstake at the same time
269 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
271 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
272 // generating coinstake at the same time
273 // block/tx hash should not be used here as they can be generated in vast
274 // quantities so as to generate blocks faster, degrading the system back into
275 // a proof-of-work situation.
277 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)
279 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
280 return error("CheckStakeKernelHash() : nTime violation");
282 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
283 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
284 return error("CheckStakeKernelHash() : min age violation");
286 CBigNum bnTargetPerCoinDay;
287 bnTargetPerCoinDay.SetCompact(nBits);
288 int64 nValueIn = txPrev.vout[prevout.n].nValue;
290 uint256 hashBlockFrom = blockFrom.GetHash();
292 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
293 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
296 CDataStream ss(SER_GETHASH, 0);
297 uint64 nStakeModifier = 0;
298 int nStakeModifierHeight = 0;
299 int64 nStakeModifierTime = 0;
301 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
303 ss << nStakeModifier;
305 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
306 hashProofOfStake = Hash(ss.begin(), ss.end());
307 if (fPrintProofOfStake)
309 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
310 nStakeModifier, nStakeModifierHeight,
311 DateTimeStrFormat(nStakeModifierTime).c_str(),
312 mapBlockIndex[hashBlockFrom]->nHeight,
313 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
314 printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
316 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
317 hashProofOfStake.ToString().c_str());
320 // Now check if proof-of-stake hash meets target protocol
321 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
323 if (fDebug && !fPrintProofOfStake)
325 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
326 nStakeModifier, nStakeModifierHeight,
327 DateTimeStrFormat(nStakeModifierTime).c_str(),
328 mapBlockIndex[hashBlockFrom]->nHeight,
329 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
330 printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
332 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
333 hashProofOfStake.ToString().c_str());
338 // Check kernel hash target and coinstake signature
339 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
341 if (!tx.IsCoinStake())
342 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
344 // Kernel (input 0) must match the stake hash target per coin age (nBits)
345 const CTxIn& txin = tx.vin[0];
347 // First try finding the previous transaction in database
351 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
352 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];