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, hashGenesisBlockOfficial )
28 ( 6000, uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"))
29 ( 8700, uint256("0x00000000014270724837789c9a69859290f6bdee38556bc4561c21f17935a178"))
30 ( 13560, uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"))
31 ( 14189, uint256("0x00000000020f76474d2522b19c7bfafc43ba6ecbabae54293bcd9546159c8c1d"))
34 static MapCheckpoints mapCheckpointsTestnet =
35 boost::assign::map_list_of
36 ( 0, hashGenesisBlockOfficial )
39 bool CheckHardened(int nHeight, const uint256& hash)
41 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
43 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
44 if (i == checkpoints.end()) return true;
45 return hash == i->second;
48 int GetTotalBlocksEstimate()
50 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
52 return checkpoints.rbegin()->first;
55 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
57 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
59 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
61 const uint256& hash = i.second;
62 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
63 if (t != mapBlockIndex.end())
69 // ppcoin: synchronized checkpoint (centrally broadcasted)
70 uint256 hashSyncCheckpoint = 0;
71 uint256 hashPendingCheckpoint = 0;
72 CSyncCheckpoint checkpointMessage;
73 CSyncCheckpoint checkpointMessagePending;
74 uint256 hashInvalidCheckpoint = 0;
75 CCriticalSection cs_hashSyncCheckpoint;
77 // ppcoin: get last synchronized checkpoint
78 CBlockIndex* GetLastSyncCheckpoint()
80 LOCK(cs_hashSyncCheckpoint);
81 if (!mapBlockIndex.count(hashSyncCheckpoint))
82 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
84 return mapBlockIndex[hashSyncCheckpoint];
88 // ppcoin: only descendant of current sync-checkpoint is allowed
89 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
91 if (!mapBlockIndex.count(hashSyncCheckpoint))
92 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
93 if (!mapBlockIndex.count(hashCheckpoint))
94 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
96 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
97 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
99 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
101 // Received an older checkpoint, trace back from current checkpoint
102 // to the same height of the received checkpoint to verify
103 // that current checkpoint should be a descendant block
104 CBlockIndex* pindex = pindexSyncCheckpoint;
105 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
106 if (!(pindex = pindex->pprev))
107 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
108 if (pindex->GetBlockHash() != hashCheckpoint)
110 hashInvalidCheckpoint = hashCheckpoint;
111 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
113 return false; // ignore older checkpoint
116 // Received checkpoint should be a descendant block of the current
117 // checkpoint. Trace back to the same height of current checkpoint
119 CBlockIndex* pindex = pindexCheckpointRecv;
120 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
121 if (!(pindex = pindex->pprev))
122 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
123 if (pindex->GetBlockHash() != hashSyncCheckpoint)
125 hashInvalidCheckpoint = hashCheckpoint;
126 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
131 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
135 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
138 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
140 if (!txdb.TxnCommit())
141 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
144 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
148 bool AcceptPendingSyncCheckpoint()
150 LOCK(cs_hashSyncCheckpoint);
151 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
153 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
155 hashPendingCheckpoint = 0;
156 checkpointMessagePending.SetNull();
161 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
162 if (!pindexCheckpoint->IsInMainChain())
165 if (!block.ReadFromDisk(pindexCheckpoint))
166 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
167 if (!block.SetBestChain(txdb, pindexCheckpoint))
169 hashInvalidCheckpoint = hashPendingCheckpoint;
170 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
176 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
177 hashPendingCheckpoint = 0;
178 checkpointMessage = checkpointMessagePending;
179 checkpointMessagePending.SetNull();
180 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
181 // relay the checkpoint
182 if (!checkpointMessage.IsNull())
184 BOOST_FOREACH(CNode* pnode, vNodes)
185 checkpointMessage.RelayTo(pnode);
192 // Automatically select a suitable sync-checkpoint
193 uint256 AutoSelectSyncCheckpoint()
195 // Proof-of-work blocks are immediately checkpointed
196 // to defend against 51% attack which rejects other miners block
198 // Select the last proof-of-work block
199 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
200 // Search forward for a block within max span and maturity window
201 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
202 pindex = pindex->pnext;
203 return pindex->GetBlockHash();
206 // Check against synchronized checkpoint
207 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
209 if (fTestNet) return true; // Testnet has no checkpoints
210 int nHeight = pindexPrev->nHeight + 1;
212 LOCK(cs_hashSyncCheckpoint);
213 // sync-checkpoint should always be accepted block
214 assert(mapBlockIndex.count(hashSyncCheckpoint));
215 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
217 if (nHeight > pindexSync->nHeight)
219 // trace back to same height as sync-checkpoint
220 const CBlockIndex* pindex = pindexPrev;
221 while (pindex->nHeight > pindexSync->nHeight)
222 if (!(pindex = pindex->pprev))
223 return error("CheckSync: pprev null - block index structure failure");
224 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
225 return false; // only descendant of sync-checkpoint can pass check
227 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
228 return false; // same height with sync-checkpoint
229 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
230 return false; // lower height than sync-checkpoint
234 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
236 LOCK(cs_hashSyncCheckpoint);
237 if (hashPendingCheckpoint == 0)
239 if (hashBlock == hashPendingCheckpoint)
241 if (mapOrphanBlocks.count(hashPendingCheckpoint)
242 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
247 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
248 bool ResetSyncCheckpoint()
250 LOCK(cs_hashSyncCheckpoint);
251 const uint256& hash = mapCheckpoints.rbegin()->second;
252 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
254 // checkpoint block accepted but not yet in main chain
255 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
258 if (!block.ReadFromDisk(mapBlockIndex[hash]))
259 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
260 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
262 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
266 else if(!mapBlockIndex.count(hash))
268 // checkpoint block not yet accepted
269 hashPendingCheckpoint = hash;
270 checkpointMessagePending.SetNull();
271 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
274 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
276 const uint256& hash = i.second;
277 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
279 if (!WriteSyncCheckpoint(hash))
280 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
281 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
289 void AskForPendingSyncCheckpoint(CNode* pfrom)
291 LOCK(cs_hashSyncCheckpoint);
292 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
293 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
296 bool SetCheckpointPrivKey(std::string strPrivKey)
298 // Test signing a sync-checkpoint with genesis block
299 CSyncCheckpoint checkpoint;
300 checkpoint.hashCheckpoint = hashGenesisBlock;
301 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
302 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
303 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
305 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
307 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
308 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
311 // Test signing successful, proceed
312 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
316 bool SendSyncCheckpoint(uint256 hashCheckpoint)
318 CSyncCheckpoint checkpoint;
319 checkpoint.hashCheckpoint = hashCheckpoint;
320 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
321 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
322 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
324 if (CSyncCheckpoint::strMasterPrivKey.empty())
325 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
326 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
328 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
329 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
330 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
332 if(!checkpoint.ProcessSyncCheckpoint(NULL))
334 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
341 BOOST_FOREACH(CNode* pnode, vNodes)
342 checkpoint.RelayTo(pnode);
347 // Is the sync-checkpoint outside maturity window?
348 bool IsMatureSyncCheckpoint()
350 LOCK(cs_hashSyncCheckpoint);
351 // sync-checkpoint should always be accepted block
352 assert(mapBlockIndex.count(hashSyncCheckpoint));
353 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
354 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
355 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
358 // Is the sync-checkpoint too old?
359 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
361 LOCK(cs_hashSyncCheckpoint);
362 // sync-checkpoint should always be accepted block
363 assert(mapBlockIndex.count(hashSyncCheckpoint));
364 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
365 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
369 // ppcoin: sync-checkpoint master key
370 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
372 std::string CSyncCheckpoint::strMasterPrivKey = "";
374 // ppcoin: verify signature of sync-checkpoint message
375 bool CSyncCheckpoint::CheckSignature()
378 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
379 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
380 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
381 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
383 // Now unserialize the data
384 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
385 sMsg >> *(CUnsignedSyncCheckpoint*)this;
389 // ppcoin: process synchronized checkpoint
390 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
392 if (!CheckSignature())
395 LOCK(Checkpoints::cs_hashSyncCheckpoint);
396 if (!mapBlockIndex.count(hashCheckpoint))
398 // We haven't received the checkpoint chain, keep the checkpoint as pending
399 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
400 Checkpoints::checkpointMessagePending = *this;
401 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
402 // Ask this guy to fill in what we're missing
405 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
406 // ask directly as well in case rejected earlier by duplicate
407 // proof-of-stake because getblocks may not get it this time
408 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
413 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
417 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
418 if (!pindexCheckpoint->IsInMainChain())
420 // checkpoint chain received but not yet main chain
422 if (!block.ReadFromDisk(pindexCheckpoint))
423 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
424 if (!block.SetBestChain(txdb, pindexCheckpoint))
426 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
427 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
432 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
433 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
434 Checkpoints::checkpointMessage = *this;
435 Checkpoints::hashPendingCheckpoint = 0;
436 Checkpoints::checkpointMessagePending.SetNull();
437 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());