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.
5 #include "checkpoints.h"
7 #include "txdb-leveldb.h"
12 typedef std::map<int, std::pair<uint256, unsigned int> > MapCheckpoints;
13 typedef std::list<uint256> ListBannedBlocks;
16 // What makes a good checkpoint block?
17 // + Is surrounded by blocks with reasonable timestamps
18 // (no blocks before with a timestamp after, none after with
20 // + Contains no strange transactions
22 static MapCheckpoints mapCheckpoints =
24 { 0, {hashGenesisBlock, 1360105017} },
25 { 13560, {uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052} },
26 { 143990, {uint256("0x00000000001ff5c3940a9f73ad4a990f64955179bde0f743c76dbf0031429efc"), 1418953493} },
27 { 149000, {uint256("0x7a24acfcadcf43054e7f7d9f273522c0dfc5791ba4006e0273e7521a8d36c525"), 1420872125} },
28 { 160000, {uint256("0x000000000001cb1133043d38d077c0e93f66c8b2566779f10f182137d1e34a68"), 1425150237} },
29 { 200000, {uint256("0x0000000000029f8bbf66e6ea6f3e5db55009404aae0fe395a53dd33142b2bff2"), 1441127233} },
30 { 221047, {uint256("0xa28aef712e7aa0c285bfe29351ca21ed416689139e3063ef770fc826a8b9e9da"), 1449431646} },
31 { 243100, {uint256("0x000000000006522d1ebc0734cb0e6b83f5d4da0c3cbc72bd91b82016f611c4f0"), 1458215793} },
32 { 532000, {uint256("0x0000000000018b7eba5e189c41605780c8a855f74144fa837fa05fa4c67b6ba9"), 1569359486} },
33 { 561108, {uint256("0x2f3cf523ae1022300b4f40073e506d15ef0d6e208f123aed5b93016f81a10e1e"), 1580943827} },
34 { 712891, {uint256("0xaaafebcb23c1b8ab49f7517b7a34bcc420cc6f284d9ffc672c1f47b5af2b0088"), 1640557462} }
37 static ListBannedBlocks listBanned =
39 // Invalid block #221047 with future timestamp of 2016/02/23 09:24:17 UTC
40 uint256("0x46223e5432ceffe650d5729b4bb8479dcdf0ca1e534fa8e69382dc87b42ea94b")
43 // TestNet has no checkpoints
44 static MapCheckpoints mapCheckpointsTestnet =
46 { 0, { hashGenesisBlockTestNet, 1360105017 } }
49 bool CheckHardened(int nHeight, const uint256& hash)
51 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
53 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
54 if (i == checkpoints.end()) return true;
55 return hash == i->second.first;
58 bool CheckBanned(const uint256 &nHash)
60 if (fTestNet) // Testnet has no banned blocks
62 ListBannedBlocks::const_iterator it = std::find(listBanned.begin(), listBanned.end(), nHash);
63 return it == listBanned.end();
66 int GetTotalBlocksEstimate()
68 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
70 return checkpoints.rbegin()->first;
73 unsigned int GetLastCheckpointTime()
75 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
77 return checkpoints.rbegin()->second.second;
80 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
82 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
84 for(auto it = checkpoints.rbegin(); it != checkpoints.rend(); ++it)
86 const uint256& hash = it->second.first;
87 auto t = mapBlockIndex.find(hash);
88 if (t != mapBlockIndex.end())
94 // ppcoin: synchronized checkpoint (centrally broadcasted)
95 uint256 hashSyncCheckpoint = 0;
96 uint256 hashPendingCheckpoint = 0;
97 CSyncCheckpoint checkpointMessage;
98 CSyncCheckpoint checkpointMessagePending;
99 uint256 hashInvalidCheckpoint = 0;
100 CCriticalSection cs_hashSyncCheckpoint;
102 // ppcoin: get last synchronized checkpoint
103 CBlockIndex* GetLastSyncCheckpoint()
105 LOCK(cs_hashSyncCheckpoint);
106 if (!mapBlockIndex.count(hashSyncCheckpoint))
107 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
109 return mapBlockIndex[hashSyncCheckpoint];
113 // ppcoin: only descendant of current sync-checkpoint is allowed
114 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
116 if (!mapBlockIndex.count(hashSyncCheckpoint))
117 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
118 if (!mapBlockIndex.count(hashCheckpoint))
119 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
121 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
122 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
124 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
126 // Received an older checkpoint, trace back from current checkpoint
127 // to the same height of the received checkpoint to verify
128 // that current checkpoint should be a descendant block
129 CBlockIndex* pindex = pindexSyncCheckpoint;
130 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
131 if ((pindex = pindex->pprev) == NULL)
132 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
133 if (pindex->GetBlockHash() != hashCheckpoint)
135 hashInvalidCheckpoint = hashCheckpoint;
136 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
138 return false; // ignore older checkpoint
141 // Received checkpoint should be a descendant block of the current
142 // checkpoint. Trace back to the same height of current checkpoint
144 CBlockIndex* pindex = pindexCheckpointRecv;
145 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
146 if ((pindex = pindex->pprev) == NULL)
147 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
148 if (pindex->GetBlockHash() != hashSyncCheckpoint)
150 hashInvalidCheckpoint = hashCheckpoint;
151 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
156 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
160 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
163 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
165 if (!txdb.TxnCommit())
166 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
168 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
172 bool AcceptPendingSyncCheckpoint()
174 LOCK(cs_hashSyncCheckpoint);
175 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
177 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
179 hashPendingCheckpoint = 0;
180 checkpointMessagePending.SetNull();
185 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
186 if (!pindexCheckpoint->IsInMainChain())
189 if (!block.ReadFromDisk(pindexCheckpoint))
190 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
191 if (!block.SetBestChain(txdb, pindexCheckpoint))
193 hashInvalidCheckpoint = hashPendingCheckpoint;
194 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
198 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
199 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
200 hashPendingCheckpoint = 0;
201 checkpointMessage = checkpointMessagePending;
202 checkpointMessagePending.SetNull();
203 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
204 // relay the checkpoint
205 if (!checkpointMessage.IsNull())
207 for (std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it)
208 checkpointMessage.RelayTo(*it);
215 // Automatically select a suitable sync-checkpoint
216 uint256 AutoSelectSyncCheckpoint()
218 const CBlockIndex *pindex = pindexBest;
219 // Search backward for a block within max span and maturity window
220 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
221 pindex = pindex->pprev;
222 return pindex->GetBlockHash();
225 // Check against synchronized checkpoint
226 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
228 if (fTestNet) return true; // Testnet has no checkpoints
229 int nHeight = pindexPrev->nHeight + 1;
231 LOCK(cs_hashSyncCheckpoint);
232 // sync-checkpoint should always be accepted block
233 assert(mapBlockIndex.count(hashSyncCheckpoint));
234 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
236 if (nHeight > pindexSync->nHeight)
238 // trace back to same height as sync-checkpoint
239 const CBlockIndex* pindex = pindexPrev;
240 while (pindex->nHeight > pindexSync->nHeight)
241 if ((pindex = pindex->pprev) == NULL)
242 return error("CheckSync: pprev null - block index structure failure");
243 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
244 return false; // only descendant of sync-checkpoint can pass check
246 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
247 return false; // same height with sync-checkpoint
248 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
249 return false; // lower height than sync-checkpoint
253 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
255 LOCK(cs_hashSyncCheckpoint);
256 if (hashPendingCheckpoint == 0)
258 if (hashBlock == hashPendingCheckpoint)
260 if (mapOrphanBlocks.count(hashPendingCheckpoint)
261 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
266 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
267 bool ResetSyncCheckpoint()
269 LOCK(cs_hashSyncCheckpoint);
270 const uint256& hash = mapCheckpoints.rbegin()->second.first;
271 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
273 // checkpoint block accepted but not yet in main chain
274 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
277 if (!block.ReadFromDisk(mapBlockIndex[hash]))
278 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
279 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
281 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
284 else if(!mapBlockIndex.count(hash))
286 // checkpoint block not yet accepted
287 hashPendingCheckpoint = hash;
288 checkpointMessagePending.SetNull();
289 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
292 for(auto it = mapCheckpoints.rbegin(); it != mapCheckpoints.rend(); ++it)
294 const uint256& hash = it->second.first;
295 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
297 if (!WriteSyncCheckpoint(hash))
298 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
299 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
307 void AskForPendingSyncCheckpoint(CNode* pfrom)
309 LOCK(cs_hashSyncCheckpoint);
310 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
311 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
314 bool SetCheckpointPrivKey(std::string strPrivKey)
316 // Test signing a sync-checkpoint with genesis block
317 CSyncCheckpoint checkpoint;
318 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
319 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
320 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
321 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
323 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
325 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
326 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
329 // Test signing successful, proceed
330 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
334 bool SendSyncCheckpoint(uint256 hashCheckpoint)
336 CSyncCheckpoint checkpoint;
337 checkpoint.hashCheckpoint = hashCheckpoint;
338 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
339 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
340 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
342 if (CSyncCheckpoint::strMasterPrivKey.empty())
343 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
344 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
346 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
347 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
348 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
350 if(!checkpoint.ProcessSyncCheckpoint(NULL))
352 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
359 for (std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it)
360 checkpoint.RelayTo(*it);
365 // Is the sync-checkpoint outside maturity window?
366 bool IsMatureSyncCheckpoint()
368 LOCK(cs_hashSyncCheckpoint);
369 // sync-checkpoint should always be accepted block
370 assert(mapBlockIndex.count(hashSyncCheckpoint));
371 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
372 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
373 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
377 // ppcoin: sync-checkpoint master key
378 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
380 std::string CSyncCheckpoint::strMasterPrivKey = "";
382 // ppcoin: verify signature of sync-checkpoint message
383 CSyncCheckpoint::CSyncCheckpoint()
388 void CSyncCheckpoint::SetNull()
390 CUnsignedSyncCheckpoint::SetNull();
395 bool CSyncCheckpoint::IsNull() const
397 return (hashCheckpoint == 0);
400 uint256 CSyncCheckpoint::GetHash() const
402 return SerializeHash(*this);
405 bool CSyncCheckpoint::RelayTo(CNode *pnode) const
407 // returns true if wasn't already sent
408 if (pnode->hashCheckpointKnown != hashCheckpoint)
410 pnode->hashCheckpointKnown = hashCheckpoint;
411 pnode->PushMessage("checkpoint", *this);
417 bool CSyncCheckpoint::CheckSignature()
419 CPubKey key(ParseHex(CSyncCheckpoint::strMasterPubKey));
420 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
421 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
423 // Now unserialize the data
424 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
425 sMsg >> *(CUnsignedSyncCheckpoint*)this;
429 // process synchronized checkpoint
430 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
432 if (!CheckSignature())
435 LOCK(Checkpoints::cs_hashSyncCheckpoint);
436 if (!mapBlockIndex.count(hashCheckpoint))
438 // We haven't received the checkpoint chain, keep the checkpoint as pending
439 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
440 Checkpoints::checkpointMessagePending = *this;
441 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
442 // Ask this guy to fill in what we're missing
445 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
446 // ask directly as well in case rejected earlier by duplicate
447 // proof-of-stake because getblocks may not get it this time
448 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
453 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
457 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
458 if (!pindexCheckpoint->IsInMainChain())
460 // checkpoint chain received but not yet main chain
462 if (!block.ReadFromDisk(pindexCheckpoint))
463 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
464 if (!block.SetBestChain(txdb, pindexCheckpoint))
466 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
467 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
471 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
472 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
473 Checkpoints::checkpointMessage = *this;
474 Checkpoints::hashPendingCheckpoint = 0;
475 Checkpoints::checkpointMessagePending.SetNull();
476 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());