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 // Modifier interval: time to elapse before new modifier is computed
13 // Set to 6-hour for production network and 20-minute for test network
14 unsigned int nModifierInterval = MODIFIER_INTERVAL;
16 // Hard checkpoints of stake modifiers to ensure they are deterministic
17 static std::map<int, unsigned int> mapStakeModifierCheckpoints =
18 boost::assign::map_list_of
21 ( 12661, 0x5d84115du )
24 // Get the last stake modifier and its generation time from a given block
25 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
28 return error("GetLastStakeModifier: null pindex");
29 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
30 pindex = pindex->pprev;
31 if (!pindex->GeneratedStakeModifier())
32 return error("GetLastStakeModifier: no generation at genesis block");
33 nStakeModifier = pindex->nStakeModifier;
34 nModifierTime = pindex->GetBlockTime();
38 // Get selection interval section (in seconds)
39 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
41 assert (nSection >= 0 && nSection < 64);
42 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
45 // Get stake modifier selection interval (in seconds)
46 static int64 GetStakeModifierSelectionInterval()
48 int64 nSelectionInterval = 0;
49 for (int nSection=0; nSection<64; nSection++)
50 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
51 return nSelectionInterval;
54 // select a block from the candidate blocks in vSortedByTimestamp, excluding
55 // already selected blocks in vSelectedBlocks, and with timestamp up to
56 // nSelectionIntervalStop.
57 static bool SelectBlockFromCandidates(
58 vector<pair<int64, uint256> >& vSortedByTimestamp,
59 map<uint256, const CBlockIndex*>& mapSelectedBlocks,
60 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
61 const CBlockIndex** pindexSelected)
63 bool fSelected = false;
65 *pindexSelected = (const CBlockIndex*) 0;
66 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
68 if (!mapBlockIndex.count(item.second))
69 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
70 const CBlockIndex* pindex = mapBlockIndex[item.second];
71 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
73 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
75 // compute the selection hash by hashing its proof-hash and the
76 // previous proof-of-stake modifier
77 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
78 CDataStream ss(SER_GETHASH, 0);
79 ss << hashProof << nStakeModifierPrev;
80 uint256 hashSelection = Hash(ss.begin(), ss.end());
81 // the selection hash is divided by 2**32 so that proof-of-stake block
82 // is always favored over proof-of-work block. this is to preserve
83 // the energy efficiency property
84 if (pindex->IsProofOfStake())
86 if (fSelected && hashSelection < hashBest)
88 hashBest = hashSelection;
89 *pindexSelected = (const CBlockIndex*) pindex;
94 hashBest = hashSelection;
95 *pindexSelected = (const CBlockIndex*) pindex;
98 if (fDebug && GetBoolArg("-printstakemodifier"))
99 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
103 // Stake Modifier (hash modifier of proof-of-stake):
104 // The purpose of stake modifier is to prevent a txout (coin) owner from
105 // computing future proof-of-stake generated by this txout at the time
106 // of transaction confirmation. To meet kernel protocol, the txout
107 // must hash with a future stake modifier to generate the proof.
108 // Stake modifier consists of bits each of which is contributed from a
109 // selected block of a given block group in the past.
110 // The selection of a block is based on a hash of the block's proof-hash and
111 // the previous stake modifier.
112 // Stake modifier is recomputed at a fixed time interval instead of every
113 // block. This is to make it difficult for an attacker to gain control of
114 // additional bits in the stake modifier, even after generating a chain of
116 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
119 fGeneratedStakeModifier = false;
122 fGeneratedStakeModifier = true;
123 return true; // genesis block's modifier is 0
125 // First find current stake modifier and its generation block time
126 // if it's not old enough, return the same stake modifier
127 int64 nModifierTime = 0;
128 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
129 return error("ComputeNextStakeModifier: unable to get last modifier");
132 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
134 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
137 // Sort candidate blocks by timestamp
138 vector<pair<int64, uint256> > vSortedByTimestamp;
139 vSortedByTimestamp.reserve(64 * nModifierInterval / STAKE_TARGET_SPACING);
140 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
141 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
142 const CBlockIndex* pindex = pindexPrev;
143 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
145 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
146 pindex = pindex->pprev;
148 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
149 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
150 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
152 // Select 64 blocks from candidate blocks to generate stake modifier
153 uint64 nStakeModifierNew = 0;
154 int64 nSelectionIntervalStop = nSelectionIntervalStart;
155 map<uint256, const CBlockIndex*> mapSelectedBlocks;
156 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
158 // add an interval section to the current selection round
159 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
160 // select a block from the candidates of current round
161 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
162 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
163 // write the entropy bit of the selected block
164 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
165 // add the selected block from candidates to selected list
166 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
167 if (fDebug && GetBoolArg("-printstakemodifier"))
168 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
169 nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
172 // Print selection map for visualization of the selected blocks
173 if (fDebug && GetBoolArg("-printstakemodifier"))
175 string strSelectionMap = "";
176 // '-' indicates proof-of-work blocks not selected
177 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
179 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
181 // '=' indicates proof-of-stake blocks not selected
182 if (pindex->IsProofOfStake())
183 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
184 pindex = pindex->pprev;
186 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
188 // 'S' indicates selected proof-of-stake blocks
189 // 'W' indicates selected proof-of-work blocks
190 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
192 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
196 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
199 nStakeModifier = nStakeModifierNew;
200 fGeneratedStakeModifier = true;
204 // The stake modifier used to hash for a stake kernel is chosen as the stake
205 // modifier about a selection interval later than the coin generating the kernel
206 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
209 if (!mapBlockIndex.count(hashBlockFrom))
210 return error("GetKernelStakeModifier() : block not indexed");
211 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
212 nStakeModifierHeight = pindexFrom->nHeight;
213 nStakeModifierTime = pindexFrom->GetBlockTime();
214 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
215 const CBlockIndex* pindex = pindexFrom;
216 // loop to find the stake modifier later by a selection interval
217 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
220 { // reached best block; may happen if node is behind on block chain
221 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
222 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
223 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
227 pindex = pindex->pnext;
228 if (pindex->GeneratedStakeModifier())
230 nStakeModifierHeight = pindex->nHeight;
231 nStakeModifierTime = pindex->GetBlockTime();
234 nStakeModifier = pindex->nStakeModifier;
238 // ppcoin kernel protocol
239 // coinstake must meet hash target according to the protocol:
240 // kernel (input 0) must meet the formula
241 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
242 // this ensures that the chance of getting a coinstake is proportional to the
243 // amount of coin age one owns.
244 // The reason this hash is chosen is the following:
246 // (v0.3) scrambles computation to make it very difficult to precompute
247 // future proof-of-stake at the time of the coin's confirmation
248 // (v0.2) nBits (deprecated): encodes all past block timestamps
249 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
250 // generate transaction for future advantage
251 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
252 // nodes generating coinstake at the same time
253 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
255 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
256 // generating coinstake at the same time
257 // block/tx hash should not be used here as they can be generated in vast
258 // quantities so as to generate blocks faster, degrading the system back into
259 // a proof-of-work situation.
261 bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, bool fPrintProofOfStake)
263 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
264 return error("CheckStakeKernelHash() : nTime violation");
266 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
267 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
268 return error("CheckStakeKernelHash() : min age violation");
270 CBigNum bnTargetPerCoinDay;
271 bnTargetPerCoinDay.SetCompact(nBits);
272 int64 nValueIn = txPrev.vout[prevout.n].nValue;
274 // v0.3 protocol kernel hash weight starts from 0 at the 30-day min age
275 // this change increases active coins participating the hash and helps
276 // to secure the network when proof-of-stake difficulty is low
277 int64 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)STAKE_MAX_AGE) - nStakeMinAge;
278 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
281 CDataStream ss(SER_GETHASH, 0);
282 uint64 nStakeModifier = 0;
283 int nStakeModifierHeight = 0;
284 int64 nStakeModifierTime = 0;
286 if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
288 ss << nStakeModifier;
290 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
291 hashProofOfStake = Hash(ss.begin(), ss.end());
292 if (fPrintProofOfStake)
294 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
295 nStakeModifier, nStakeModifierHeight,
296 DateTimeStrFormat(nStakeModifierTime).c_str(),
297 mapBlockIndex[blockFrom.GetHash()]->nHeight,
298 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
299 printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
302 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
303 hashProofOfStake.ToString().c_str());
306 // Now check if proof-of-stake hash meets target protocol
307 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
309 if (fDebug && !fPrintProofOfStake)
311 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
312 nStakeModifier, nStakeModifierHeight,
313 DateTimeStrFormat(nStakeModifierTime).c_str(),
314 mapBlockIndex[blockFrom.GetHash()]->nHeight,
315 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
316 printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
319 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
320 hashProofOfStake.ToString().c_str());
325 // Check kernel hash target and coinstake signature
326 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake)
328 if (!tx.IsCoinStake())
329 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
331 // Kernel (input 0) must match the stake hash target per coin age (nBits)
332 const CTxIn& txin = tx.vin[0];
334 // First try finding the previous transaction in database
338 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
339 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
343 if (!VerifySignature(txPrev, tx, 0, true, 0))
344 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
348 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
349 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
351 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, fDebug))
352 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
357 // Check whether the coinstake timestamp meets protocol
358 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
361 return (nTimeBlock == nTimeTx);
364 // Get stake modifier checksum
365 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
367 assert (pindex->pprev || pindex->GetBlockHash() == hashGenesisBlock);
368 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
369 CDataStream ss(SER_GETHASH, 0);
371 ss << pindex->pprev->nStakeModifierChecksum;
372 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
373 uint256 hashChecksum = Hash(ss.begin(), ss.end());
374 hashChecksum >>= (256 - 32);
375 return hashChecksum.Get64();
378 // Check stake modifier hard checkpoints
379 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
381 if (fTestNet) return true; // Testnet has no checkpoints
382 if (mapStakeModifierCheckpoints.count(nHeight))
383 return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];