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 )
26 ( 68600, 0x73a8cc4cu )
27 ( 92161, 0xe21a911au )
28 ( 98661, 0xd20c44d4u )
31 // Hard checkpoints of stake modifiers to ensure they are deterministic (testNet)
32 static std::map<int, unsigned int> mapStakeModifierCheckpointsTestNet =
33 boost::assign::map_list_of
38 int64 GetWeight(int64 nIntervalBeginning, int64 nIntervalEnd)
40 // Kernel hash weight starts from 0 at the 30-day min age
41 // this change increases active coins participating the hash and helps
42 // to secure the network when proof-of-stake difficulty is low
44 // Maximum TimeWeight is 90 days.
46 return min(nIntervalEnd - nIntervalBeginning - nStakeMinAge, (int64)nStakeMaxAge);
49 // Get the last stake modifier and its generation time from a given block
50 static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64& nStakeModifier, int64& nModifierTime)
53 return error("GetLastStakeModifier: null pindex");
54 while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
55 pindex = pindex->pprev;
56 if (!pindex->GeneratedStakeModifier())
57 return error("GetLastStakeModifier: no generation at genesis block");
58 nStakeModifier = pindex->nStakeModifier;
59 nModifierTime = pindex->GetBlockTime();
63 // Get selection interval section (in seconds)
64 static int64 GetStakeModifierSelectionIntervalSection(int nSection)
66 assert (nSection >= 0 && nSection < 64);
67 return (nModifierInterval * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1))));
70 // Get stake modifier selection interval (in seconds)
71 static int64 GetStakeModifierSelectionInterval()
73 int64 nSelectionInterval = 0;
74 for (int nSection=0; nSection<64; nSection++)
75 nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
76 return nSelectionInterval;
79 // select a block from the candidate blocks in vSortedByTimestamp, excluding
80 // already selected blocks in vSelectedBlocks, and with timestamp up to
81 // nSelectionIntervalStop.
82 static bool SelectBlockFromCandidates(vector<pair<int64, uint256> >& vSortedByTimestamp, map<uint256, const CBlockIndex*>& mapSelectedBlocks,
83 int64 nSelectionIntervalStop, uint64 nStakeModifierPrev, const CBlockIndex** pindexSelected)
85 bool fSelected = false;
87 *pindexSelected = (const CBlockIndex*) 0;
88 BOOST_FOREACH(const PAIRTYPE(int64, uint256)& item, vSortedByTimestamp)
90 if (!mapBlockIndex.count(item.second))
91 return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
92 const CBlockIndex* pindex = mapBlockIndex[item.second];
93 if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
95 if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
97 // compute the selection hash by hashing its proof-hash and the
98 // previous proof-of-stake modifier
99 uint256 hashProof = pindex->IsProofOfStake()? pindex->hashProofOfStake : pindex->GetBlockHash();
100 CDataStream ss(SER_GETHASH, 0);
101 ss << hashProof << nStakeModifierPrev;
102 uint256 hashSelection = Hash(ss.begin(), ss.end());
103 // the selection hash is divided by 2**32 so that proof-of-stake block
104 // is always favored over proof-of-work block. this is to preserve
105 // the energy efficiency property
106 if (pindex->IsProofOfStake())
107 hashSelection >>= 32;
108 if (fSelected && hashSelection < hashBest)
110 hashBest = hashSelection;
111 *pindexSelected = (const CBlockIndex*) pindex;
116 hashBest = hashSelection;
117 *pindexSelected = (const CBlockIndex*) pindex;
120 if (fDebug && GetBoolArg("-printstakemodifier"))
121 printf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
125 // Stake Modifier (hash modifier of proof-of-stake):
126 // The purpose of stake modifier is to prevent a txout (coin) owner from
127 // computing future proof-of-stake generated by this txout at the time
128 // of transaction confirmation. To meet kernel protocol, the txout
129 // must hash with a future stake modifier to generate the proof.
130 // Stake modifier consists of bits each of which is contributed from a
131 // selected block of a given block group in the past.
132 // The selection of a block is based on a hash of the block's proof-hash and
133 // the previous stake modifier.
134 // Stake modifier is recomputed at a fixed time interval instead of every
135 // block. This is to make it difficult for an attacker to gain control of
136 // additional bits in the stake modifier, even after generating a chain of
138 bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64& nStakeModifier, bool& fGeneratedStakeModifier)
141 fGeneratedStakeModifier = false;
144 fGeneratedStakeModifier = true;
145 return true; // genesis block's modifier is 0
147 // First find current stake modifier and its generation block time
148 // if it's not old enough, return the same stake modifier
149 int64 nModifierTime = 0;
150 if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
151 return error("ComputeNextStakeModifier: unable to get last modifier");
154 printf("ComputeNextStakeModifier: prev modifier=0x%016"PRI64x" time=%s\n", nStakeModifier, DateTimeStrFormat(nModifierTime).c_str());
156 if (nModifierTime / nModifierInterval >= pindexPrev->GetBlockTime() / nModifierInterval)
159 // Sort candidate blocks by timestamp
160 vector<pair<int64, uint256> > vSortedByTimestamp;
161 vSortedByTimestamp.reserve(64 * nModifierInterval / nStakeTargetSpacing);
162 int64 nSelectionInterval = GetStakeModifierSelectionInterval();
163 int64 nSelectionIntervalStart = (pindexPrev->GetBlockTime() / nModifierInterval) * nModifierInterval - nSelectionInterval;
164 const CBlockIndex* pindex = pindexPrev;
165 while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart)
167 vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
168 pindex = pindex->pprev;
170 int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
171 reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
172 sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
174 // Select 64 blocks from candidate blocks to generate stake modifier
175 uint64 nStakeModifierNew = 0;
176 int64 nSelectionIntervalStop = nSelectionIntervalStart;
177 map<uint256, const CBlockIndex*> mapSelectedBlocks;
178 for (int nRound=0; nRound<min(64, (int)vSortedByTimestamp.size()); nRound++)
180 // add an interval section to the current selection round
181 nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
182 // select a block from the candidates of current round
183 if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
184 return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
185 // write the entropy bit of the selected block
186 nStakeModifierNew |= (((uint64)pindex->GetStakeEntropyBit()) << nRound);
187 // add the selected block from candidates to selected list
188 mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
189 if (fDebug && GetBoolArg("-printstakemodifier"))
190 printf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n", nRound, DateTimeStrFormat(nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
193 // Print selection map for visualization of the selected blocks
194 if (fDebug && GetBoolArg("-printstakemodifier"))
196 string strSelectionMap = "";
197 // '-' indicates proof-of-work blocks not selected
198 strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
200 while (pindex && pindex->nHeight >= nHeightFirstCandidate)
202 // '=' indicates proof-of-stake blocks not selected
203 if (pindex->IsProofOfStake())
204 strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
205 pindex = pindex->pprev;
207 BOOST_FOREACH(const PAIRTYPE(uint256, const CBlockIndex*)& item, mapSelectedBlocks)
209 // 'S' indicates selected proof-of-stake blocks
210 // 'W' indicates selected proof-of-work blocks
211 strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake()? "S" : "W");
213 printf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
217 printf("ComputeNextStakeModifier: new modifier=0x%016"PRI64x" time=%s\n", nStakeModifierNew, DateTimeStrFormat(pindexPrev->GetBlockTime()).c_str());
220 nStakeModifier = nStakeModifierNew;
221 fGeneratedStakeModifier = true;
225 // The stake modifier used to hash for a stake kernel is chosen as the stake
226 // modifier about a selection interval later than the coin generating the kernel
227 static bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64& nStakeModifier, int& nStakeModifierHeight, int64& nStakeModifierTime, bool fPrintProofOfStake)
230 if (!mapBlockIndex.count(hashBlockFrom))
231 return error("GetKernelStakeModifier() : block not indexed");
232 const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
233 nStakeModifierHeight = pindexFrom->nHeight;
234 nStakeModifierTime = pindexFrom->GetBlockTime();
235 int64 nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
236 const CBlockIndex* pindex = pindexFrom;
237 // loop to find the stake modifier later by a selection interval
238 while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval)
241 { // reached best block; may happen if node is behind on block chain
242 if (fPrintProofOfStake || (pindex->GetBlockTime() + nStakeMinAge - nStakeModifierSelectionInterval > GetAdjustedTime()))
243 return error("GetKernelStakeModifier() : reached best block %s at height %d from block %s",
244 pindex->GetBlockHash().ToString().c_str(), pindex->nHeight, hashBlockFrom.ToString().c_str());
248 pindex = pindex->pnext;
249 if (pindex->GeneratedStakeModifier())
251 nStakeModifierHeight = pindex->nHeight;
252 nStakeModifierTime = pindex->GetBlockTime();
255 nStakeModifier = pindex->nStakeModifier;
259 // ppcoin kernel protocol
260 // coinstake must meet hash target according to the protocol:
261 // kernel (input 0) must meet the formula
262 // hash(nStakeModifier + txPrev.block.nTime + txPrev.offset + txPrev.nTime + txPrev.vout.n + nTime) < bnTarget * nCoinDayWeight
263 // this ensures that the chance of getting a coinstake is proportional to the
264 // amount of coin age one owns.
265 // The reason this hash is chosen is the following:
266 // nStakeModifier: scrambles computation to make it very difficult to precompute
267 // future proof-of-stake at the time of the coin's confirmation
268 // txPrev.block.nTime: prevent nodes from guessing a good timestamp to
269 // generate transaction for future advantage
270 // txPrev.offset: offset of txPrev inside block, to reduce the chance of
271 // nodes generating coinstake at the same time
272 // txPrev.nTime: reduce the chance of nodes generating coinstake at the same
274 // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
275 // generating coinstake at the same time
276 // block/tx hash should not be used here as they can be generated in vast
277 // quantities so as to generate blocks faster, degrading the system back into
278 // a proof-of-work situation.
280 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)
282 if (nTimeTx < txPrev.nTime) // Transaction timestamp violation
283 return error("CheckStakeKernelHash() : nTime violation");
285 unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
286 if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
287 return error("CheckStakeKernelHash() : min age violation");
289 CBigNum bnTargetPerCoinDay;
290 bnTargetPerCoinDay.SetCompact(nBits);
291 int64 nValueIn = txPrev.vout[prevout.n].nValue;
293 uint256 hashBlockFrom = blockFrom.GetHash();
295 CBigNum bnCoinDayWeight = CBigNum(nValueIn) * GetWeight((int64)txPrev.nTime, (int64)nTimeTx) / COIN / (24 * 60 * 60);
296 targetProofOfStake = (bnCoinDayWeight * bnTargetPerCoinDay).getuint256();
299 CDataStream ss(SER_GETHASH, 0);
300 uint64 nStakeModifier = 0;
301 int nStakeModifierHeight = 0;
302 int64 nStakeModifierTime = 0;
304 if (!GetKernelStakeModifier(hashBlockFrom, nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake))
306 ss << nStakeModifier;
308 ss << nTimeBlockFrom << nTxPrevOffset << txPrev.nTime << prevout.n << nTimeTx;
309 hashProofOfStake = Hash(ss.begin(), ss.end());
310 if (fPrintProofOfStake)
312 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
313 nStakeModifier, nStakeModifierHeight,
314 DateTimeStrFormat(nStakeModifierTime).c_str(),
315 mapBlockIndex[hashBlockFrom]->nHeight,
316 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
317 printf("CheckStakeKernelHash() : check 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());
323 // Now check if proof-of-stake hash meets target protocol
324 if (CBigNum(hashProofOfStake) > bnCoinDayWeight * bnTargetPerCoinDay)
326 if (fDebug && !fPrintProofOfStake)
328 printf("CheckStakeKernelHash() : using modifier 0x%016"PRI64x" at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
329 nStakeModifier, nStakeModifierHeight,
330 DateTimeStrFormat(nStakeModifierTime).c_str(),
331 mapBlockIndex[hashBlockFrom]->nHeight,
332 DateTimeStrFormat(blockFrom.GetBlockTime()).c_str());
333 printf("CheckStakeKernelHash() : pass 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, uint256& targetProofOfStake)
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
358 if (!VerifySignature(txPrev, tx, 0, true, 0))
359 return tx.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str()));
363 if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
364 return fDebug? error("CheckProofOfStake() : read block failed") : false; // unable to read block of previous transaction
366 if (!CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, txPrev, txin.prevout, tx.nTime, hashProofOfStake, targetProofOfStake, fDebug))
367 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
372 // Get stake modifier checksum
373 unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
375 assert (pindex->pprev || pindex->GetBlockHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
376 // Hash previous checksum with flags, hashProofOfStake and nStakeModifier
377 CDataStream ss(SER_GETHASH, 0);
379 ss << pindex->pprev->nStakeModifierChecksum;
380 ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
381 uint256 hashChecksum = Hash(ss.begin(), ss.end());
382 hashChecksum >>= (256 - 32);
383 return hashChecksum.Get64();
386 // Check stake modifier hard checkpoints
387 bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
389 MapModifierCheckpoints& checkpoints = (fTestNet ? mapStakeModifierCheckpointsTestNet : mapStakeModifierCheckpoints);
391 if (checkpoints.count(nHeight))
392 return nStakeModifierChecksum == checkpoints[nHeight];