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) )
31 // TestNet has no checkpoints
32 static MapCheckpoints mapCheckpointsTestnet =
33 boost::assign::map_list_of
34 ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
37 bool CheckHardened(int nHeight, const uint256& hash)
39 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
41 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
42 if (i == checkpoints.end()) return true;
43 return hash == i->second.first;
46 int GetTotalBlocksEstimate()
48 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
50 return checkpoints.rbegin()->first;
53 int GetLastCheckpointTime()
55 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
57 return checkpoints.rbegin()->second.second;
60 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
62 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
64 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
66 const uint256& hash = i.second.first;
67 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
68 if (t != mapBlockIndex.end())
74 // ppcoin: synchronized checkpoint (centrally broadcasted)
75 uint256 hashSyncCheckpoint = 0;
76 uint256 hashPendingCheckpoint = 0;
77 CSyncCheckpoint checkpointMessage;
78 CSyncCheckpoint checkpointMessagePending;
79 uint256 hashInvalidCheckpoint = 0;
80 CCriticalSection cs_hashSyncCheckpoint;
82 // ppcoin: get last synchronized checkpoint
83 CBlockIndex* GetLastSyncCheckpoint()
85 LOCK(cs_hashSyncCheckpoint);
86 if (!mapBlockIndex.count(hashSyncCheckpoint))
87 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
89 return mapBlockIndex[hashSyncCheckpoint];
93 // ppcoin: only descendant of current sync-checkpoint is allowed
94 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
96 if (!mapBlockIndex.count(hashSyncCheckpoint))
97 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
98 if (!mapBlockIndex.count(hashCheckpoint))
99 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
101 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
102 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
104 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
106 // Received an older checkpoint, trace back from current checkpoint
107 // to the same height of the received checkpoint to verify
108 // that current checkpoint should be a descendant block
109 CBlockIndex* pindex = pindexSyncCheckpoint;
110 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
111 if (!(pindex = pindex->pprev))
112 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
113 if (pindex->GetBlockHash() != hashCheckpoint)
115 hashInvalidCheckpoint = hashCheckpoint;
116 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
118 return false; // ignore older checkpoint
121 // Received checkpoint should be a descendant block of the current
122 // checkpoint. Trace back to the same height of current checkpoint
124 CBlockIndex* pindex = pindexCheckpointRecv;
125 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
126 if (!(pindex = pindex->pprev))
127 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
128 if (pindex->GetBlockHash() != hashSyncCheckpoint)
130 hashInvalidCheckpoint = hashCheckpoint;
131 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
136 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
140 if (!chaindb.WriteSyncCheckpoint(hashCheckpoint))
143 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
145 if (!chaindb.TxnCommit())
146 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(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());
257 if (!block.ReadFromDisk(mapBlockIndex[hash]))
258 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
259 if (!block.SetBestChain(mapBlockIndex[hash]))
261 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
264 else if(!mapBlockIndex.count(hash))
266 // checkpoint block not yet accepted
267 hashPendingCheckpoint = hash;
268 checkpointMessagePending.SetNull();
269 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
272 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
274 const uint256& hash = i.second.first;
275 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
277 if (!WriteSyncCheckpoint(hash))
278 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
279 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
287 void AskForPendingSyncCheckpoint(CNode* pfrom)
289 LOCK(cs_hashSyncCheckpoint);
290 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
291 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
294 bool SetCheckpointPrivKey(std::string strPrivKey)
296 // Test signing a sync-checkpoint with genesis block
297 CSyncCheckpoint checkpoint;
298 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
299 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
300 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
301 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
303 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
305 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
306 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
309 // Test signing successful, proceed
310 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
314 bool SendSyncCheckpoint(uint256 hashCheckpoint)
316 CSyncCheckpoint checkpoint;
317 checkpoint.hashCheckpoint = hashCheckpoint;
318 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
319 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
320 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
322 if (CSyncCheckpoint::strMasterPrivKey.empty())
323 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
324 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
326 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
327 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
328 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
330 if(!checkpoint.ProcessSyncCheckpoint(NULL))
332 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
339 BOOST_FOREACH(CNode* pnode, vNodes)
340 checkpoint.RelayTo(pnode);
345 // Is the sync-checkpoint outside maturity window?
346 bool IsMatureSyncCheckpoint()
348 LOCK(cs_hashSyncCheckpoint);
349 // sync-checkpoint should always be accepted block
350 assert(mapBlockIndex.count(hashSyncCheckpoint));
351 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
352 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
353 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
356 // Is the sync-checkpoint too old?
357 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
359 LOCK(cs_hashSyncCheckpoint);
360 // sync-checkpoint should always be accepted block
361 assert(mapBlockIndex.count(hashSyncCheckpoint));
362 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
363 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
367 // ppcoin: sync-checkpoint master key
368 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
370 std::string CSyncCheckpoint::strMasterPrivKey = "";
372 // ppcoin: verify signature of sync-checkpoint message
373 bool CSyncCheckpoint::CheckSignature()
376 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
377 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
378 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
379 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
381 // Now unserialize the data
382 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
383 sMsg >> *(CUnsignedSyncCheckpoint*)this;
387 // ppcoin: process synchronized checkpoint
388 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
390 if (!CheckSignature())
393 LOCK(Checkpoints::cs_hashSyncCheckpoint);
394 if (!mapBlockIndex.count(hashCheckpoint))
396 // We haven't received the checkpoint chain, keep the checkpoint as pending
397 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
398 Checkpoints::checkpointMessagePending = *this;
399 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
400 // Ask this guy to fill in what we're missing
403 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
404 // ask directly as well in case rejected earlier by duplicate
405 // proof-of-stake because getblocks may not get it this time
406 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
411 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
415 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
416 if (!pindexCheckpoint->IsInMainChain())
418 // checkpoint chain received but not yet main chain
420 if (!block.ReadFromDisk(pindexCheckpoint))
421 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
422 if (!block.SetBestChain(pindexCheckpoint))
424 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
425 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
429 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
430 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
431 Checkpoints::checkpointMessage = *this;
432 Checkpoints::hashPendingCheckpoint = 0;
433 Checkpoints::checkpointMessagePending.SetNull();
434 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());