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 )
24 ( 26174, 0xaf9983dcu )
27 // Get the last stake modifier and its generation time from a given block
28 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
31 return error("GetLastStakeModifier: null pindex");
32 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
33 pindex = pindex->pprev;
34 if (!pindex->GeneratedStakeModifier())
35 return error("GetLastStakeModifier: no generation at genesis block");
36 nStakeModifier = pindex->nStakeModifier;
37 nModifierTime = pindex->GetBlockTime();
41 // Get selection interval section (in seconds)
42 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
44 assert (nSection >= 0 && nSection < 64);
45 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
48 // Get stake modifier selection interval (in seconds)
49 static int64 GetStakeModifierSelectionInterval()
51 int64 nSelectionInterval = 0;
52 for (int nSection=0; nSection<64; nSection++)
53 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
54 return nSelectionInterval;
57 // select a block from the candidate blocks in vSortedByTimestamp, excluding
58 // already selected blocks in vSelectedBlocks, and with timestamp up to
59 // nSelectionIntervalStop.
60 static bool SelectBlockFromCandidates(
61 vector<pair<int64, uint256> >& vSortedByTimestamp,
62 map<uint256, const CBlockIndex*>& mapSelectedBlocks,
63 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev,
64 const CBlockIndex** pindexSelected)
66 bool fSelected = false;
68 *pindexSelected = (const CBlockIndex*) 0;
69 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
71 if (!mapBlockIndex.count(item.second))
72 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
73 const CBlockIndex* pindex = mapBlockIndex[item.second];
74 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
76 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
78 // compute the selection hash by hashing its proof-hash and the
79 // previous proof-of-stake modifier
80 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
81 CDataStream ss(SER_GETHASH, 0);
82 ss << hashProof << nStakeModifierPrev;
83 uint256 hashSelection = Hash(ss.begin(), ss.end());
84 // the selection hash is divided by 2**32 so that proof-of-stake block
85 // is always favored over proof-of-work block. this is to preserve
86 // the energy efficiency property
87 if (pindex->IsProofOfStake())
89 if (fSelected && hashSelection < hashBest)
91 hashBest = hashSelection;
92 *pindexSelected = (const CBlockIndex*) pindex;
97 hashBest = hashSelection;
98 *pindexSelected = (const CBlockIndex*) pindex;
101 if (fDebug && GetBoolArg("-printstakemodifier"))
102 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
106 // Stake Modifier (hash modifier of proof-of-stake):
107 // The purpose of stake modifier is to prevent a txout (coin) owner from
108 // computing future proof-of-stake generated by this txout at the time
109 // of transaction confirmation. To meet kernel protocol, the txout
110 // must hash with a future stake modifier to generate the proof.
111 // Stake modifier consists of bits each of which is contributed from a
112 // selected block of a given block group in the past.
113 // The selection of a block is based on a hash of the block's proof-hash and
114 // the previous stake modifier.
115 // Stake modifier is recomputed at a fixed time interval instead of every
116 // block. This is to make it difficult for an attacker to gain control of
117 // additional bits in the stake modifier, even after generating a chain of
119 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
122 fGeneratedStakeModifier = false;
125 fGeneratedStakeModifier = true;
126 return true; // genesis block's modifier is 0
128 // First find current stake modifier and its generation block time
129 // if it's not old enough, return the same stake modifier
130 int64 nModifierTime = 0;
131 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
132 return error("ComputeNextStakeModifier: unable to get last modifier");
135 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
137 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
140 // Sort candidate blocks by timestamp
141 vector<pair<int64, uint256> > vSortedByTimestamp;
142 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
143 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
144 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
145 const CBlockIndex* pindex = pindexPrev;
146 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
148 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
149 pindex = pindex->pprev;
151 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
152 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
153 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
155 // Select 64 blocks from candidate blocks to generate stake modifier
156 uint64 nStakeModifierNew = 0;
157 int64 nSelectionIntervalStop = nSelectionIntervalStart;
158 map<uint256, const CBlockIndex*> mapSelectedBlocks;
159 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
161 // add an interval section to the current selection round
162 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
163 // select a block from the candidates of current round
164 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
165 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
166 // write the entropy bit of the selected block
167 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
168 // add the selected block from candidates to selected list
169 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
170 if (fDebug && GetBoolArg("-printstakemodifier"))
171 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
172 nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
175 // Print selection map for visualization of the selected blocks
176 if (fDebug && GetBoolArg("-printstakemodifier"))
178 string strSelectionMap = "";
179 // '-' indicates proof-of-work blocks not selected
180 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
182 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
184 // '=' indicates proof-of-stake blocks not selected
185 if (pindex->IsProofOfStake())
186 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
187 pindex = pindex->pprev;
189 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
191 // 'S' indicates selected proof-of-stake blocks
192 // 'W' indicates selected proof-of-work blocks
193 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
195 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
199 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
202 nStakeModifier = nStakeModifierNew;
203 fGeneratedStakeModifier = true;
207 // The stake modifier used to hash for a stake kernel is chosen as the stake
208 // modifier about a selection interval later than the coin generating the kernel
209 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
212 if (!mapBlockIndex.count(hashBlockFrom))
213 return error("GetKernelStakeModifier() : block not indexed");
214 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
215 nStakeModifierHeight = pindexFrom->nHeight;
216 nStakeModifierTime = pindexFrom->GetBlockTime();
217 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
218 const CBlockIndex* pindex = pindexFrom;
219 // loop to find the stake modifier later by a selection interval
220 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
223 { // reached best block; may happen if node is behind on block chain
224 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
225 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
226 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
230 pindex = pindex->pnext;
231 if (pindex->GeneratedStakeModifier())
233 nStakeModifierHeight = pindex->nHeight;
234 nStakeModifierTime = pindex->GetBlockTime();
237 nStakeModifier = pindex->nStakeModifier;
241 // ppcoin kernel protocol
242 // coinstake must meet hash target according to the protocol:
243 // kernel (input 0) must meet the formula
244 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
245 // this ensures that the chance of getting a coinstake is proportional to the
246 // amount of coin age one owns.
247 // The reason this hash is chosen is the following:
249 // (v0.3) scrambles computation to make it very difficult to precompute
250 // future proof-of-stake at the time of the coin's confirmation
251 // (v0.2) nBits (deprecated): encodes all past block timestamps
252 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
253 // generate transaction for future advantage
254 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
255 // nodes generating coinstake at the same time
256 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
258 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
259 // generating coinstake at the same time
260 // block/tx hash should not be used here as they can be generated in vast
261 // quantities so as to generate blocks faster, degrading the system back into
262 // a proof-of-work situation.
264 bool CheckStakeKernelHash(unsigned int nBits, const CBlock& blockFrom, unsigned int nTxPrevOffset, const CTransaction& txPrev, const COutPoint& prevout, unsigned int nTimeTx, uint256& hashProofOfStake, bool fPrintProofOfStake)
266 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
267 return error("CheckStakeKernelHash() : nTime violation");
269 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
270 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
271 return error("CheckStakeKernelHash() : min age violation");
273 CBigNum bnTargetPerCoinDay;
274 bnTargetPerCoinDay.SetCompact(nBits);
275 int64 nValueIn = txPrev.vout[prevout.n].nValue;
279 // Kernel hash weight starts from 0 at the 30-day min age
280 // this change increases active coins participating the hash and helps
281 // to secure the network when proof-of-stake difficulty is low
283 if(fTestNet || (STAKEWEIGHT_SWITCH_TIME < nTimeTx))
285 // New rule since 01 Jan 2014: Maximum TimeWeight is 90 days.
286 nTimeWeight = min((int64)nTimeTx - txPrev.nTime - nStakeMinAge, (int64)nStakeMaxAge);
290 // Current rule: Maximum TimeWeight is 60 days.
291 nTimeWeight = min((int64)nTimeTx - txPrev.nTime, (int64)nStakeMaxAge) - nStakeMinAge;
294 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * nTimeWeight / COIN / (24 * 60 * 60);
297 CDataStream ss(SER_GETHASH, 0);
298 uint64 nStakeModifier = 0;
299 int nStakeModifierHeight = 0;
300 int64 nStakeModifierTime = 0;
302 if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
304 ss << nStakeModifier;
306 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
307 hashProofOfStake = Hash(ss.begin(), ss.end());
308 if (fPrintProofOfStake)
310 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
311 nStakeModifier, nStakeModifierHeight,
312 DateTimeStrFormat(nStakeModifierTime).c_str(),
313 mapBlockIndex[blockFrom.GetHash()]->nHeight,
314 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
315 printf("CheckStakeKernelHash() : check protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
318 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
319 hashProofOfStake.ToString().c_str());
322 // Now check if proof-of-stake hash meets target protocol
323 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
325 if (fDebug && !fPrintProofOfStake)
327 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
328 nStakeModifier, nStakeModifierHeight,
329 DateTimeStrFormat(nStakeModifierTime).c_str(),
330 mapBlockIndex[blockFrom.GetHash()]->nHeight,
331 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
332 printf("CheckStakeKernelHash() : pass protocol=%s modifier=0x%016"PRI64x" nTimeBlockFrom=%u nTxPrevOffset=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
335 nTimeBlockFrom, nTxPrevOffset, txPrev.nTime, prevout.n, nTimeTx,
336 hashProofOfStake.ToString().c_str());
341 // Check kernel hash target and coinstake signature
342 bool CheckProofOfStake(const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake)
344 if (!tx.IsCoinStake())
345 return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
347 // Kernel (input 0) must match the stake hash target per coin age (nBits)
348 const CTxIn& txin = tx.vin[0];
350 // First try finding the previous transaction in database
354 if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
355 return tx.DoS(1, error("CheckProofOfStake() : INFO: read txPrev failed")); // previous transaction not in main chain, may occur during initial download
359 if (!VerifySignature(txPrev, tx, 0, true, 0))
360 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
364 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
365 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
367 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, fDebug))
368 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
373 // Check whether the coinstake timestamp meets protocol
374 bool CheckCoinStakeTimestamp(int64 nTimeBlock, int64 nTimeTx)
377 return (nTimeBlock == nTimeTx);
380 // Get stake modifier checksum
381 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
383 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
384 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
385 CDataStream ss(SER_GETHASH, 0);
387 ss << pindex->pprev->nStakeModifierChecksum;
388 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
389 uint256 hashChecksum = Hash(ss.begin(), ss.end());
390 hashChecksum >>= (256 - 32);
391 return hashChecksum.Get64();
394 // Check stake modifier hard checkpoints
395 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
397 if (fTestNet) return true; // Testnet has no checkpoints
398 if (mapStakeModifierCheckpoints.count(nHeight))
399 return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];