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
21 ( 68600, 0x73a8cc4cu )
24 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
25 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
26 boost::assign::map_list_of
31 int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
33 // Kernel hash weight starts from 0 at the 30-day min age
34 // this change increases active coins participating the hash and helps
35 // to secure the network when proof-of-stake difficulty is low
37 // Maximum TimeWeight is 90 days.
39 return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
42 // Get the last stake modifier and its generation time from a given block
43 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
46 return error("GetLastStakeModifier: null pindex");
47 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
48 pindex = pindex->pprev;
49 if (!pindex->GeneratedStakeModifier())
50 return error("GetLastStakeModifier: no generation at genesis block");
51 nStakeModifier = pindex->nStakeModifier;
52 nModifierTime = pindex->GetBlockTime();
56 // Get selection interval section (in seconds)
57 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
59 assert (nSection >= 0 && nSection < 64);
60 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
63 // Get stake modifier selection interval (in seconds)
64 static int64 GetStakeModifierSelectionInterval()
66 int64 nSelectionInterval = 0;
67 for (int nSection=0; nSection<64; nSection++)
68 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
69 return nSelectionInterval;
72 // select a block from the candidate blocks in vSortedByTimestamp, excluding
73 // already selected blocks in vSelectedBlocks, and with timestamp up to
74 // nSelectionIntervalStop.
75 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
76 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
78 bool fSelected = false;
80 *pindexSelected = (const CBlockIndex*) 0;
81 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
83 if (!mapBlockIndex.count(item.second))
84 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
85 const CBlockIndex* pindex = mapBlockIndex[item.second];
86 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
88 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
90 // compute the selection hash by hashing its proof-hash and the
91 // previous proof-of-stake modifier
92 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
93 CDataStream ss(SER_GETHASH, 0);
94 ss << hashProof << nStakeModifierPrev;
95 uint256 hashSelection = Hash(ss.begin(), ss.end());
96 // the selection hash is divided by 2**32 so that proof-of-stake block
97 // is always favored over proof-of-work block. this is to preserve
98 // the energy efficiency property
99 if (pindex->IsProofOfStake())
100 hashSelection >>= 32;
101 if (fSelected && hashSelection < hashBest)
103 hashBest = hashSelection;
104 *pindexSelected = (const CBlockIndex*) pindex;
109 hashBest = hashSelection;
110 *pindexSelected = (const CBlockIndex*) pindex;
113 if (fDebug && GetBoolArg("-printstakemodifier"))
114 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
118 // Stake Modifier (hash modifier of proof-of-stake):
119 // The purpose of stake modifier is to prevent a txout (coin) owner from
120 // computing future proof-of-stake generated by this txout at the time
121 // of transaction confirmation. To meet kernel protocol, the txout
122 // must hash with a future stake modifier to generate the proof.
123 // Stake modifier consists of bits each of which is contributed from a
124 // selected block of a given block group in the past.
125 // The selection of a block is based on a hash of the block's proof-hash and
126 // the previous stake modifier.
127 // Stake modifier is recomputed at a fixed time interval instead of every
128 // block. This is to make it difficult for an attacker to gain control of
129 // additional bits in the stake modifier, even after generating a chain of
131 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
134 fGeneratedStakeModifier = false;
137 fGeneratedStakeModifier = true;
138 return true; // genesis block's modifier is 0
140 // First find current stake modifier and its generation block time
141 // if it's not old enough, return the same stake modifier
142 int64 nModifierTime = 0;
143 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
144 return error("ComputeNextStakeModifier: unable to get last modifier");
147 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
149 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
152 // Sort candidate blocks by timestamp
153 vector<pair<int64, uint256> > vSortedByTimestamp;
154 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
155 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
156 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
157 const CBlockIndex* pindex = pindexPrev;
158 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
160 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
161 pindex = pindex->pprev;
163 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
164 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
165 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
167 // Select 64 blocks from candidate blocks to generate stake modifier
168 uint64 nStakeModifierNew = 0;
169 int64 nSelectionIntervalStop = nSelectionIntervalStart;
170 map<uint256, const CBlockIndex*> mapSelectedBlocks;
171 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
173 // add an interval section to the current selection round
174 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
175 // select a block from the candidates of current round
176 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
177 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
178 // write the entropy bit of the selected block
179 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
180 // add the selected block from candidates to selected list
181 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
182 if (fDebug && GetBoolArg("-printstakemodifier"))
183 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
186 // Print selection map for visualization of the selected blocks
187 if (fDebug && GetBoolArg("-printstakemodifier"))
189 string strSelectionMap = "";
190 // '-' indicates proof-of-work blocks not selected
191 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
193 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
195 // '=' indicates proof-of-stake blocks not selected
196 if (pindex->IsProofOfStake())
197 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
198 pindex = pindex->pprev;
200 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
202 // 'S' indicates selected proof-of-stake blocks
203 // 'W' indicates selected proof-of-work blocks
204 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
206 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
210 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
213 nStakeModifier = nStakeModifierNew;
214 fGeneratedStakeModifier = true;
218 // The stake modifier used to hash for a stake kernel is chosen as the stake
219 // modifier about a selection interval later than the coin generating the kernel
220 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
223 if (!mapBlockIndex.count(hashBlockFrom))
224 return error("GetKernelStakeModifier() : block not indexed");
225 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
226 nStakeModifierHeight = pindexFrom->nHeight;
227 nStakeModifierTime = pindexFrom->GetBlockTime();
228 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
229 const CBlockIndex* pindex = pindexFrom;
230 // loop to find the stake modifier later by a selection interval
231 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
234 { // reached best block; may happen if node is behind on block chain
235 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
236 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
237 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
241 pindex = pindex->pnext;
242 if (pindex->GeneratedStakeModifier())
244 nStakeModifierHeight = pindex->nHeight;
245 nStakeModifierTime = pindex->GetBlockTime();
248 nStakeModifier = pindex->nStakeModifier;
252 // ppcoin kernel protocol
253 // coinstake must meet hash target according to the protocol:
254 // kernel (input 0) must meet the formula
255 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
256 // this ensures that the chance of getting a coinstake is proportional to the
257 // amount of coin age one owns.
258 // The reason this hash is chosen is the following:
259 // nStakeModifier: scrambles computation to make it very difficult to precompute
260 // future proof-of-stake at the time of the coin's confirmation
261 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
262 // generate transaction for future advantage
263 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
264 // nodes generating coinstake at the same time
265 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
267 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
268 // generating coinstake at the same time
269 // block/tx hash should not be used here as they can be generated in vast
270 // quantities so as to generate blocks faster, degrading the system back into
271 // a proof-of-work situation.
273 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)
275 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
276 return error("CheckStakeKernelHash() : nTime violation");
278 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
279 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
280 return error("CheckStakeKernelHash() : min age violation");
282 CBigNum bnTargetPerCoinDay;
283 bnTargetPerCoinDay.SetCompact(nBits);
284 int64 nValueIn = txPrev.vout[prevout.n].nValue;
286 uint256 hashBlockFrom = blockFrom.GetHash();
288 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / 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());
304 if (fPrintProofOfStake)
306 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
307 nStakeModifier, nStakeModifierHeight,
308 DateTimeStrFormat(nStakeModifierTime).c_str(),
309 mapBlockIndex[hashBlockFrom]->nHeight,
310 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
311 printf("CheckStakeKernelHash() : check modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
313 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
314 hashProofOfStake.ToString().c_str());
317 // Now check if proof-of-stake hash meets target protocol
318 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
320 if (fDebug && !fPrintProofOfStake)
322 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
323 nStakeModifier, nStakeModifierHeight,
324 DateTimeStrFormat(nStakeModifierTime).c_str(),
325 mapBlockIndex[hashBlockFrom]->nHeight,
326 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
327 printf("CheckStakeKernelHash() : pass modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
329 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
330 hashProofOfStake.ToString().c_str());
335 // Check kernel hash target and coinstake signature
336 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake)
338 if (!tx.IsCoinStake())
339 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
341 // Kernel (input 0) must match the stake hash target per coin age (nBits)
342 const CTxIn& txin = tx.vin[0];
348 CCoinsViewCache &view = *pcoinsTip;
350 if (!view.GetCoins(txin.prevout.hash, coins))
351 return tx.DoS(1, error("CheckProofOfStake() : INFO: read coins for txPrev failed")); // previous transaction not in main chain, may occur during initial download
353 CBlockIndex* pindex = FindBlockByHeight(coins.nHeight);
355 // Read block and scan it to find txPrev
357 if (block.ReadFromDisk(pindex)) {
358 nTxPos = GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
359 BOOST_FOREACH(const CTransaction &tx, block.vtx) {
360 if (tx.GetHash() == txin.prevout.hash) {
364 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
368 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
371 if (!VerifySignature(coins, tx, 0, true, false, 0))
372 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
374 if (!CheckStakeKernelHash(nBits, block, nTxPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
375 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
380 // Check whether the coinstake timestamp meets protocol
381 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
384 return (nTimeBlock == nTimeTx);
387 // Get stake modifier checksum
388 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
390 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
391 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
392 CDataStream ss(SER_GETHASH, 0);
394 ss << pindex->pprev->nStakeModifierChecksum;
395 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
396 uint256 hashChecksum = Hash(ss.begin(), ss.end());
397 hashChecksum >>= (256 - 32);
398 return hashChecksum.Get64();
401 // Check stake modifier hard checkpoints
402 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
404 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
406 if (checkpoints.count(nHeight))
407 return nStakeModifierChecksum == checkpoints[nHeight];