1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include "checkpoints.h"
17 typedef map<int, pair<uint256, unsigned int> > MapCheckpoints;
18 typedef list<uint256> ListBannedBlocks;
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 =
29 { 0, { hashGenesisBlock, 1360105017 } },
30 { 13560, { uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052 } },
31 { 143990, { uint256("0x00000000001ff5c3940a9f73ad4a990f64955179bde0f743c76dbf0031429efc"), 1418953493 } },
32 { 149000, { uint256("0x7a24acfcadcf43054e7f7d9f273522c0dfc5791ba4006e0273e7521a8d36c525"), 1420872125 } },
33 { 160000, { uint256("0x000000000001cb1133043d38d077c0e93f66c8b2566779f10f182137d1e34a68"), 1425150237 } },
34 { 200000, { uint256("0x0000000000029f8bbf66e6ea6f3e5db55009404aae0fe395a53dd33142b2bff2"), 1441127233 } },
35 { 221047, { uint256("0xa28aef712e7aa0c285bfe29351ca21ed416689139e3063ef770fc826a8b9e9da"), 1449431646 } },
36 { 243100, { uint256("0x000000000006522d1ebc0734cb0e6b83f5d4da0c3cbc72bd91b82016f611c4f0"), 1458215793 } },
39 static ListBannedBlocks listBanned =
41 // Invalid block #221047 with future timestamp of 2016/02/23 09:24:17 UTC
42 uint256("0x46223e5432ceffe650d5729b4bb8479dcdf0ca1e534fa8e69382dc87b42ea94b")
45 // TestNet has no checkpoints
46 static MapCheckpoints mapCheckpointsTestnet =
48 { 0, { hashGenesisBlockTestNet, 1360105017 } }
51 bool CheckHardened(int nHeight, const uint256& hash)
53 auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
55 auto i = checkpoints.find(nHeight);
56 if (i == checkpoints.end()) return true;
57 return hash == i->second.first;
60 bool CheckBanned(const uint256 &nHash)
62 if (fTestNet) // Testnet has no banned blocks
64 auto it = find(listBanned.begin(), listBanned.end(), nHash);
65 return it == listBanned.end();
68 int GetTotalBlocksEstimate()
70 auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
72 return checkpoints.rbegin()->first;
75 unsigned int GetLastCheckpointTime()
77 auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
79 return checkpoints.rbegin()->second.second;
82 CBlockIndex* GetLastCheckpoint(const map<uint256, CBlockIndex*>& mapBlockIndex)
84 auto& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
86 for(auto it = checkpoints.rbegin(); it != checkpoints.rend(); ++it)
88 auto& hash = it->second.first;
89 auto t = mapBlockIndex.find(hash);
90 if (t != mapBlockIndex.end())
96 // ppcoin: synchronized checkpoint (centrally broadcasted)
97 uint256 hashSyncCheckpoint = 0;
98 uint256 hashPendingCheckpoint = 0;
99 CSyncCheckpoint checkpointMessage;
100 CSyncCheckpoint checkpointMessagePending;
101 uint256 hashInvalidCheckpoint = 0;
102 CCriticalSection cs_hashSyncCheckpoint;
104 // ppcoin: get last synchronized checkpoint
105 CBlockIndex* GetLastSyncCheckpoint()
107 LOCK(cs_hashSyncCheckpoint);
108 if (!mapBlockIndex.count(hashSyncCheckpoint))
109 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
111 return mapBlockIndex[hashSyncCheckpoint];
115 // ppcoin: only descendant of current sync-checkpoint is allowed
116 bool ValidateSyncCheckpoint(const uint256 &hashCheckpoint)
118 if (!mapBlockIndex.count(hashSyncCheckpoint))
119 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
120 if (!mapBlockIndex.count(hashCheckpoint))
121 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
123 auto pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
124 auto pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
126 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
128 // Received an older checkpoint, trace back from current checkpoint
129 // to the same height of the received checkpoint to verify
130 // that current checkpoint should be a descendant block
131 auto pindex = pindexSyncCheckpoint;
132 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
133 if ((pindex = pindex->pprev) == NULL)
134 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
135 if (pindex->GetBlockHash() != hashCheckpoint)
137 hashInvalidCheckpoint = hashCheckpoint;
138 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
140 return false; // ignore older checkpoint
143 // Received checkpoint should be a descendant block of the current
144 // checkpoint. Trace back to the same height of current checkpoint
146 auto pindex = pindexCheckpointRecv;
147 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
148 if ((pindex = pindex->pprev) == NULL)
149 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
150 if (pindex->GetBlockHash() != hashSyncCheckpoint)
152 hashInvalidCheckpoint = hashCheckpoint;
153 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
158 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
162 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
165 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
167 if (!txdb.TxnCommit())
168 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
174 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
178 bool AcceptPendingSyncCheckpoint()
180 LOCK(cs_hashSyncCheckpoint);
181 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
183 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
185 hashPendingCheckpoint = 0;
186 checkpointMessagePending.SetNull();
191 auto pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
192 if (!pindexCheckpoint->IsInMainChain())
195 if (!block.ReadFromDisk(pindexCheckpoint))
196 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
197 if (!block.SetBestChain(txdb, pindexCheckpoint))
199 hashInvalidCheckpoint = hashPendingCheckpoint;
200 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
207 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
208 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
209 hashPendingCheckpoint = 0;
210 checkpointMessage = checkpointMessagePending;
211 checkpointMessagePending.SetNull();
212 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
213 // relay the checkpoint
214 if (!checkpointMessage.IsNull())
216 for (auto it = vNodes.begin(); it != vNodes.end(); ++it)
217 checkpointMessage.RelayTo(*it);
224 // Automatically select a suitable sync-checkpoint
225 uint256 AutoSelectSyncCheckpoint()
227 auto pindex = pindexBest;
228 // Search backward for a block within max span and maturity window
229 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
230 pindex = pindex->pprev;
231 return pindex->GetBlockHash();
234 // Check against synchronized checkpoint
235 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
237 if (fTestNet) return true; // Testnet has no checkpoints
238 int nHeight = pindexPrev->nHeight + 1;
240 LOCK(cs_hashSyncCheckpoint);
241 // sync-checkpoint should always be accepted block
242 assert(mapBlockIndex.count(hashSyncCheckpoint));
243 auto pindexSync = mapBlockIndex[hashSyncCheckpoint];
245 if (nHeight > pindexSync->nHeight)
247 // trace back to same height as sync-checkpoint
248 auto pindex = pindexPrev;
249 while (pindex->nHeight > pindexSync->nHeight)
250 if ((pindex = pindex->pprev) == NULL)
251 return error("CheckSync: pprev null - block index structure failure");
252 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
253 return false; // only descendant of sync-checkpoint can pass check
255 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
256 return false; // same height with sync-checkpoint
257 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
258 return false; // lower height than sync-checkpoint
262 bool WantedByPendingSyncCheckpoint(const uint256 &hashBlock)
264 LOCK(cs_hashSyncCheckpoint);
265 if (hashPendingCheckpoint == 0)
267 if (hashBlock == hashPendingCheckpoint)
269 if (mapOrphanBlocks.count(hashPendingCheckpoint)
270 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
275 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
276 bool ResetSyncCheckpoint()
278 LOCK(cs_hashSyncCheckpoint);
279 const auto& hash = mapCheckpoints.rbegin()->second.first;
280 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
282 // checkpoint block accepted but not yet in main chain
283 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
286 if (!block.ReadFromDisk(mapBlockIndex[hash]))
287 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
288 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
290 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
298 else if(!mapBlockIndex.count(hash))
300 // checkpoint block not yet accepted
301 hashPendingCheckpoint = hash;
302 checkpointMessagePending.SetNull();
303 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
306 for(auto it = mapCheckpoints.rbegin(); it != mapCheckpoints.rend(); ++it)
308 const auto& hash = it->second.first;
309 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
311 if (!WriteSyncCheckpoint(hash))
312 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
313 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
321 void AskForPendingSyncCheckpoint(CNode* pfrom)
323 LOCK(cs_hashSyncCheckpoint);
324 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
325 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
328 bool SetCheckpointPrivKey(const string &strPrivKey)
330 // Test signing a sync-checkpoint with genesis block
331 CSyncCheckpoint checkpoint;
332 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
333 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
334 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
335 checkpoint.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
337 auto vchPrivKey = ParseHex(strPrivKey);
339 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
340 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
343 // Test signing successful, proceed
344 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
348 bool SendSyncCheckpoint(const uint256 &hashCheckpoint)
350 CSyncCheckpoint checkpoint;
351 checkpoint.hashCheckpoint = hashCheckpoint;
352 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
353 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
354 checkpoint.vchMsg = vector<unsigned char>(sMsg.begin(), sMsg.end());
356 if (CSyncCheckpoint::strMasterPrivKey.empty())
357 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
358 auto vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
360 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
361 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
362 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
364 if(!checkpoint.ProcessSyncCheckpoint(NULL))
366 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
373 for(auto pnode : vNodes)
374 checkpoint.RelayTo(pnode);
379 // Is the sync-checkpoint outside maturity window?
380 bool IsMatureSyncCheckpoint()
382 LOCK(cs_hashSyncCheckpoint);
383 // sync-checkpoint should always be accepted block
384 assert(mapBlockIndex.count(hashSyncCheckpoint));
385 const auto pindexSync = mapBlockIndex[hashSyncCheckpoint];
386 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
387 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
391 void CUnsignedSyncCheckpoint::SetNull()
397 std::string CUnsignedSyncCheckpoint::ToString() const
401 " nVersion = %" PRId32 "\n"
402 " hashCheckpoint = %s\n"
405 hashCheckpoint.ToString().c_str());
408 // ppcoin: sync-checkpoint master key
409 const string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
411 string CSyncCheckpoint::strMasterPrivKey = "";
413 CSyncCheckpoint::CSyncCheckpoint()
418 void CSyncCheckpoint::SetNull()
420 CUnsignedSyncCheckpoint::SetNull();
425 bool CSyncCheckpoint::IsNull() const
427 return (hashCheckpoint == 0);
430 uint256 CSyncCheckpoint::GetHash() const
432 return SerializeHash(*this);
435 bool CSyncCheckpoint::RelayTo(CNode* pnode) const
437 // returns true if wasn't already sent
438 if (pnode->hashCheckpointKnown != hashCheckpoint)
440 pnode->hashCheckpointKnown = hashCheckpoint;
441 pnode->PushMessage("checkpoint", *this);
447 // ppcoin: verify signature of sync-checkpoint message
448 bool CSyncCheckpoint::CheckSignature()
450 CPubKey key(ParseHex(CSyncCheckpoint::strMasterPubKey));
451 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
452 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
454 // Now unserialize the data
455 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
456 sMsg >> *(CUnsignedSyncCheckpoint*)this;
460 // process synchronized checkpoint
461 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
463 if (!CheckSignature())
466 LOCK(Checkpoints::cs_hashSyncCheckpoint);
467 if (!mapBlockIndex.count(hashCheckpoint))
469 // We haven't received the checkpoint chain, keep the checkpoint as pending
470 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
471 Checkpoints::checkpointMessagePending = *this;
472 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
473 // Ask this guy to fill in what we're missing
476 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
477 // ask directly as well in case rejected earlier by duplicate
478 // proof-of-stake because getblocks may not get it this time
479 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
484 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
488 auto pindexCheckpoint = mapBlockIndex[hashCheckpoint];
489 if (!pindexCheckpoint->IsInMainChain())
491 // checkpoint chain received but not yet main chain
493 if (!block.ReadFromDisk(pindexCheckpoint))
494 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
495 if (!block.SetBestChain(txdb, pindexCheckpoint))
497 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
498 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
506 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
507 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
508 Checkpoints::checkpointMessage = *this;
509 Checkpoints::hashPendingCheckpoint = 0;
510 Checkpoints::checkpointMessagePending.SetNull();
511 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());