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"))
34 ( 26174, uint256("0x00000000006cf1bfaa0d73caea92f6d2afa465651a76415b8d53b0bb0e01a8be"))
37 // TestNet has no checkpoints
38 static MapCheckpoints mapCheckpointsTestnet =
39 boost::assign::map_list_of
40 ( 0, hashGenesisBlockTestNet )
43 bool CheckHardened(int nHeight, const uint256& hash)
45 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
47 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
48 if (i == checkpoints.end()) return true;
49 return hash == i->second;
52 int GetTotalBlocksEstimate()
54 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
56 return checkpoints.rbegin()->first;
59 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
61 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
63 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
65 const uint256& hash = i.second;
66 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
67 if (t != mapBlockIndex.end())
73 // ppcoin: synchronized checkpoint (centrally broadcasted)
74 uint256 hashSyncCheckpoint = 0;
75 uint256 hashPendingCheckpoint = 0;
76 CSyncCheckpoint checkpointMessage;
77 CSyncCheckpoint checkpointMessagePending;
78 uint256 hashInvalidCheckpoint = 0;
79 CCriticalSection cs_hashSyncCheckpoint;
81 // ppcoin: get last synchronized checkpoint
82 CBlockIndex* GetLastSyncCheckpoint()
84 LOCK(cs_hashSyncCheckpoint);
85 if (!mapBlockIndex.count(hashSyncCheckpoint))
86 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
88 return mapBlockIndex[hashSyncCheckpoint];
92 // ppcoin: only descendant of current sync-checkpoint is allowed
93 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
95 if (!mapBlockIndex.count(hashSyncCheckpoint))
96 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
97 if (!mapBlockIndex.count(hashCheckpoint))
98 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
100 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
101 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
103 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
105 // Received an older checkpoint, trace back from current checkpoint
106 // to the same height of the received checkpoint to verify
107 // that current checkpoint should be a descendant block
108 CBlockIndex* pindex = pindexSyncCheckpoint;
109 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
110 if (!(pindex = pindex->pprev))
111 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
112 if (pindex->GetBlockHash() != hashCheckpoint)
114 hashInvalidCheckpoint = hashCheckpoint;
115 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
117 return false; // ignore older checkpoint
120 // Received checkpoint should be a descendant block of the current
121 // checkpoint. Trace back to the same height of current checkpoint
123 CBlockIndex* pindex = pindexCheckpointRecv;
124 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
125 if (!(pindex = pindex->pprev))
126 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
127 if (pindex->GetBlockHash() != hashSyncCheckpoint)
129 hashInvalidCheckpoint = hashCheckpoint;
130 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
135 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
139 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
142 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
144 if (!txdb.TxnCommit())
145 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
148 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
152 bool AcceptPendingSyncCheckpoint()
154 LOCK(cs_hashSyncCheckpoint);
155 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
157 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
159 hashPendingCheckpoint = 0;
160 checkpointMessagePending.SetNull();
165 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
166 if (!pindexCheckpoint->IsInMainChain())
169 if (!block.ReadFromDisk(pindexCheckpoint))
170 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
171 if (!block.SetBestChain(txdb, pindexCheckpoint))
173 hashInvalidCheckpoint = hashPendingCheckpoint;
174 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
179 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
180 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
181 hashPendingCheckpoint = 0;
182 checkpointMessage = checkpointMessagePending;
183 checkpointMessagePending.SetNull();
184 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
185 // relay the checkpoint
186 if (!checkpointMessage.IsNull())
188 BOOST_FOREACH(CNode* pnode, vNodes)
189 checkpointMessage.RelayTo(pnode);
196 // Automatically select a suitable sync-checkpoint
197 uint256 AutoSelectSyncCheckpoint()
199 // Proof-of-work blocks are immediately checkpointed
200 // to defend against 51% attack which rejects other miners block
202 // Select the last proof-of-work block
203 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
204 // Search forward for a block within max span and maturity window
205 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
206 pindex = pindex->pnext;
207 return pindex->GetBlockHash();
210 // Check against synchronized checkpoint
211 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
213 if (fTestNet) return true; // Testnet has no checkpoints
214 int nHeight = pindexPrev->nHeight + 1;
216 LOCK(cs_hashSyncCheckpoint);
217 // sync-checkpoint should always be accepted block
218 assert(mapBlockIndex.count(hashSyncCheckpoint));
219 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
221 if (nHeight > pindexSync->nHeight)
223 // trace back to same height as sync-checkpoint
224 const CBlockIndex* pindex = pindexPrev;
225 while (pindex->nHeight > pindexSync->nHeight)
226 if (!(pindex = pindex->pprev))
227 return error("CheckSync: pprev null - block index structure failure");
228 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
229 return false; // only descendant of sync-checkpoint can pass check
231 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
232 return false; // same height with sync-checkpoint
233 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
234 return false; // lower height than sync-checkpoint
238 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
240 LOCK(cs_hashSyncCheckpoint);
241 if (hashPendingCheckpoint == 0)
243 if (hashBlock == hashPendingCheckpoint)
245 if (mapOrphanBlocks.count(hashPendingCheckpoint)
246 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
251 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
252 bool ResetSyncCheckpoint()
254 LOCK(cs_hashSyncCheckpoint);
255 const uint256& hash = mapCheckpoints.rbegin()->second;
256 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
258 // checkpoint block accepted but not yet in main chain
259 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
262 if (!block.ReadFromDisk(mapBlockIndex[hash]))
263 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
264 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
266 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
270 else if(!mapBlockIndex.count(hash))
272 // checkpoint block not yet accepted
273 hashPendingCheckpoint = hash;
274 checkpointMessagePending.SetNull();
275 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
278 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
280 const uint256& hash = i.second;
281 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
283 if (!WriteSyncCheckpoint(hash))
284 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
285 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
293 void AskForPendingSyncCheckpoint(CNode* pfrom)
295 LOCK(cs_hashSyncCheckpoint);
296 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
297 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
300 bool SetCheckpointPrivKey(std::string strPrivKey)
302 // Test signing a sync-checkpoint with genesis block
303 CSyncCheckpoint checkpoint;
304 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
305 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
306 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
307 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
309 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
311 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
312 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
315 // Test signing successful, proceed
316 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
320 bool SendSyncCheckpoint(uint256 hashCheckpoint)
322 CSyncCheckpoint checkpoint;
323 checkpoint.hashCheckpoint = hashCheckpoint;
324 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
325 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
326 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
328 if (CSyncCheckpoint::strMasterPrivKey.empty())
329 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
330 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
332 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
333 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
334 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
336 if(!checkpoint.ProcessSyncCheckpoint(NULL))
338 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
345 BOOST_FOREACH(CNode* pnode, vNodes)
346 checkpoint.RelayTo(pnode);
351 // Is the sync-checkpoint outside maturity window?
352 bool IsMatureSyncCheckpoint()
354 LOCK(cs_hashSyncCheckpoint);
355 // sync-checkpoint should always be accepted block
356 assert(mapBlockIndex.count(hashSyncCheckpoint));
357 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
358 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
359 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
362 // Is the sync-checkpoint too old?
363 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
365 LOCK(cs_hashSyncCheckpoint);
366 // sync-checkpoint should always be accepted block
367 assert(mapBlockIndex.count(hashSyncCheckpoint));
368 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
369 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
373 // ppcoin: sync-checkpoint master key
374 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
376 std::string CSyncCheckpoint::strMasterPrivKey = "";
378 // ppcoin: verify signature of sync-checkpoint message
379 bool CSyncCheckpoint::CheckSignature()
382 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
383 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
384 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
385 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
387 // Now unserialize the data
388 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
389 sMsg >> *(CUnsignedSyncCheckpoint*)this;
393 // ppcoin: process synchronized checkpoint
394 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
396 if (!CheckSignature())
399 LOCK(Checkpoints::cs_hashSyncCheckpoint);
400 if (!mapBlockIndex.count(hashCheckpoint))
402 // We haven't received the checkpoint chain, keep the checkpoint as pending
403 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
404 Checkpoints::checkpointMessagePending = *this;
405 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
406 // Ask this guy to fill in what we're missing
409 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
410 // ask directly as well in case rejected earlier by duplicate
411 // proof-of-stake because getblocks may not get it this time
412 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
417 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
421 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
422 if (!pindexCheckpoint->IsInMainChain())
424 // checkpoint chain received but not yet main chain
426 if (!block.ReadFromDisk(pindexCheckpoint))
427 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
428 if (!block.SetBestChain(txdb, pindexCheckpoint))
430 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
431 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
436 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
437 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
438 Checkpoints::checkpointMessage = *this;
439 Checkpoints::hashPendingCheckpoint = 0;
440 Checkpoints::checkpointMessagePending.SetNull();
441 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());