1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Copyright (c) 2011-2013 The PPCoin developers
3 // Copyright (c) 2013 NovaCoin Developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
7 #include <boost/assign/list_of.hpp> // for 'map_list_of()'
8 #include <boost/foreach.hpp>
10 #include "checkpoints.h"
18 typedef std::map<int, uint256> MapCheckpoints; // hardened checkpoints
21 // What makes a good checkpoint block?
22 // + Is surrounded by blocks with reasonable timestamps
23 // (no blocks before with a timestamp after, none after with
25 // + Contains no strange transactions
27 static MapCheckpoints mapCheckpoints =
28 boost::assign::map_list_of
29 ( 0, hashGenesisBlockOfficial )
32 bool CheckHardened(int nHeight, const uint256& hash)
34 if (fTestNet) return true; // Testnet has no checkpoints
36 MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
37 if (i == mapCheckpoints.end()) return true;
38 return hash == i->second;
41 int GetTotalBlocksEstimate()
43 if (fTestNet) return 0;
45 return mapCheckpoints.rbegin()->first;
48 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
51 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
52 if (t != mapBlockIndex.end())
57 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
59 const uint256& hash = i.second;
60 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
61 if (t != mapBlockIndex.end())
67 // ppcoin: synchronized checkpoint (centrally broadcasted)
68 uint256 hashSyncCheckpoint = 0;
69 uint256 hashPendingCheckpoint = 0;
70 CSyncCheckpoint checkpointMessage;
71 CSyncCheckpoint checkpointMessagePending;
72 uint256 hashInvalidCheckpoint = 0;
73 CCriticalSection cs_hashSyncCheckpoint;
75 // ppcoin: get last synchronized checkpoint
76 CBlockIndex* GetLastSyncCheckpoint()
78 LOCK(cs_hashSyncCheckpoint);
79 if (!mapBlockIndex.count(hashSyncCheckpoint))
80 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
82 return mapBlockIndex[hashSyncCheckpoint];
86 // ppcoin: only descendant of current sync-checkpoint is allowed
87 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
89 if (!mapBlockIndex.count(hashSyncCheckpoint))
90 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
91 if (!mapBlockIndex.count(hashCheckpoint))
92 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
94 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
95 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
97 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
99 // Received an older checkpoint, trace back from current checkpoint
100 // to the same height of the received checkpoint to verify
101 // that current checkpoint should be a descendant block
102 CBlockIndex* pindex = pindexSyncCheckpoint;
103 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
104 if (!(pindex = pindex->pprev))
105 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
106 if (pindex->GetBlockHash() != hashCheckpoint)
108 hashInvalidCheckpoint = hashCheckpoint;
109 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
111 return false; // ignore older checkpoint
114 // Received checkpoint should be a descendant block of the current
115 // checkpoint. Trace back to the same height of current checkpoint
117 CBlockIndex* pindex = pindexCheckpointRecv;
118 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
119 if (!(pindex = pindex->pprev))
120 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
121 if (pindex->GetBlockHash() != hashSyncCheckpoint)
123 hashInvalidCheckpoint = hashCheckpoint;
124 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
129 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
133 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
136 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
138 if (!txdb.TxnCommit())
139 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
142 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
146 bool AcceptPendingSyncCheckpoint()
148 LOCK(cs_hashSyncCheckpoint);
149 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
151 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
153 hashPendingCheckpoint = 0;
154 checkpointMessagePending.SetNull();
159 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
160 if (!pindexCheckpoint->IsInMainChain())
163 if (!block.ReadFromDisk(pindexCheckpoint))
164 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
165 if (!block.SetBestChain(txdb, pindexCheckpoint))
167 hashInvalidCheckpoint = hashPendingCheckpoint;
168 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
173 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
174 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
175 hashPendingCheckpoint = 0;
176 checkpointMessage = checkpointMessagePending;
177 checkpointMessagePending.SetNull();
178 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
179 // relay the checkpoint
180 if (!checkpointMessage.IsNull())
182 BOOST_FOREACH(CNode* pnode, vNodes)
183 checkpointMessage.RelayTo(pnode);
190 // Automatically select a suitable sync-checkpoint
191 uint256 AutoSelectSyncCheckpoint()
193 // Proof-of-work blocks are immediately checkpointed
194 // to defend against 51% attack which rejects other miners block
196 // Select the last proof-of-work block
197 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
198 // Search forward for a block within max span and maturity window
199 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
200 pindex = pindex->pnext;
201 return pindex->GetBlockHash();
204 // Check against synchronized checkpoint
205 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
207 if (fTestNet) return true; // Testnet has no checkpoints
208 int nHeight = pindexPrev->nHeight + 1;
210 LOCK(cs_hashSyncCheckpoint);
211 // sync-checkpoint should always be accepted block
212 assert(mapBlockIndex.count(hashSyncCheckpoint));
213 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
215 if (nHeight > pindexSync->nHeight)
217 // trace back to same height as sync-checkpoint
218 const CBlockIndex* pindex = pindexPrev;
219 while (pindex->nHeight > pindexSync->nHeight)
220 if (!(pindex = pindex->pprev))
221 return error("CheckSync: pprev null - block index structure failure");
222 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
223 return false; // only descendant of sync-checkpoint can pass check
225 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
226 return false; // same height with sync-checkpoint
227 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
228 return false; // lower height than sync-checkpoint
232 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
234 LOCK(cs_hashSyncCheckpoint);
235 if (hashPendingCheckpoint == 0)
237 if (hashBlock == hashPendingCheckpoint)
239 if (mapOrphanBlocks.count(hashPendingCheckpoint)
240 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
245 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
246 bool ResetSyncCheckpoint()
248 LOCK(cs_hashSyncCheckpoint);
249 const uint256& hash = mapCheckpoints.rbegin()->second;
250 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
252 // checkpoint block accepted but not yet in main chain
253 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 (!block.SetBestChain(txdb, mapBlockIndex[hash]))
260 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;
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 = hashGenesisBlock;
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(txdb, pindexCheckpoint))
424 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
425 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
430 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
431 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
432 Checkpoints::checkpointMessage = *this;
433 Checkpoints::hashPendingCheckpoint = 0;
434 Checkpoints::checkpointMessagePending.SetNull();
435 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());