1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Copyright (c) 2011-2012 The PPCoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
7 #include <boost/foreach.hpp>
9 #include "checkpoints.h"
17 typedef std::map<int, uint256> MapCheckpoints; // hardened checkpoints
20 // What makes a good checkpoint block?
21 // + Is surrounded by blocks with reasonable timestamps
22 // (no blocks before with a timestamp after, none after with
24 // + Contains no strange transactions
26 static MapCheckpoints mapCheckpoints =
27 boost::assign::map_list_of
28 ( 0, hashGenesisBlockOfficial )
29 ; // ppcoin: no checkpoint yet; to be created in future releases
31 bool CheckHardened(int nHeight, const uint256& hash)
33 if (fTestNet) return true; // Testnet has no checkpoints
35 MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
36 if (i == mapCheckpoints.end()) return true;
37 return hash == i->second;
40 int GetTotalBlocksEstimate()
42 if (fTestNet) return 0;
44 return mapCheckpoints.rbegin()->first;
47 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
50 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
51 if (t != mapBlockIndex.end())
56 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
58 const uint256& hash = i.second;
59 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
60 if (t != mapBlockIndex.end())
66 // ppcoin: synchronized checkpoint (centrally broadcasted)
67 uint256 hashSyncCheckpoint = 0;
68 uint256 hashPendingCheckpoint = 0;
69 CSyncCheckpoint checkpointMessage;
70 CSyncCheckpoint checkpointMessagePending;
71 uint256 hashInvalidCheckpoint = 0;
72 CCriticalSection cs_hashSyncCheckpoint;
74 // ppcoin: get last synchronized checkpoint
75 CBlockIndex* GetLastSyncCheckpoint()
77 LOCK(cs_hashSyncCheckpoint);
78 if (!mapBlockIndex.count(hashSyncCheckpoint))
79 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
81 return mapBlockIndex[hashSyncCheckpoint];
85 // ppcoin: only descendant of current sync-checkpoint is allowed
86 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
88 if (!mapBlockIndex.count(hashSyncCheckpoint))
89 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
90 if (!mapBlockIndex.count(hashCheckpoint))
91 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
93 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
94 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
96 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
98 // Received an older checkpoint, trace back from current checkpoint
99 // to the same height of the received checkpoint to verify
100 // that current checkpoint should be a descendant block
101 CBlockIndex* pindex = pindexSyncCheckpoint;
102 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
103 if (!(pindex = pindex->pprev))
104 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
105 if (pindex->GetBlockHash() != hashCheckpoint)
107 hashInvalidCheckpoint = hashCheckpoint;
108 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
110 return false; // ignore older checkpoint
113 // Received checkpoint should be a descendant block of the current
114 // checkpoint. Trace back to the same height of current checkpoint
116 CBlockIndex* pindex = pindexCheckpointRecv;
117 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
118 if (!(pindex = pindex->pprev))
119 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
120 if (pindex->GetBlockHash() != hashSyncCheckpoint)
122 hashInvalidCheckpoint = hashCheckpoint;
123 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
128 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
132 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
135 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
137 if (!txdb.TxnCommit())
138 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
141 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
145 bool AcceptPendingSyncCheckpoint()
147 LOCK(cs_hashSyncCheckpoint);
148 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
150 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
152 hashPendingCheckpoint = 0;
153 checkpointMessagePending.SetNull();
158 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
159 if (!pindexCheckpoint->IsInMainChain())
162 if (!Reorganize(txdb, pindexCheckpoint))
165 hashInvalidCheckpoint = hashPendingCheckpoint;
166 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
171 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
172 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
173 hashPendingCheckpoint = 0;
174 checkpointMessage = checkpointMessagePending;
175 checkpointMessagePending.SetNull();
176 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
177 // relay the checkpoint
178 if (!checkpointMessage.IsNull())
180 BOOST_FOREACH(CNode* pnode, vNodes)
181 checkpointMessage.RelayTo(pnode);
188 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
190 if (fTestNet) return true; // Testnet has no checkpoints
191 int nHeight = pindexPrev->nHeight + 1;
193 LOCK(cs_hashSyncCheckpoint);
194 // sync-checkpoint should always be accepted block
195 assert(mapBlockIndex.count(hashSyncCheckpoint));
196 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
198 if (nHeight > pindexSync->nHeight)
200 // trace back to same height as sync-checkpoint
201 const CBlockIndex* pindex = pindexPrev;
202 while (pindex->nHeight > pindexSync->nHeight)
203 if (!(pindex = pindex->pprev))
204 return error("CheckSync: pprev null - block index structure failure");
205 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
206 return false; // only descendant of sync-checkpoint can pass check
208 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
209 return false; // same height with sync-checkpoint
210 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
211 return false; // lower height than sync-checkpoint
215 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
217 LOCK(cs_hashSyncCheckpoint);
218 if (hashPendingCheckpoint == 0)
220 if (hashBlock == hashPendingCheckpoint)
222 if (mapOrphanBlocks.count(hashPendingCheckpoint)
223 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
228 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
229 bool ResetSyncCheckpoint()
231 LOCK(cs_hashSyncCheckpoint);
232 const uint256& hash = mapCheckpoints.rbegin()->second;
233 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
235 // checkpoint block accepted but not yet in main chain
236 printf("ResetSyncCheckpoint: Reorganize to hardened checkpoint %s\n", hash.ToString().c_str());
239 if (!Reorganize(txdb, mapBlockIndex[hash]))
242 return error("ResetSyncCheckpoint: Reorganize failed for hardened checkpoint %s", hash.ToString().c_str());
246 else if(!mapBlockIndex.count(hash))
248 // checkpoint block not yet accepted
249 hashPendingCheckpoint = hash;
250 checkpointMessagePending.SetNull();
251 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
254 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
256 const uint256& hash = i.second;
257 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
259 if (!WriteSyncCheckpoint(hash))
260 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
261 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
269 void AskForPendingSyncCheckpoint(CNode* pfrom)
271 LOCK(cs_hashSyncCheckpoint);
272 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
273 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
276 bool SendSyncCheckpoint(uint256 hashCheckpoint)
278 CSyncCheckpoint checkpoint;
279 checkpoint.hashCheckpoint = hashCheckpoint;
280 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
281 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
282 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
284 if (CSyncCheckpoint::strMasterPrivKey.empty())
285 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
286 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
288 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
289 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
290 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
292 if(!checkpoint.ProcessSyncCheckpoint(NULL))
293 return error("SendSyncCheckpoint: Failed to process checkpoint.");
297 BOOST_FOREACH(CNode* pnode, vNodes)
298 checkpoint.RelayTo(pnode);
304 // ppcoin: sync-checkpoint master key
305 const std::string CSyncCheckpoint::strMasterPubKey = "0424f20205e5da98ba632bbd278a11a6499585f62bfb2c782377ef59f0251daab8085fc31471bcb8180bc75ed0fa41bb50c7c084511d54015a3a5241d645c7268a";
307 std::string CSyncCheckpoint::strMasterPrivKey = "";
309 // ppcoin: verify signature of sync-checkpoint message
310 bool CSyncCheckpoint::CheckSignature()
313 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
314 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
315 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
316 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
318 // Now unserialize the data
319 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
320 sMsg >> *(CUnsignedSyncCheckpoint*)this;
324 // ppcoin: process synchronized checkpoint
325 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
327 if (!CheckSignature())
330 LOCK(Checkpoints::cs_hashSyncCheckpoint);
331 if (!mapBlockIndex.count(hashCheckpoint))
333 // We haven't received the checkpoint chain, keep the checkpoint as pending
334 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
335 Checkpoints::checkpointMessagePending = *this;
336 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
337 // Ask this guy to fill in what we're missing
340 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
341 // ask directly as well in case rejected earlier by duplicate
342 // proof-of-stake because getblocks may not get it this time
343 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
348 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
352 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
353 if (!pindexCheckpoint->IsInMainChain())
355 // checkpoint chain received but not yet main chain
357 if (!Reorganize(txdb, pindexCheckpoint))
360 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
361 return error("ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
366 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
367 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
368 Checkpoints::checkpointMessage = *this;
369 Checkpoints::hashPendingCheckpoint = 0;
370 Checkpoints::checkpointMessagePending.SetNull();
371 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());