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 )
30 ( 6000, uint256("0x000000000945e3c9d8e15df834e802521eb79f9ceb4191a27bdfadad4b777f4a"))
31 ( 8700, uint256("0x00000000014270724837789c9a69859290f6bdee38556bc4561c21f17935a178"))
32 ( 13560, uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"))
35 bool CheckHardened(int nHeight, const uint256& hash)
37 if (fTestNet) return true; // Testnet has no checkpoints
39 MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
40 if (i == mapCheckpoints.end()) return true;
41 return hash == i->second;
44 int GetTotalBlocksEstimate()
46 if (fTestNet) return 0;
48 return mapCheckpoints.rbegin()->first;
51 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
54 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hashGenesisBlock);
55 if (t != mapBlockIndex.end())
60 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
62 const uint256& hash = i.second;
63 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
64 if (t != mapBlockIndex.end())
70 // ppcoin: synchronized checkpoint (centrally broadcasted)
71 uint256 hashSyncCheckpoint = 0;
72 uint256 hashPendingCheckpoint = 0;
73 CSyncCheckpoint checkpointMessage;
74 CSyncCheckpoint checkpointMessagePending;
75 uint256 hashInvalidCheckpoint = 0;
76 CCriticalSection cs_hashSyncCheckpoint;
78 // ppcoin: get last synchronized checkpoint
79 CBlockIndex* GetLastSyncCheckpoint()
81 LOCK(cs_hashSyncCheckpoint);
82 if (!mapBlockIndex.count(hashSyncCheckpoint))
83 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
85 return mapBlockIndex[hashSyncCheckpoint];
89 // ppcoin: only descendant of current sync-checkpoint is allowed
90 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
92 if (!mapBlockIndex.count(hashSyncCheckpoint))
93 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
94 if (!mapBlockIndex.count(hashCheckpoint))
95 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
97 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
98 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
100 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
102 // Received an older checkpoint, trace back from current checkpoint
103 // to the same height of the received checkpoint to verify
104 // that current checkpoint should be a descendant block
105 CBlockIndex* pindex = pindexSyncCheckpoint;
106 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
107 if (!(pindex = pindex->pprev))
108 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
109 if (pindex->GetBlockHash() != hashCheckpoint)
111 hashInvalidCheckpoint = hashCheckpoint;
112 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
114 return false; // ignore older checkpoint
117 // Received checkpoint should be a descendant block of the current
118 // checkpoint. Trace back to the same height of current checkpoint
120 CBlockIndex* pindex = pindexCheckpointRecv;
121 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
122 if (!(pindex = pindex->pprev))
123 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
124 if (pindex->GetBlockHash() != hashSyncCheckpoint)
126 hashInvalidCheckpoint = hashCheckpoint;
127 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
132 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
136 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
139 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
141 if (!txdb.TxnCommit())
142 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
145 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
149 bool AcceptPendingSyncCheckpoint()
151 LOCK(cs_hashSyncCheckpoint);
152 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
154 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
156 hashPendingCheckpoint = 0;
157 checkpointMessagePending.SetNull();
162 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
163 if (!pindexCheckpoint->IsInMainChain())
166 if (!block.ReadFromDisk(pindexCheckpoint))
167 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
168 if (!block.SetBestChain(txdb, pindexCheckpoint))
170 hashInvalidCheckpoint = hashPendingCheckpoint;
171 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
176 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
177 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
178 hashPendingCheckpoint = 0;
179 checkpointMessage = checkpointMessagePending;
180 checkpointMessagePending.SetNull();
181 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
182 // relay the checkpoint
183 if (!checkpointMessage.IsNull())
185 BOOST_FOREACH(CNode* pnode, vNodes)
186 checkpointMessage.RelayTo(pnode);
193 // Automatically select a suitable sync-checkpoint
194 uint256 AutoSelectSyncCheckpoint()
196 // Proof-of-work blocks are immediately checkpointed
197 // to defend against 51% attack which rejects other miners block
199 // Select the last proof-of-work block
200 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
201 // Search forward for a block within max span and maturity window
202 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
203 pindex = pindex->pnext;
204 return pindex->GetBlockHash();
207 // Check against synchronized checkpoint
208 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
210 if (fTestNet) return true; // Testnet has no checkpoints
211 int nHeight = pindexPrev->nHeight + 1;
213 LOCK(cs_hashSyncCheckpoint);
214 // sync-checkpoint should always be accepted block
215 assert(mapBlockIndex.count(hashSyncCheckpoint));
216 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
218 if (nHeight > pindexSync->nHeight)
220 // trace back to same height as sync-checkpoint
221 const CBlockIndex* pindex = pindexPrev;
222 while (pindex->nHeight > pindexSync->nHeight)
223 if (!(pindex = pindex->pprev))
224 return error("CheckSync: pprev null - block index structure failure");
225 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
226 return false; // only descendant of sync-checkpoint can pass check
228 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
229 return false; // same height with sync-checkpoint
230 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
231 return false; // lower height than sync-checkpoint
235 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
237 LOCK(cs_hashSyncCheckpoint);
238 if (hashPendingCheckpoint == 0)
240 if (hashBlock == hashPendingCheckpoint)
242 if (mapOrphanBlocks.count(hashPendingCheckpoint)
243 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
248 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
249 bool ResetSyncCheckpoint()
251 LOCK(cs_hashSyncCheckpoint);
252 const uint256& hash = mapCheckpoints.rbegin()->second;
253 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
255 // checkpoint block accepted but not yet in main chain
256 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
259 if (!block.ReadFromDisk(mapBlockIndex[hash]))
260 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
261 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
263 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
267 else if(!mapBlockIndex.count(hash))
269 // checkpoint block not yet accepted
270 hashPendingCheckpoint = hash;
271 checkpointMessagePending.SetNull();
272 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
275 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
277 const uint256& hash = i.second;
278 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
280 if (!WriteSyncCheckpoint(hash))
281 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
282 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
290 void AskForPendingSyncCheckpoint(CNode* pfrom)
292 LOCK(cs_hashSyncCheckpoint);
293 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
294 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
297 bool SetCheckpointPrivKey(std::string strPrivKey)
299 // Test signing a sync-checkpoint with genesis block
300 CSyncCheckpoint checkpoint;
301 checkpoint.hashCheckpoint = hashGenesisBlock;
302 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
303 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
304 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
306 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
308 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
309 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
312 // Test signing successful, proceed
313 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
317 bool SendSyncCheckpoint(uint256 hashCheckpoint)
319 CSyncCheckpoint checkpoint;
320 checkpoint.hashCheckpoint = hashCheckpoint;
321 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
322 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
323 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
325 if (CSyncCheckpoint::strMasterPrivKey.empty())
326 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
327 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
329 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
330 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
331 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
333 if(!checkpoint.ProcessSyncCheckpoint(NULL))
335 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
342 BOOST_FOREACH(CNode* pnode, vNodes)
343 checkpoint.RelayTo(pnode);
348 // Is the sync-checkpoint outside maturity window?
349 bool IsMatureSyncCheckpoint()
351 LOCK(cs_hashSyncCheckpoint);
352 // sync-checkpoint should always be accepted block
353 assert(mapBlockIndex.count(hashSyncCheckpoint));
354 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
355 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
356 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
359 // Is the sync-checkpoint too old?
360 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
362 LOCK(cs_hashSyncCheckpoint);
363 // sync-checkpoint should always be accepted block
364 assert(mapBlockIndex.count(hashSyncCheckpoint));
365 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
366 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
370 // ppcoin: sync-checkpoint master key
371 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
373 std::string CSyncCheckpoint::strMasterPrivKey = "";
375 // ppcoin: verify signature of sync-checkpoint message
376 bool CSyncCheckpoint::CheckSignature()
379 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
380 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
381 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
382 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
384 // Now unserialize the data
385 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
386 sMsg >> *(CUnsignedSyncCheckpoint*)this;
390 // ppcoin: process synchronized checkpoint
391 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
393 if (!CheckSignature())
396 LOCK(Checkpoints::cs_hashSyncCheckpoint);
397 if (!mapBlockIndex.count(hashCheckpoint))
399 // We haven't received the checkpoint chain, keep the checkpoint as pending
400 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
401 Checkpoints::checkpointMessagePending = *this;
402 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
403 // Ask this guy to fill in what we're missing
406 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
407 // ask directly as well in case rejected earlier by duplicate
408 // proof-of-stake because getblocks may not get it this time
409 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
414 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
418 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
419 if (!pindexCheckpoint->IsInMainChain())
421 // checkpoint chain received but not yet main chain
423 if (!block.ReadFromDisk(pindexCheckpoint))
424 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
425 if (!block.SetBestChain(txdb, pindexCheckpoint))
427 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
428 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
433 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
434 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
435 Checkpoints::checkpointMessage = *this;
436 Checkpoints::hashPendingCheckpoint = 0;
437 Checkpoints::checkpointMessagePending.SetNull();
438 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());