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 <boost/assign/list_of.hpp> // for 'map_list_of()'
6 #include <boost/foreach.hpp>
8 #include "checkpoints.h"
18 uint256 hashCheckPoint;
22 typedef std::map<int, Checkpoint> MapCheckpoints;
24 Checkpoint initCheckpoint(uint256 hashCheckPoint, unsigned int nTime)
27 item.hashCheckPoint = hashCheckPoint;
34 // What makes a good checkpoint block?
35 // + Is surrounded by blocks with reasonable timestamps
36 // (no blocks before with a timestamp after, none after with
38 // + Contains no strange transactions
40 static MapCheckpoints mapCheckpoints =
41 boost::assign::map_list_of
42 ( 0, initCheckpoint(hashGenesisBlock, 1360105017) )
43 ( 9690, initCheckpoint(uint256("0x00000000026561450859c46868099e0df6068a538f038cb18988fd8d47dcdaf5"), 1362791423) )
44 ( 13560, initCheckpoint(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
45 ( 37092, initCheckpoint(uint256("0x0000000000a38c2f98556f46793b453e92d8fab2d31c0b93fd08bcf78e56099d"), 1376677203) )
46 ( 44200, initCheckpoint(uint256("0xc9bda7232a18b9c1f5ff974a9e5566b2d1879ceb8fc0e9e61fba9038a25b8447"), 1380145962) )
47 ( 65000, initCheckpoint(uint256("0xfb2b51a2fd65062c98a7a6053cde46aeaefebb95ba2f680e85a29ee25b1dcf05"), 1388526385) )
50 // TestNet has no checkpoints
51 static MapCheckpoints mapCheckpointsTestnet =
52 boost::assign::map_list_of
53 ( 0, initCheckpoint(hashGenesisBlockTestNet, 1360105017) )
56 bool CheckHardened(int nHeight, const uint256& hash)
58 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
60 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
61 if (i == checkpoints.end()) return true;
62 return hash == i->second.hashCheckPoint;
65 int GetTotalBlocksEstimate()
67 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
69 return checkpoints.rbegin()->first;
72 int GetLastCheckpointTime()
74 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
76 return checkpoints.rbegin()->second.nTime;
79 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
81 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
83 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
85 const uint256& hash = i.second.hashCheckPoint;
86 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
87 if (t != mapBlockIndex.end())
93 // ppcoin: synchronized checkpoint (centrally broadcasted)
94 uint256 hashSyncCheckpoint = 0;
95 uint256 hashPendingCheckpoint = 0;
96 CSyncCheckpoint checkpointMessage;
97 CSyncCheckpoint checkpointMessagePending;
98 uint256 hashInvalidCheckpoint = 0;
99 CCriticalSection cs_hashSyncCheckpoint;
101 // ppcoin: get last synchronized checkpoint
102 CBlockIndex* GetLastSyncCheckpoint()
104 LOCK(cs_hashSyncCheckpoint);
105 if (!mapBlockIndex.count(hashSyncCheckpoint))
106 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
108 return mapBlockIndex[hashSyncCheckpoint];
112 // ppcoin: only descendant of current sync-checkpoint is allowed
113 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
115 if (!mapBlockIndex.count(hashSyncCheckpoint))
116 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
117 if (!mapBlockIndex.count(hashCheckpoint))
118 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
120 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
121 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
123 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
125 // Received an older checkpoint, trace back from current checkpoint
126 // to the same height of the received checkpoint to verify
127 // that current checkpoint should be a descendant block
128 CBlockIndex* pindex = pindexSyncCheckpoint;
129 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
130 if (!(pindex = pindex->pprev))
131 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
132 if (pindex->GetBlockHash() != hashCheckpoint)
134 hashInvalidCheckpoint = hashCheckpoint;
135 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
137 return false; // ignore older checkpoint
140 // Received checkpoint should be a descendant block of the current
141 // checkpoint. Trace back to the same height of current checkpoint
143 CBlockIndex* pindex = pindexCheckpointRecv;
144 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
145 if (!(pindex = pindex->pprev))
146 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
147 if (pindex->GetBlockHash() != hashSyncCheckpoint)
149 hashInvalidCheckpoint = hashCheckpoint;
150 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
155 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
159 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
162 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
164 if (!txdb.TxnCommit())
165 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
167 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
171 bool AcceptPendingSyncCheckpoint()
173 LOCK(cs_hashSyncCheckpoint);
174 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
176 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
178 hashPendingCheckpoint = 0;
179 checkpointMessagePending.SetNull();
184 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
185 if (!pindexCheckpoint->IsInMainChain())
188 if (!block.ReadFromDisk(pindexCheckpoint))
189 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
190 if (!block.SetBestChain(txdb, pindexCheckpoint))
192 hashInvalidCheckpoint = hashPendingCheckpoint;
193 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
197 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
198 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
199 hashPendingCheckpoint = 0;
200 checkpointMessage = checkpointMessagePending;
201 checkpointMessagePending.SetNull();
202 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
203 // relay the checkpoint
204 if (!checkpointMessage.IsNull())
206 BOOST_FOREACH(CNode* pnode, vNodes)
207 checkpointMessage.RelayTo(pnode);
214 // Automatically select a suitable sync-checkpoint
215 uint256 AutoSelectSyncCheckpoint()
217 const CBlockIndex *pindex = pindexBest;
218 // Search backward for a block within max span and maturity window
219 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
220 pindex = pindex->pprev;
221 return pindex->GetBlockHash();
224 // Check against synchronized checkpoint
225 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
227 if (fTestNet) return true; // Testnet has no checkpoints
228 int nHeight = pindexPrev->nHeight + 1;
230 LOCK(cs_hashSyncCheckpoint);
231 // sync-checkpoint should always be accepted block
232 assert(mapBlockIndex.count(hashSyncCheckpoint));
233 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
235 if (nHeight > pindexSync->nHeight)
237 // trace back to same height as sync-checkpoint
238 const CBlockIndex* pindex = pindexPrev;
239 while (pindex->nHeight > pindexSync->nHeight)
240 if (!(pindex = pindex->pprev))
241 return error("CheckSync: pprev null - block index structure failure");
242 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
243 return false; // only descendant of sync-checkpoint can pass check
245 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
246 return false; // same height with sync-checkpoint
247 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
248 return false; // lower height than sync-checkpoint
252 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
254 LOCK(cs_hashSyncCheckpoint);
255 if (hashPendingCheckpoint == 0)
257 if (hashBlock == hashPendingCheckpoint)
259 if (mapOrphanBlocks.count(hashPendingCheckpoint)
260 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
265 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
266 bool ResetSyncCheckpoint()
268 LOCK(cs_hashSyncCheckpoint);
269 const uint256& hash = mapCheckpoints.rbegin()->second.hashCheckPoint;
270 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
272 // checkpoint block accepted but not yet in main chain
273 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
276 if (!block.ReadFromDisk(mapBlockIndex[hash]))
277 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
278 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
280 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
283 else if(!mapBlockIndex.count(hash))
285 // checkpoint block not yet accepted
286 hashPendingCheckpoint = hash;
287 checkpointMessagePending.SetNull();
288 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
291 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
293 const uint256& hash = i.second.hashCheckPoint;
294 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
296 if (!WriteSyncCheckpoint(hash))
297 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
298 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
306 void AskForPendingSyncCheckpoint(CNode* pfrom)
308 LOCK(cs_hashSyncCheckpoint);
309 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
310 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
313 bool SetCheckpointPrivKey(std::string strPrivKey)
315 // Test signing a sync-checkpoint with genesis block
316 CSyncCheckpoint checkpoint;
317 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
318 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
319 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
320 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
322 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
324 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
325 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
328 // Test signing successful, proceed
329 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
333 bool SendSyncCheckpoint(uint256 hashCheckpoint)
335 CSyncCheckpoint checkpoint;
336 checkpoint.hashCheckpoint = hashCheckpoint;
337 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
338 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
339 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
341 if (CSyncCheckpoint::strMasterPrivKey.empty())
342 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
343 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
345 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
346 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
347 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
349 if(!checkpoint.ProcessSyncCheckpoint(NULL))
351 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
358 BOOST_FOREACH(CNode* pnode, vNodes)
359 checkpoint.RelayTo(pnode);
364 // Is the sync-checkpoint outside maturity window?
365 bool IsMatureSyncCheckpoint()
367 LOCK(cs_hashSyncCheckpoint);
368 // sync-checkpoint should always be accepted block
369 assert(mapBlockIndex.count(hashSyncCheckpoint));
370 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
371 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
372 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
375 // Is the sync-checkpoint too old?
376 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
378 LOCK(cs_hashSyncCheckpoint);
379 // sync-checkpoint should always be accepted block
380 assert(mapBlockIndex.count(hashSyncCheckpoint));
381 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
382 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
386 // ppcoin: sync-checkpoint master key
387 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
389 std::string CSyncCheckpoint::strMasterPrivKey = "";
391 // ppcoin: verify signature of sync-checkpoint message
392 bool CSyncCheckpoint::CheckSignature()
395 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
396 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
397 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
398 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
400 // Now unserialize the data
401 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
402 sMsg >> *(CUnsignedSyncCheckpoint*)this;
406 // ppcoin: process synchronized checkpoint
407 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
409 if (!CheckSignature())
412 LOCK(Checkpoints::cs_hashSyncCheckpoint);
413 if (!mapBlockIndex.count(hashCheckpoint))
415 // We haven't received the checkpoint chain, keep the checkpoint as pending
416 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
417 Checkpoints::checkpointMessagePending = *this;
418 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
419 // Ask this guy to fill in what we're missing
422 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
423 // ask directly as well in case rejected earlier by duplicate
424 // proof-of-stake because getblocks may not get it this time
425 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
430 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
434 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
435 if (!pindexCheckpoint->IsInMainChain())
437 // checkpoint chain received but not yet main chain
439 if (!block.ReadFromDisk(pindexCheckpoint))
440 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
441 if (!block.SetBestChain(txdb, pindexCheckpoint))
443 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
444 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
448 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
449 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
450 Checkpoints::checkpointMessage = *this;
451 Checkpoints::hashPendingCheckpoint = 0;
452 Checkpoints::checkpointMessagePending.SetNull();
453 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());