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, uint256> 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, hashGenesisBlock )
28 ( 6000, uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"))
29 ( 9690, uint256("0x00000000026561450859c46868099e0df6068a538f038cb18988fd8d47dcdaf5"))
30 ( 13560, uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"))
31 ( 14189, uint256("0x00000000020f76474d2522b19c7bfafc43ba6ecbabae54293bcd9546159c8c1d"))
32 ( 19600, uint256("0x252ae08d6df4bc7220c1dcdaed7b8a6e78bab05a60173511e8f565a3a38ce3c3"))
33 ( 21800, uint256("0x64bdeb35023f240ed01beaa082f840f2d4cc6defccbbcda1260de87e58296b37"))
36 static MapCheckpoints mapCheckpointsTestnet =
37 boost::assign::map_list_of
38 ( 0, hashGenesisBlockTestNet )
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;
50 int GetTotalBlocksEstimate()
52 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
54 return checkpoints.rbegin()->first;
57 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
59 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
61 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
63 const uint256& hash = i.second;
64 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
65 if (t != mapBlockIndex.end())
71 // ppcoin: synchronized checkpoint (centrally broadcasted)
72 uint256 hashSyncCheckpoint = 0;
73 uint256 hashPendingCheckpoint = 0;
74 CSyncCheckpoint checkpointMessage;
75 CSyncCheckpoint checkpointMessagePending;
76 uint256 hashInvalidCheckpoint = 0;
77 CCriticalSection cs_hashSyncCheckpoint;
79 // ppcoin: get last synchronized checkpoint
80 CBlockIndex* GetLastSyncCheckpoint()
82 LOCK(cs_hashSyncCheckpoint);
83 if (!mapBlockIndex.count(hashSyncCheckpoint))
84 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
86 return mapBlockIndex[hashSyncCheckpoint];
90 // ppcoin: only descendant of current sync-checkpoint is allowed
91 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
93 if (!mapBlockIndex.count(hashSyncCheckpoint))
94 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
95 if (!mapBlockIndex.count(hashCheckpoint))
96 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
98 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
99 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
101 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
103 // Received an older checkpoint, trace back from current checkpoint
104 // to the same height of the received checkpoint to verify
105 // that current checkpoint should be a descendant block
106 CBlockIndex* pindex = pindexSyncCheckpoint;
107 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
108 if (!(pindex = pindex->pprev))
109 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
110 if (pindex->GetBlockHash() != hashCheckpoint)
112 hashInvalidCheckpoint = hashCheckpoint;
113 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
115 return false; // ignore older checkpoint
118 // Received checkpoint should be a descendant block of the current
119 // checkpoint. Trace back to the same height of current checkpoint
121 CBlockIndex* pindex = pindexCheckpointRecv;
122 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
123 if (!(pindex = pindex->pprev))
124 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
125 if (pindex->GetBlockHash() != hashSyncCheckpoint)
127 hashInvalidCheckpoint = hashCheckpoint;
128 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
133 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
137 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
140 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
142 if (!txdb.TxnCommit())
143 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
146 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
150 bool AcceptPendingSyncCheckpoint()
152 LOCK(cs_hashSyncCheckpoint);
153 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
155 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
157 hashPendingCheckpoint = 0;
158 checkpointMessagePending.SetNull();
163 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
164 if (!pindexCheckpoint->IsInMainChain())
167 if (!block.ReadFromDisk(pindexCheckpoint))
168 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
169 if (!block.SetBestChain(txdb, pindexCheckpoint))
171 hashInvalidCheckpoint = hashPendingCheckpoint;
172 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
177 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
178 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
179 hashPendingCheckpoint = 0;
180 checkpointMessage = checkpointMessagePending;
181 checkpointMessagePending.SetNull();
182 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
183 // relay the checkpoint
184 if (!checkpointMessage.IsNull())
186 BOOST_FOREACH(CNode* pnode, vNodes)
187 checkpointMessage.RelayTo(pnode);
194 // Automatically select a suitable sync-checkpoint
195 uint256 AutoSelectSyncCheckpoint()
197 // Proof-of-work blocks are immediately checkpointed
198 // to defend against 51% attack which rejects other miners block
200 // Select the last proof-of-work block
201 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
202 // Search forward for a block within max span and maturity window
203 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
204 pindex = pindex->pnext;
205 return pindex->GetBlockHash();
208 // Check against synchronized checkpoint
209 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
211 if (fTestNet) return true; // Testnet has no checkpoints
212 int nHeight = pindexPrev->nHeight + 1;
214 LOCK(cs_hashSyncCheckpoint);
215 // sync-checkpoint should always be accepted block
216 assert(mapBlockIndex.count(hashSyncCheckpoint));
217 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
219 if (nHeight > pindexSync->nHeight)
221 // trace back to same height as sync-checkpoint
222 const CBlockIndex* pindex = pindexPrev;
223 while (pindex->nHeight > pindexSync->nHeight)
224 if (!(pindex = pindex->pprev))
225 return error("CheckSync: pprev null - block index structure failure");
226 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
227 return false; // only descendant of sync-checkpoint can pass check
229 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
230 return false; // same height with sync-checkpoint
231 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
232 return false; // lower height than sync-checkpoint
236 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
238 LOCK(cs_hashSyncCheckpoint);
239 if (hashPendingCheckpoint == 0)
241 if (hashBlock == hashPendingCheckpoint)
243 if (mapOrphanBlocks.count(hashPendingCheckpoint)
244 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
249 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
250 bool ResetSyncCheckpoint()
252 LOCK(cs_hashSyncCheckpoint);
253 const uint256& hash = mapCheckpoints.rbegin()->second;
254 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
256 // checkpoint block accepted but not yet in main chain
257 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
260 if (!block.ReadFromDisk(mapBlockIndex[hash]))
261 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
262 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
264 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;
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());
434 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
435 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
436 Checkpoints::checkpointMessage = *this;
437 Checkpoints::hashPendingCheckpoint = 0;
438 Checkpoints::checkpointMessagePending.SetNull();
439 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());