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"
18 uint256 hashCheckPoint;
22 typedef std::map<int, Checkpoint> MapCheckpoints;
24 Checkpoint initCheckpoint(uint256 hashCheckPoint, unsigned int nTime)
27 item.hashCheckPoint = hashCheckPoint;
34 // What makes a good checkpoint block?
35 // + Is surrounded by blocks with reasonable timestamps
36 // (no blocks before with a timestamp after, none after with
38 // + Contains no strange transactions
40 static MapCheckpoints mapCheckpoints =
41 boost::assign::map_list_of
42 ( 0, initCheckpoint(hashGenesisBlock, 1360105017) )
43 ( 9690, initCheckpoint(uint256("0x00000000026561450859c46868099e0df6068a538f038cb18988fd8d47dcdaf5"), 1362791423) )
44 ( 13560, initCheckpoint(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
45 ( 37092, initCheckpoint(uint256("0x0000000000a38c2f98556f46793b453e92d8fab2d31c0b93fd08bcf78e56099d"), 1376677203) )
48 // TestNet has no checkpoints
49 static MapCheckpoints mapCheckpointsTestnet =
50 boost::assign::map_list_of
51 ( 0, initCheckpoint(hashGenesisBlockTestNet, 1360105017) )
54 bool CheckHardened(int nHeight, const uint256& hash)
56 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
58 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
59 if (i == checkpoints.end()) return true;
60 return hash == i->second.hashCheckPoint;
63 int GetTotalBlocksEstimate()
65 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
67 return checkpoints.rbegin()->first;
70 int GetLastCheckpointTime()
72 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
74 return checkpoints.rbegin()->second.nTime;
77 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
79 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
81 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
83 const uint256& hash = i.second.hashCheckPoint;
84 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
85 if (t != mapBlockIndex.end())
91 // ppcoin: synchronized checkpoint (centrally broadcasted)
92 uint256 hashSyncCheckpoint = 0;
93 uint256 hashPendingCheckpoint = 0;
94 CSyncCheckpoint checkpointMessage;
95 CSyncCheckpoint checkpointMessagePending;
96 uint256 hashInvalidCheckpoint = 0;
97 CCriticalSection cs_hashSyncCheckpoint;
99 // ppcoin: get last synchronized checkpoint
100 CBlockIndex* GetLastSyncCheckpoint()
102 LOCK(cs_hashSyncCheckpoint);
103 if (!mapBlockIndex.count(hashSyncCheckpoint))
104 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
106 return mapBlockIndex[hashSyncCheckpoint];
110 // ppcoin: only descendant of current sync-checkpoint is allowed
111 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
113 if (!mapBlockIndex.count(hashSyncCheckpoint))
114 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
115 if (!mapBlockIndex.count(hashCheckpoint))
116 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
118 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
119 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
121 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
123 // Received an older checkpoint, trace back from current checkpoint
124 // to the same height of the received checkpoint to verify
125 // that current checkpoint should be a descendant block
126 CBlockIndex* pindex = pindexSyncCheckpoint;
127 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
128 if (!(pindex = pindex->pprev))
129 return error("ValidateSyncCheckpoint: pprev1 null - block index structure failure");
130 if (pindex->GetBlockHash() != hashCheckpoint)
132 hashInvalidCheckpoint = hashCheckpoint;
133 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
135 return false; // ignore older checkpoint
138 // Received checkpoint should be a descendant block of the current
139 // checkpoint. Trace back to the same height of current checkpoint
141 CBlockIndex* pindex = pindexCheckpointRecv;
142 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
143 if (!(pindex = pindex->pprev))
144 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
145 if (pindex->GetBlockHash() != hashSyncCheckpoint)
147 hashInvalidCheckpoint = hashCheckpoint;
148 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
153 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
157 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
160 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
162 if (!txdb.TxnCommit())
163 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
166 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
170 bool AcceptPendingSyncCheckpoint()
172 LOCK(cs_hashSyncCheckpoint);
173 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
175 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
177 hashPendingCheckpoint = 0;
178 checkpointMessagePending.SetNull();
183 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
184 if (!pindexCheckpoint->IsInMainChain())
187 if (!block.ReadFromDisk(pindexCheckpoint))
188 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
189 if (!block.SetBestChain(txdb, pindexCheckpoint))
191 hashInvalidCheckpoint = hashPendingCheckpoint;
192 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
197 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
198 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
199 hashPendingCheckpoint = 0;
200 checkpointMessage = checkpointMessagePending;
201 checkpointMessagePending.SetNull();
202 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
203 // relay the checkpoint
204 if (!checkpointMessage.IsNull())
206 BOOST_FOREACH(CNode* pnode, vNodes)
207 checkpointMessage.RelayTo(pnode);
214 // Automatically select a suitable sync-checkpoint
215 uint256 AutoSelectSyncCheckpoint()
217 // Proof-of-work blocks are immediately checkpointed
218 // to defend against 51% attack which rejects other miners block
220 // Select the last proof-of-work block
221 const CBlockIndex *pindex = GetLastBlockIndex(pindexBest, false);
222 // Search forward for a block within max span and maturity window
223 while (pindex->pnext && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN <= pindexBest->GetBlockTime() || pindex->nHeight + std::min(6, nCoinbaseMaturity - 20) <= pindexBest->nHeight))
224 pindex = pindex->pnext;
225 return pindex->GetBlockHash();
228 // Check against synchronized checkpoint
229 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
231 if (fTestNet) return true; // Testnet has no checkpoints
232 int nHeight = pindexPrev->nHeight + 1;
234 LOCK(cs_hashSyncCheckpoint);
235 // sync-checkpoint should always be accepted block
236 assert(mapBlockIndex.count(hashSyncCheckpoint));
237 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
239 if (nHeight > pindexSync->nHeight)
241 // trace back to same height as sync-checkpoint
242 const CBlockIndex* pindex = pindexPrev;
243 while (pindex->nHeight > pindexSync->nHeight)
244 if (!(pindex = pindex->pprev))
245 return error("CheckSync: pprev null - block index structure failure");
246 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
247 return false; // only descendant of sync-checkpoint can pass check
249 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
250 return false; // same height with sync-checkpoint
251 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
252 return false; // lower height than sync-checkpoint
256 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
258 LOCK(cs_hashSyncCheckpoint);
259 if (hashPendingCheckpoint == 0)
261 if (hashBlock == hashPendingCheckpoint)
263 if (mapOrphanBlocks.count(hashPendingCheckpoint)
264 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
269 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
270 bool ResetSyncCheckpoint()
272 LOCK(cs_hashSyncCheckpoint);
273 const uint256& hash = mapCheckpoints.rbegin()->second.hashCheckPoint;
274 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
276 // checkpoint block accepted but not yet in main chain
277 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
280 if (!block.ReadFromDisk(mapBlockIndex[hash]))
281 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
282 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
284 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
288 else if(!mapBlockIndex.count(hash))
290 // checkpoint block not yet accepted
291 hashPendingCheckpoint = hash;
292 checkpointMessagePending.SetNull();
293 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
296 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
298 const uint256& hash = i.second.hashCheckPoint;
299 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
301 if (!WriteSyncCheckpoint(hash))
302 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
303 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
311 void AskForPendingSyncCheckpoint(CNode* pfrom)
313 LOCK(cs_hashSyncCheckpoint);
314 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
315 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
318 bool SetCheckpointPrivKey(std::string strPrivKey)
320 // Test signing a sync-checkpoint with genesis block
321 CSyncCheckpoint checkpoint;
322 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
323 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
324 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
325 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
327 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
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))
333 // Test signing successful, proceed
334 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
338 bool SendSyncCheckpoint(uint256 hashCheckpoint)
340 CSyncCheckpoint checkpoint;
341 checkpoint.hashCheckpoint = hashCheckpoint;
342 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
343 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
344 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
346 if (CSyncCheckpoint::strMasterPrivKey.empty())
347 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
348 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
350 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
351 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
352 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
354 if(!checkpoint.ProcessSyncCheckpoint(NULL))
356 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
363 BOOST_FOREACH(CNode* pnode, vNodes)
364 checkpoint.RelayTo(pnode);
369 // Is the sync-checkpoint outside maturity window?
370 bool IsMatureSyncCheckpoint()
372 LOCK(cs_hashSyncCheckpoint);
373 // sync-checkpoint should always be accepted block
374 assert(mapBlockIndex.count(hashSyncCheckpoint));
375 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
376 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
377 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
380 // Is the sync-checkpoint too old?
381 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
383 LOCK(cs_hashSyncCheckpoint);
384 // sync-checkpoint should always be accepted block
385 assert(mapBlockIndex.count(hashSyncCheckpoint));
386 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
387 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
391 // ppcoin: sync-checkpoint master key
392 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
394 std::string CSyncCheckpoint::strMasterPrivKey = "";
396 // ppcoin: verify signature of sync-checkpoint message
397 bool CSyncCheckpoint::CheckSignature()
400 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
401 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
402 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
403 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
405 // Now unserialize the data
406 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
407 sMsg >> *(CUnsignedSyncCheckpoint*)this;
411 // ppcoin: process synchronized checkpoint
412 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
414 if (!CheckSignature())
417 LOCK(Checkpoints::cs_hashSyncCheckpoint);
418 if (!mapBlockIndex.count(hashCheckpoint))
420 // We haven't received the checkpoint chain, keep the checkpoint as pending
421 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
422 Checkpoints::checkpointMessagePending = *this;
423 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
424 // Ask this guy to fill in what we're missing
427 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
428 // ask directly as well in case rejected earlier by duplicate
429 // proof-of-stake because getblocks may not get it this time
430 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
435 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
439 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
440 if (!pindexCheckpoint->IsInMainChain())
442 // checkpoint chain received but not yet main chain
444 if (!block.ReadFromDisk(pindexCheckpoint))
445 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
446 if (!block.SetBestChain(txdb, pindexCheckpoint))
448 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
449 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
454 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
455 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
456 Checkpoints::checkpointMessage = *this;
457 Checkpoints::hashPendingCheckpoint = 0;
458 Checkpoints::checkpointMessagePending.SetNull();
459 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());