1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Copyright (c) 2011-2013 The PPCoin developers
3 // Copyright (c) 2013 NovaCoin Developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
8 #include <boost/foreach.hpp>
10 #include "checkpoints.h"
18 typedef std::map<int, uint256> MapCheckpoints; // hardened checkpoints
21 // What makes a good checkpoint block?
22 // + Is surrounded by blocks with reasonable timestamps
23 // (no blocks before with a timestamp after, none after with
25 // + Contains no strange transactions
27 static MapCheckpoints mapCheckpoints =
28 boost::assign::map_list_of
29 ( 0, hashGenesisBlockOfficial )
30 ( 6000, uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"))
33 bool CheckHardened(int nHeight, const uint256& hash)
35 if (fTestNet) return true; // Testnet has no checkpoints
37 MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
38 if (i == mapCheckpoints.end()) return true;
39 return hash == i->second;
42 int GetTotalBlocksEstimate()
44 if (fTestNet) return 0;
46 return mapCheckpoints.rbegin()->first;
49 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
52 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
53 if (t != mapBlockIndex.end())
58 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
60 const uint256& hash = i.second;
61 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
62 if (t != mapBlockIndex.end())
68 // ppcoin: synchronized checkpoint (centrally broadcasted)
69 uint256 hashSyncCheckpoint = 0;
70 uint256 hashPendingCheckpoint = 0;
71 CSyncCheckpoint checkpointMessage;
72 CSyncCheckpoint checkpointMessagePending;
73 uint256 hashInvalidCheckpoint = 0;
74 CCriticalSection cs_hashSyncCheckpoint;
76 // ppcoin: get last synchronized checkpoint
77 CBlockIndex* GetLastSyncCheckpoint()
79 LOCK(cs_hashSyncCheckpoint);
80 if (!mapBlockIndex.count(hashSyncCheckpoint))
81 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
83 return mapBlockIndex[hashSyncCheckpoint];
87 // ppcoin: only descendant of current sync-checkpoint is allowed
88 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
90 if (!mapBlockIndex.count(hashSyncCheckpoint))
91 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
92 if (!mapBlockIndex.count(hashCheckpoint))
93 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
95 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
96 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
98 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
100 // Received an older checkpoint, trace back from current checkpoint
101 // to the same height of the received checkpoint to verify
102 // that current checkpoint should be a descendant block
103 CBlockIndex* pindex = pindexSyncCheckpoint;
104 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
105 if (!(pindex = pindex->pprev))
106 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
107 if (pindex->GetBlockHash() != hashCheckpoint)
109 hashInvalidCheckpoint = hashCheckpoint;
110 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
112 return false; // ignore older checkpoint
115 // Received checkpoint should be a descendant block of the current
116 // checkpoint. Trace back to the same height of current checkpoint
118 CBlockIndex* pindex = pindexCheckpointRecv;
119 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
120 if (!(pindex = pindex->pprev))
121 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
122 if (pindex->GetBlockHash() != hashSyncCheckpoint)
124 hashInvalidCheckpoint = hashCheckpoint;
125 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
130 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
134 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
137 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
139 if (!txdb.TxnCommit())
140 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
143 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
147 bool AcceptPendingSyncCheckpoint()
149 LOCK(cs_hashSyncCheckpoint);
150 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
152 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
154 hashPendingCheckpoint = 0;
155 checkpointMessagePending.SetNull();
160 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
161 if (!pindexCheckpoint->IsInMainChain())
164 if (!block.ReadFromDisk(pindexCheckpoint))
165 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
166 if (!block.SetBestChain(txdb, pindexCheckpoint))
168 hashInvalidCheckpoint = hashPendingCheckpoint;
169 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
174 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
175 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
176 hashPendingCheckpoint = 0;
177 checkpointMessage = checkpointMessagePending;
178 checkpointMessagePending.SetNull();
179 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
180 // relay the checkpoint
181 if (!checkpointMessage.IsNull())
183 BOOST_FOREACH(CNode* pnode, vNodes)
184 checkpointMessage.RelayTo(pnode);
191 // Automatically select a suitable sync-checkpoint
192 uint256 AutoSelectSyncCheckpoint()
194 // Proof-of-work blocks are immediately checkpointed
195 // to defend against 51% attack which rejects other miners block
197 // Select the last proof-of-work block
198 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
199 // Search forward for a block within max span and maturity window
200 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
201 pindex = pindex->pnext;
202 return pindex->GetBlockHash();
205 // Check against synchronized checkpoint
206 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
208 if (fTestNet) return true; // Testnet has no checkpoints
209 int nHeight = pindexPrev->nHeight + 1;
211 LOCK(cs_hashSyncCheckpoint);
212 // sync-checkpoint should always be accepted block
213 assert(mapBlockIndex.count(hashSyncCheckpoint));
214 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
216 if (nHeight > pindexSync->nHeight)
218 // trace back to same height as sync-checkpoint
219 const CBlockIndex* pindex = pindexPrev;
220 while (pindex->nHeight > pindexSync->nHeight)
221 if (!(pindex = pindex->pprev))
222 return error("CheckSync: pprev null - block index structure failure");
223 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
224 return false; // only descendant of sync-checkpoint can pass check
226 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
227 return false; // same height with sync-checkpoint
228 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
229 return false; // lower height than sync-checkpoint
233 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
235 LOCK(cs_hashSyncCheckpoint);
236 if (hashPendingCheckpoint == 0)
238 if (hashBlock == hashPendingCheckpoint)
240 if (mapOrphanBlocks.count(hashPendingCheckpoint)
241 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
246 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
247 bool ResetSyncCheckpoint()
249 LOCK(cs_hashSyncCheckpoint);
250 const uint256& hash = mapCheckpoints.rbegin()->second;
251 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
253 // checkpoint block accepted but not yet in main chain
254 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
257 if (!block.ReadFromDisk(mapBlockIndex[hash]))
258 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
259 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
261 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
265 else if(!mapBlockIndex.count(hash))
267 // checkpoint block not yet accepted
268 hashPendingCheckpoint = hash;
269 checkpointMessagePending.SetNull();
270 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
273 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
275 const uint256& hash = i.second;
276 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
278 if (!WriteSyncCheckpoint(hash))
279 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
280 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
288 void AskForPendingSyncCheckpoint(CNode* pfrom)
290 LOCK(cs_hashSyncCheckpoint);
291 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
292 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
295 bool SetCheckpointPrivKey(std::string strPrivKey)
297 // Test signing a sync-checkpoint with genesis block
298 CSyncCheckpoint checkpoint;
299 checkpoint.hashCheckpoint = hashGenesisBlock;
300 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
301 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
302 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
304 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
306 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
307 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
310 // Test signing successful, proceed
311 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
315 bool SendSyncCheckpoint(uint256 hashCheckpoint)
317 CSyncCheckpoint checkpoint;
318 checkpoint.hashCheckpoint = hashCheckpoint;
319 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
320 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
321 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
323 if (CSyncCheckpoint::strMasterPrivKey.empty())
324 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
325 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
327 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
328 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
329 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
331 if(!checkpoint.ProcessSyncCheckpoint(NULL))
333 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
340 BOOST_FOREACH(CNode* pnode, vNodes)
341 checkpoint.RelayTo(pnode);
346 // Is the sync-checkpoint outside maturity window?
347 bool IsMatureSyncCheckpoint()
349 LOCK(cs_hashSyncCheckpoint);
350 // sync-checkpoint should always be accepted block
351 assert(mapBlockIndex.count(hashSyncCheckpoint));
352 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
353 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
354 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
357 // Is the sync-checkpoint too old?
358 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
360 LOCK(cs_hashSyncCheckpoint);
361 // sync-checkpoint should always be accepted block
362 assert(mapBlockIndex.count(hashSyncCheckpoint));
363 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
364 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
368 // ppcoin: sync-checkpoint master key
369 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
371 std::string CSyncCheckpoint::strMasterPrivKey = "";
373 // ppcoin: verify signature of sync-checkpoint message
374 bool CSyncCheckpoint::CheckSignature()
377 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
378 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
379 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
380 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
382 // Now unserialize the data
383 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
384 sMsg >> *(CUnsignedSyncCheckpoint*)this;
388 // ppcoin: process synchronized checkpoint
389 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
391 if (!CheckSignature())
394 LOCK(Checkpoints::cs_hashSyncCheckpoint);
395 if (!mapBlockIndex.count(hashCheckpoint))
397 // We haven't received the checkpoint chain, keep the checkpoint as pending
398 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
399 Checkpoints::checkpointMessagePending = *this;
400 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
401 // Ask this guy to fill in what we're missing
404 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
405 // ask directly as well in case rejected earlier by duplicate
406 // proof-of-stake because getblocks may not get it this time
407 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
412 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
416 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
417 if (!pindexCheckpoint->IsInMainChain())
419 // checkpoint chain received but not yet main chain
421 if (!block.ReadFromDisk(pindexCheckpoint))
422 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
423 if (!block.SetBestChain(txdb, pindexCheckpoint))
425 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
426 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
431 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
432 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
433 Checkpoints::checkpointMessage = *this;
434 Checkpoints::hashPendingCheckpoint = 0;
435 Checkpoints::checkpointMessagePending.SetNull();
436 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());