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"
16 typedef std::map<int, std::pair<uint256, unsigned int> > MapCheckpoints;
19 // What makes a good checkpoint block?
20 // + Is surrounded by blocks with reasonable timestamps
21 // (no blocks before with a timestamp after, none after with
23 // + Contains no strange transactions
25 static MapCheckpoints mapCheckpoints =
26 boost::assign::map_list_of
27 ( 0, std::make_pair(hashGenesisBlock, 1360105017) )
28 ( 9690, std::make_pair(uint256("0x00000000026561450859c46868099e0df6068a538f038cb18988fd8d47dcdaf5"), 1362791423) )
29 ( 13560, std::make_pair(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
30 ( 37092, std::make_pair(uint256("0x0000000000a38c2f98556f46793b453e92d8fab2d31c0b93fd08bcf78e56099d"), 1376677203) )
31 ( 44200, std::make_pair(uint256("0xc9bda7232a18b9c1f5ff974a9e5566b2d1879ceb8fc0e9e61fba9038a25b8447"), 1380145962) )
32 ( 65000, std::make_pair(uint256("0xfb2b51a2fd65062c98a7a6053cde46aeaefebb95ba2f680e85a29ee25b1dcf05"), 1388526385) )
35 // TestNet has no checkpoints
36 static MapCheckpoints mapCheckpointsTestnet =
37 boost::assign::map_list_of
38 ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
41 bool CheckHardened(int nHeight, const uint256& hash)
43 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
45 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
46 if (i == checkpoints.end()) return true;
47 return hash == i->second.first;
50 int GetTotalBlocksEstimate()
52 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
54 return checkpoints.rbegin()->first;
57 int GetLastCheckpointTime()
59 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
61 return checkpoints.rbegin()->second.second;
64 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
66 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
68 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
70 const uint256& hash = i.second.first;
71 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
72 if (t != mapBlockIndex.end())
78 // ppcoin: synchronized checkpoint (centrally broadcasted)
79 uint256 hashSyncCheckpoint = 0;
80 uint256 hashPendingCheckpoint = 0;
81 CSyncCheckpoint checkpointMessage;
82 CSyncCheckpoint checkpointMessagePending;
83 uint256 hashInvalidCheckpoint = 0;
84 CCriticalSection cs_hashSyncCheckpoint;
86 // ppcoin: get last synchronized checkpoint
87 CBlockIndex* GetLastSyncCheckpoint()
89 LOCK(cs_hashSyncCheckpoint);
90 if (!mapBlockIndex.count(hashSyncCheckpoint))
91 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
93 return mapBlockIndex[hashSyncCheckpoint];
97 // ppcoin: only descendant of current sync-checkpoint is allowed
98 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
100 if (!mapBlockIndex.count(hashSyncCheckpoint))
101 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
102 if (!mapBlockIndex.count(hashCheckpoint))
103 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
105 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
106 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
108 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
110 // Received an older checkpoint, trace back from current checkpoint
111 // to the same height of the received checkpoint to verify
112 // that current checkpoint should be a descendant block
113 CBlockIndex* pindex = pindexSyncCheckpoint;
114 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
115 if (!(pindex = pindex->pprev))
116 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
117 if (pindex->GetBlockHash() != hashCheckpoint)
119 hashInvalidCheckpoint = hashCheckpoint;
120 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
122 return false; // ignore older checkpoint
125 // Received checkpoint should be a descendant block of the current
126 // checkpoint. Trace back to the same height of current checkpoint
128 CBlockIndex* pindex = pindexCheckpointRecv;
129 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
130 if (!(pindex = pindex->pprev))
131 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
132 if (pindex->GetBlockHash() != hashSyncCheckpoint)
134 hashInvalidCheckpoint = hashCheckpoint;
135 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
140 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
144 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
147 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
149 if (!txdb.TxnCommit())
150 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
152 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
156 bool AcceptPendingSyncCheckpoint()
158 LOCK(cs_hashSyncCheckpoint);
159 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
161 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
163 hashPendingCheckpoint = 0;
164 checkpointMessagePending.SetNull();
169 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
170 if (!pindexCheckpoint->IsInMainChain())
173 if (!block.ReadFromDisk(pindexCheckpoint))
174 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175 if (!block.SetBestChain(txdb, pindexCheckpoint))
177 hashInvalidCheckpoint = hashPendingCheckpoint;
178 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
182 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
183 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
184 hashPendingCheckpoint = 0;
185 checkpointMessage = checkpointMessagePending;
186 checkpointMessagePending.SetNull();
187 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
188 // relay the checkpoint
189 if (!checkpointMessage.IsNull())
191 BOOST_FOREACH(CNode* pnode, vNodes)
192 checkpointMessage.RelayTo(pnode);
199 // Automatically select a suitable sync-checkpoint
200 uint256 AutoSelectSyncCheckpoint()
202 const CBlockIndex *pindex = pindexBest;
203 // Search backward for a block within max span and maturity window
204 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
205 pindex = pindex->pprev;
206 return pindex->GetBlockHash();
209 // Check against synchronized checkpoint
210 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
212 if (fTestNet) return true; // Testnet has no checkpoints
213 int nHeight = pindexPrev->nHeight + 1;
215 LOCK(cs_hashSyncCheckpoint);
216 // sync-checkpoint should always be accepted block
217 assert(mapBlockIndex.count(hashSyncCheckpoint));
218 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
220 if (nHeight > pindexSync->nHeight)
222 // trace back to same height as sync-checkpoint
223 const CBlockIndex* pindex = pindexPrev;
224 while (pindex->nHeight > pindexSync->nHeight)
225 if (!(pindex = pindex->pprev))
226 return error("CheckSync: pprev null - block index structure failure");
227 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
228 return false; // only descendant of sync-checkpoint can pass check
230 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
231 return false; // same height with sync-checkpoint
232 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
233 return false; // lower height than sync-checkpoint
237 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
239 LOCK(cs_hashSyncCheckpoint);
240 if (hashPendingCheckpoint == 0)
242 if (hashBlock == hashPendingCheckpoint)
244 if (mapOrphanBlocks.count(hashPendingCheckpoint)
245 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
250 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
251 bool ResetSyncCheckpoint()
253 LOCK(cs_hashSyncCheckpoint);
254 const uint256& hash = mapCheckpoints.rbegin()->second.first;
255 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
257 // checkpoint block accepted but not yet in main chain
258 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
261 if (!block.ReadFromDisk(mapBlockIndex[hash]))
262 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
263 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
265 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
268 else if(!mapBlockIndex.count(hash))
270 // checkpoint block not yet accepted
271 hashPendingCheckpoint = hash;
272 checkpointMessagePending.SetNull();
273 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
276 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
278 const uint256& hash = i.second.first;
279 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
281 if (!WriteSyncCheckpoint(hash))
282 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
283 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
291 void AskForPendingSyncCheckpoint(CNode* pfrom)
293 LOCK(cs_hashSyncCheckpoint);
294 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
295 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
298 bool SetCheckpointPrivKey(std::string strPrivKey)
300 // Test signing a sync-checkpoint with genesis block
301 CSyncCheckpoint checkpoint;
302 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
303 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
304 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
305 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
307 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
309 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
310 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
313 // Test signing successful, proceed
314 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
318 bool SendSyncCheckpoint(uint256 hashCheckpoint)
320 CSyncCheckpoint checkpoint;
321 checkpoint.hashCheckpoint = hashCheckpoint;
322 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
323 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
324 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
326 if (CSyncCheckpoint::strMasterPrivKey.empty())
327 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
328 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
330 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
331 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
332 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
334 if(!checkpoint.ProcessSyncCheckpoint(NULL))
336 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
343 BOOST_FOREACH(CNode* pnode, vNodes)
344 checkpoint.RelayTo(pnode);
349 // Is the sync-checkpoint outside maturity window?
350 bool IsMatureSyncCheckpoint()
352 LOCK(cs_hashSyncCheckpoint);
353 // sync-checkpoint should always be accepted block
354 assert(mapBlockIndex.count(hashSyncCheckpoint));
355 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
356 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
357 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
360 // Is the sync-checkpoint too old?
361 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
363 LOCK(cs_hashSyncCheckpoint);
364 // sync-checkpoint should always be accepted block
365 assert(mapBlockIndex.count(hashSyncCheckpoint));
366 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
367 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
371 // ppcoin: sync-checkpoint master key
372 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
374 std::string CSyncCheckpoint::strMasterPrivKey = "";
376 // ppcoin: verify signature of sync-checkpoint message
377 bool CSyncCheckpoint::CheckSignature()
380 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
381 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
382 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
383 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
385 // Now unserialize the data
386 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
387 sMsg >> *(CUnsignedSyncCheckpoint*)this;
391 // ppcoin: process synchronized checkpoint
392 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
394 if (!CheckSignature())
397 LOCK(Checkpoints::cs_hashSyncCheckpoint);
398 if (!mapBlockIndex.count(hashCheckpoint))
400 // We haven't received the checkpoint chain, keep the checkpoint as pending
401 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
402 Checkpoints::checkpointMessagePending = *this;
403 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
404 // Ask this guy to fill in what we're missing
407 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
408 // ask directly as well in case rejected earlier by duplicate
409 // proof-of-stake because getblocks may not get it this time
410 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
415 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
419 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
420 if (!pindexCheckpoint->IsInMainChain())
422 // checkpoint chain received but not yet main chain
424 if (!block.ReadFromDisk(pindexCheckpoint))
425 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
426 if (!block.SetBestChain(txdb, pindexCheckpoint))
428 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
429 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
433 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
434 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
435 Checkpoints::checkpointMessage = *this;
436 Checkpoints::hashPendingCheckpoint = 0;
437 Checkpoints::checkpointMessagePending.SetNull();
438 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());