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 // Hard checkpoints of stake modifiers to ensure they are deterministic
16 static std::map<int, unsigned int> mapStakeModifierCheckpoints =
17 boost::assign::map_list_of
21 ( 12661, 0x5d84115du )
22 ( 19600, 0xdded1b8du )
23 ( 21800, 0x0daa1aaau )
26 // Get the last stake modifier and its generation time from a given block
27 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
30 return error("GetLastStakeModifier: null pindex");
31 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
32 pindex = pindex->pprev;
33 if (!pindex->GeneratedStakeModifier())
34 return error("GetLastStakeModifier: no generation at genesis block");
35 nStakeModifier = pindex->nStakeModifier;
36 nModifierTime = pindex->GetBlockTime();
40 // Get selection interval section (in seconds)
41 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
43 assert (nSection >= 0 && nSection < 64);
44 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
47 // Get stake modifier selection interval (in seconds)
48 static int64 GetStakeModifierSelectionInterval()
50 int64 nSelectionInterval = 0;
51 for (int nSection=0; nSection<64; nSection++)
52 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
53 return nSelectionInterval;
56 // select a block from the candidate blocks in vSortedByTimestamp, excluding
57 // already selected blocks in vSelectedBlocks, and with timestamp up to
58 // nSelectionIntervalStop.
59 static bool SelectBlockFromCandidates(
60 vector<pair<int64, uint256> >& vSortedByTimestamp,
61 map<uint256, const CBlockIndex*>& mapSelectedBlocks,
62 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
63 const CBlockIndex** pindexSelected)
65 bool fSelected = false;
67 *pindexSelected = (const CBlockIndex*) 0;
68 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
70 if (!mapBlockIndex.count(item.second))
71 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
72 const CBlockIndex* pindex = mapBlockIndex[item.second];
73 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
75 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
77 // compute the selection hash by hashing its proof-hash and the
78 // previous proof-of-stake modifier
79 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
80 CDataStream ss(SER_GETHASH, 0);
81 ss << hashProof << nStakeModifierPrev;
82 uint256 hashSelection = Hash(ss.begin(), ss.end());
83 // the selection hash is divided by 2**32 so that proof-of-stake block
84 // is always favored over proof-of-work block. this is to preserve
85 // the energy efficiency property
86 if (pindex->IsProofOfStake())
88 if (fSelected && hashSelection < hashBest)
90 hashBest = hashSelection;
91 *pindexSelected = (const CBlockIndex*) pindex;
96 hashBest = hashSelection;
97 *pindexSelected = (const CBlockIndex*) pindex;
100 if (fDebug && GetBoolArg("-printstakemodifier"))
101 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
105 // Stake Modifier (hash modifier of proof-of-stake):
106 // The purpose of stake modifier is to prevent a txout (coin) owner from
107 // computing future proof-of-stake generated by this txout at the time
108 // of transaction confirmation. To meet kernel protocol, the txout
109 // must hash with a future stake modifier to generate the proof.
110 // Stake modifier consists of bits each of which is contributed from a
111 // selected block of a given block group in the past.
112 // The selection of a block is based on a hash of the block's proof-hash and
113 // the previous stake modifier.
114 // Stake modifier is recomputed at a fixed time interval instead of every
115 // block. This is to make it difficult for an attacker to gain control of
116 // additional bits in the stake modifier, even after generating a chain of
118 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
121 fGeneratedStakeModifier = false;
124 fGeneratedStakeModifier = true;
125 return true; // genesis block's modifier is 0
127 // First find current stake modifier and its generation block time
128 // if it's not old enough, return the same stake modifier
129 int64 nModifierTime = 0;
130 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
131 return error("ComputeNextStakeModifier: unable to get last modifier");
134 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
136 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
139 // Sort candidate blocks by timestamp
140 vector<pair<int64, uint256> > vSortedByTimestamp;
141 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
142 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
143 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
144 const CBlockIndex* pindex = pindexPrev;
145 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
147 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
148 pindex = pindex->pprev;
150 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
151 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
152 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
154 // Select 64 blocks from candidate blocks to generate stake modifier
155 uint64 nStakeModifierNew = 0;
156 int64 nSelectionIntervalStop = nSelectionIntervalStart;
157 map<uint256, const CBlockIndex*> mapSelectedBlocks;
158 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
160 // add an interval section to the current selection round
161 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
162 // select a block from the candidates of current round
163 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
164 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
165 // write the entropy bit of the selected block
166 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
167 // add the selected block from candidates to selected list
168 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
169 if (fDebug && GetBoolArg("-printstakemodifier"))
170 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
171 nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
174 // Print selection map for visualization of the selected blocks
175 if (fDebug && GetBoolArg("-printstakemodifier"))
177 string strSelectionMap = "";
178 // '-' indicates proof-of-work blocks not selected
179 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
181 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
183 // '=' indicates proof-of-stake blocks not selected
184 if (pindex->IsProofOfStake())
185 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
186 pindex = pindex->pprev;
188 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
190 // 'S' indicates selected proof-of-stake blocks
191 // 'W' indicates selected proof-of-work blocks
192 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
194 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
198 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
201 nStakeModifier = nStakeModifierNew;
202 fGeneratedStakeModifier = true;
206 // The stake modifier used to hash for a stake kernel is chosen as the stake
207 // modifier about a selection interval later than the coin generating the kernel
208 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
211 if (!mapBlockIndex.count(hashBlockFrom))
212 return error("GetKernelStakeModifier() : block not indexed");
213 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
214 nStakeModifierHeight = pindexFrom->nHeight;
215 nStakeModifierTime = pindexFrom->GetBlockTime();
216 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
217 const CBlockIndex* pindex = pindexFrom;
218 // loop to find the stake modifier later by a selection interval
219 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
222 { // reached best block; may happen if node is behind on block chain
223 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
224 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
225 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
229 pindex = pindex->pnext;
230 if (pindex->GeneratedStakeModifier())
232 nStakeModifierHeight = pindex->nHeight;
233 nStakeModifierTime = pindex->GetBlockTime();
236 nStakeModifier = pindex->nStakeModifier;
240 // ppcoin kernel protocol
241 // coinstake must meet hash target according to the protocol:
242 // kernel (input 0) must meet the formula
243 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
244 // this ensures that the chance of getting a coinstake is proportional to the
245 // amount of coin age one owns.
246 // The reason this hash is chosen is the following:
248 // (v0.3) scrambles computation to make it very difficult to precompute
249 // future proof-of-stake at the time of the coin's confirmation
250 // (v0.2) nBits (deprecated): encodes all past block timestamps
251 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
252 // generate transaction for future advantage
253 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
254 // nodes generating coinstake at the same time
255 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
257 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
258 // generating coinstake at the same time
259 // block/tx hash should not be used here as they can be generated in vast
260 // quantities so as to generate blocks faster, degrading the system back into
261 // a proof-of-work situation.
263 bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, bool fPrintProofOfStake)
265 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
266 return error("CheckStakeKernelHash() : nTime violation");
268 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
269 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
270 return error("CheckStakeKernelHash() : min age violation");
272 CBigNum bnTargetPerCoinDay;
273 bnTargetPerCoinDay.SetCompact(nBits);
274 int64 nValueIn = txPrev.vout[prevout.n].nValue;
276 // v0.3 protocol kernel hash weight starts from 0 at the 30-day min age
277 // this change increases active coins participating the hash and helps
278 // to secure the network when proof-of-stake difficulty is low
279 int64 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
280 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
283 CDataStream ss(SER_GETHASH, 0);
284 uint64 nStakeModifier = 0;
285 int nStakeModifierHeight = 0;
286 int64 nStakeModifierTime = 0;
288 if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
290 ss << nStakeModifier;
292 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
293 hashProofOfStake = Hash(ss.begin(), ss.end());
294 if (fPrintProofOfStake)
296 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
297 nStakeModifier, nStakeModifierHeight,
298 DateTimeStrFormat(nStakeModifierTime).c_str(),
299 mapBlockIndex[blockFrom.GetHash()]->nHeight,
300 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
301 printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
304 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
305 hashProofOfStake.ToString().c_str());
308 // Now check if proof-of-stake hash meets target protocol
309 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
311 if (fDebug && !fPrintProofOfStake)
313 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
314 nStakeModifier, nStakeModifierHeight,
315 DateTimeStrFormat(nStakeModifierTime).c_str(),
316 mapBlockIndex[blockFrom.GetHash()]->nHeight,
317 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
318 printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
321 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
322 hashProofOfStake.ToString().c_str());
327 // Check kernel hash target and coinstake signature
328 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake)
330 if (!tx.IsCoinStake())
331 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
333 // Kernel (input 0) must match the stake hash target per coin age (nBits)
334 const CTxIn& txin = tx.vin[0];
336 // First try finding the previous transaction in database
340 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
341 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
345 if (!VerifySignature(txPrev, tx, 0, true, 0))
346 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
350 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
351 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
353 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, fDebug))
354 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
359 // Check whether the coinstake timestamp meets protocol
360 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
363 return (nTimeBlock == nTimeTx);
366 // Get stake modifier checksum
367 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
369 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
370 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
371 CDataStream ss(SER_GETHASH, 0);
373 ss << pindex->pprev->nStakeModifierChecksum;
374 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
375 uint256 hashChecksum = Hash(ss.begin(), ss.end());
376 hashChecksum >>= (256 - 32);
377 return hashChecksum.Get64();
380 // Check stake modifier hard checkpoints
381 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
383 if (fTestNet) return true; // Testnet has no checkpoints
384 if (mapStakeModifierCheckpoints.count(nHeight))
385 return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];