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 ( 68600, std::make_pair(uint256("0xb646b0562080ab9411f85d4b2a1ca8b197c67ae170c5e328406871b44233cb06"), 1389867276) )
29 ( 92161, std::make_pair(uint256("0x000000000079090eb31e7fa55487e4e666466253e68b213f44b7977ea7a2eeec"), 1398919969) )
30 ( 98661, std::make_pair(uint256("0x48328dfc0eaffc659723739c6202854d1624449340193bdea3e71ece4ccdd43f"), 1401469019) )
33 // TestNet has no checkpoints
34 static MapCheckpoints mapCheckpointsTestnet =
35 boost::assign::map_list_of
36 ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
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.first;
48 int GetTotalBlocksEstimate()
50 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
52 return checkpoints.rbegin()->first;
55 int GetLastCheckpointTime()
57 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
59 return checkpoints.rbegin()->second.second;
62 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
64 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
66 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
68 const uint256& hash = i.second.first;
69 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
70 if (t != mapBlockIndex.end())
76 // ppcoin: synchronized checkpoint (centrally broadcasted)
77 uint256 hashSyncCheckpoint = 0;
78 uint256 hashPendingCheckpoint = 0;
79 CSyncCheckpoint checkpointMessage;
80 CSyncCheckpoint checkpointMessagePending;
81 uint256 hashInvalidCheckpoint = 0;
82 CCriticalSection cs_hashSyncCheckpoint;
84 // ppcoin: get last synchronized checkpoint
85 CBlockIndex* GetLastSyncCheckpoint()
87 LOCK(cs_hashSyncCheckpoint);
88 if (!mapBlockIndex.count(hashSyncCheckpoint))
89 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
91 return mapBlockIndex[hashSyncCheckpoint];
95 // ppcoin: only descendant of current sync-checkpoint is allowed
96 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
98 if (!mapBlockIndex.count(hashSyncCheckpoint))
99 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
100 if (!mapBlockIndex.count(hashCheckpoint))
101 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
103 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
104 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
106 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
108 // Received an older checkpoint, trace back from current checkpoint
109 // to the same height of the received checkpoint to verify
110 // that current checkpoint should be a descendant block
111 CBlockIndex* pindex = pindexSyncCheckpoint;
112 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
113 if (!(pindex = pindex->pprev))
114 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
115 if (pindex->GetBlockHash() != hashCheckpoint)
117 hashInvalidCheckpoint = hashCheckpoint;
118 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
120 return false; // ignore older checkpoint
123 // Received checkpoint should be a descendant block of the current
124 // checkpoint. Trace back to the same height of current checkpoint
126 CBlockIndex* pindex = pindexCheckpointRecv;
127 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
128 if (!(pindex = pindex->pprev))
129 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
130 if (pindex->GetBlockHash() != hashSyncCheckpoint)
132 hashInvalidCheckpoint = hashCheckpoint;
133 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
138 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
141 LOCK(Checkpoints::cs_hashSyncCheckpoint);
143 if (!pblocktree->WriteSyncCheckpoint(hashCheckpoint))
145 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
149 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
153 bool AcceptPendingSyncCheckpoint()
155 LOCK(cs_hashSyncCheckpoint);
156 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
158 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
160 hashPendingCheckpoint = 0;
161 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 (!SetBestChain(pindexCheckpoint))
173 hashInvalidCheckpoint = hashPendingCheckpoint;
174 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
178 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
179 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
180 hashPendingCheckpoint = 0;
181 checkpointMessage = checkpointMessagePending;
182 checkpointMessagePending.SetNull();
183 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
184 // relay the checkpoint
185 if (!checkpointMessage.IsNull())
187 BOOST_FOREACH(CNode* pnode, vNodes)
188 checkpointMessage.RelayTo(pnode);
195 // Automatically select a suitable sync-checkpoint
196 uint256 AutoSelectSyncCheckpoint()
198 const CBlockIndex *pindex = pindexBest;
199 // Search backward for a block within max span and maturity window
200 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
201 pindex = pindex->pprev;
202 return pindex->GetBlockHash();
205 // Check against synchronized checkpoint
206 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
208 if (fTestNet) return true; // Testnet has no checkpoints
209 int nHeight = pindexPrev->nHeight + 1;
211 LOCK(cs_hashSyncCheckpoint);
212 // sync-checkpoint should always be accepted block
213 assert(mapBlockIndex.count(hashSyncCheckpoint));
214 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
216 if (nHeight > pindexSync->nHeight)
218 // trace back to same height as sync-checkpoint
219 const CBlockIndex* pindex = pindexPrev;
220 while (pindex->nHeight > pindexSync->nHeight)
221 if (!(pindex = pindex->pprev))
222 return error("CheckSync: pprev null - block index structure failure");
223 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
224 return false; // only descendant of sync-checkpoint can pass check
226 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
227 return false; // same height with sync-checkpoint
228 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
229 return false; // lower height than sync-checkpoint
233 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
235 LOCK(cs_hashSyncCheckpoint);
236 if (hashPendingCheckpoint == 0)
238 if (hashBlock == hashPendingCheckpoint)
240 if (mapOrphanBlocks.count(hashPendingCheckpoint)
241 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
246 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
247 bool ResetSyncCheckpoint()
249 LOCK(cs_hashSyncCheckpoint);
250 const uint256& hash = mapCheckpoints.rbegin()->second.first;
251 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
253 // checkpoint block accepted but not yet in main chain
254 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
256 if (!block.ReadFromDisk(mapBlockIndex[hash]))
257 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
258 if (!SetBestChain(mapBlockIndex[hash]))
260 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
263 else if(!mapBlockIndex.count(hash))
265 // checkpoint block not yet accepted
266 hashPendingCheckpoint = hash;
267 checkpointMessagePending.SetNull();
268 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
271 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
273 const uint256& hash = i.second.first;
274 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
276 if (!WriteSyncCheckpoint(hash))
277 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
278 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
286 void AskForPendingSyncCheckpoint(CNode* pfrom)
288 LOCK(cs_hashSyncCheckpoint);
289 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
290 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
293 bool SetCheckpointPrivKey(std::string strPrivKey)
295 // Test signing a sync-checkpoint with genesis block
296 CSyncCheckpoint checkpoint;
297 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
298 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
299 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
300 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
302 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
304 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
305 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
308 // Test signing successful, proceed
309 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
313 bool SendSyncCheckpoint(uint256 hashCheckpoint)
315 CSyncCheckpoint checkpoint;
316 checkpoint.hashCheckpoint = hashCheckpoint;
317 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
318 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
319 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
321 if (CSyncCheckpoint::strMasterPrivKey.empty())
322 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
323 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
325 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
326 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
327 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
329 if(!checkpoint.ProcessSyncCheckpoint(NULL))
331 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
338 BOOST_FOREACH(CNode* pnode, vNodes)
339 checkpoint.RelayTo(pnode);
344 // Is the sync-checkpoint outside maturity window?
345 bool IsMatureSyncCheckpoint()
347 LOCK(cs_hashSyncCheckpoint);
348 // sync-checkpoint should always be accepted block
349 assert(mapBlockIndex.count(hashSyncCheckpoint));
350 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
351 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
352 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
355 // Is the sync-checkpoint too old?
356 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
358 LOCK(cs_hashSyncCheckpoint);
359 // sync-checkpoint should always be accepted block
360 assert(mapBlockIndex.count(hashSyncCheckpoint));
361 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
362 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
366 // ppcoin: sync-checkpoint master key
367 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
369 std::string CSyncCheckpoint::strMasterPrivKey = "";
371 // ppcoin: verify signature of sync-checkpoint message
372 bool CSyncCheckpoint::CheckSignature()
375 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
376 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
377 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
378 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
380 // Now unserialize the data
381 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
382 sMsg >> *(CUnsignedSyncCheckpoint*)this;
386 // ppcoin: process synchronized checkpoint
387 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
389 if (!CheckSignature())
392 LOCK(Checkpoints::cs_hashSyncCheckpoint);
393 if (!mapBlockIndex.count(hashCheckpoint))
395 // We haven't received the checkpoint chain, keep the checkpoint as pending
396 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
397 Checkpoints::checkpointMessagePending = *this;
398 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
399 // Ask this guy to fill in what we're missing
402 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
403 // ask directly as well in case rejected earlier by duplicate
404 // proof-of-stake because getblocks may not get it this time
405 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
410 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
413 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
414 if (!pindexCheckpoint->IsInMainChain())
416 // checkpoint chain received but not yet main chain
418 if (!block.ReadFromDisk(pindexCheckpoint))
419 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
420 if (!SetBestChain(pindexCheckpoint))
422 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
423 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
427 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
428 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
429 Checkpoints::checkpointMessage = *this;
430 Checkpoints::hashPendingCheckpoint = 0;
431 Checkpoints::checkpointMessagePending.SetNull();
432 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());