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 ( 13560, std::make_pair(uint256("0xa1591a0fcbf11f282d671581edb9f0aadcd06fee69761081e0a3245914c13729"), 1364674052) )
29 ( 143990, std::make_pair(uint256("0x00000000001ff5c3940a9f73ad4a990f64955179bde0f743c76dbf0031429efc"), 1418953493) )
30 ( 149000, std::make_pair(uint256("0x7a24acfcadcf43054e7f7d9f273522c0dfc5791ba4006e0273e7521a8d36c525"), 1420872125) )
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)
142 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
145 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
147 if (!txdb.TxnCommit())
148 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
154 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
158 bool AcceptPendingSyncCheckpoint()
160 LOCK(cs_hashSyncCheckpoint);
161 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
163 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
165 hashPendingCheckpoint = 0;
166 checkpointMessagePending.SetNull();
171 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
172 if (!pindexCheckpoint->IsInMainChain())
175 if (!block.ReadFromDisk(pindexCheckpoint))
176 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
177 if (!block.SetBestChain(txdb, pindexCheckpoint))
179 hashInvalidCheckpoint = hashPendingCheckpoint;
180 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
187 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
188 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
189 hashPendingCheckpoint = 0;
190 checkpointMessage = checkpointMessagePending;
191 checkpointMessagePending.SetNull();
192 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
193 // relay the checkpoint
194 if (!checkpointMessage.IsNull())
196 BOOST_FOREACH(CNode* pnode, vNodes)
197 checkpointMessage.RelayTo(pnode);
204 // Automatically select a suitable sync-checkpoint
205 uint256 AutoSelectSyncCheckpoint()
207 const CBlockIndex *pindex = pindexBest;
208 // Search backward for a block within max span and maturity window
209 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
210 pindex = pindex->pprev;
211 return pindex->GetBlockHash();
214 // Check against synchronized checkpoint
215 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
217 if (fTestNet) return true; // Testnet has no checkpoints
218 int nHeight = pindexPrev->nHeight + 1;
220 LOCK(cs_hashSyncCheckpoint);
221 // sync-checkpoint should always be accepted block
222 assert(mapBlockIndex.count(hashSyncCheckpoint));
223 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
225 if (nHeight > pindexSync->nHeight)
227 // trace back to same height as sync-checkpoint
228 const CBlockIndex* pindex = pindexPrev;
229 while (pindex->nHeight > pindexSync->nHeight)
230 if (!(pindex = pindex->pprev))
231 return error("CheckSync: pprev null - block index structure failure");
232 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
233 return false; // only descendant of sync-checkpoint can pass check
235 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
236 return false; // same height with sync-checkpoint
237 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
238 return false; // lower height than sync-checkpoint
242 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
244 LOCK(cs_hashSyncCheckpoint);
245 if (hashPendingCheckpoint == 0)
247 if (hashBlock == hashPendingCheckpoint)
249 if (mapOrphanBlocks.count(hashPendingCheckpoint)
250 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
255 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
256 bool ResetSyncCheckpoint()
258 LOCK(cs_hashSyncCheckpoint);
259 const uint256& hash = mapCheckpoints.rbegin()->second.first;
260 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
262 // checkpoint block accepted but not yet in main chain
263 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
266 if (!block.ReadFromDisk(mapBlockIndex[hash]))
267 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
268 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
270 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
278 else if(!mapBlockIndex.count(hash))
280 // checkpoint block not yet accepted
281 hashPendingCheckpoint = hash;
282 checkpointMessagePending.SetNull();
283 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
286 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
288 const uint256& hash = i.second.first;
289 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
291 if (!WriteSyncCheckpoint(hash))
292 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
293 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
301 void AskForPendingSyncCheckpoint(CNode* pfrom)
303 LOCK(cs_hashSyncCheckpoint);
304 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
305 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
308 bool SetCheckpointPrivKey(std::string strPrivKey)
310 // Test signing a sync-checkpoint with genesis block
311 CSyncCheckpoint checkpoint;
312 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
313 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
314 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
315 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
317 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
319 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
320 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
323 // Test signing successful, proceed
324 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
328 bool SendSyncCheckpoint(uint256 hashCheckpoint)
330 CSyncCheckpoint checkpoint;
331 checkpoint.hashCheckpoint = hashCheckpoint;
332 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
333 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
334 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
336 if (CSyncCheckpoint::strMasterPrivKey.empty())
337 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
338 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
340 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
341 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
342 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
344 if(!checkpoint.ProcessSyncCheckpoint(NULL))
346 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
353 BOOST_FOREACH(CNode* pnode, vNodes)
354 checkpoint.RelayTo(pnode);
359 // Is the sync-checkpoint outside maturity window?
360 bool IsMatureSyncCheckpoint()
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 (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
367 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
371 // ppcoin: sync-checkpoint master key
372 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
374 std::string CSyncCheckpoint::strMasterPrivKey = "";
376 // ppcoin: verify signature of sync-checkpoint message
377 bool CSyncCheckpoint::CheckSignature()
380 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
381 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
382 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
383 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
385 // Now unserialize the data
386 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
387 sMsg >> *(CUnsignedSyncCheckpoint*)this;
391 // process synchronized checkpoint
392 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
394 if (!CheckSignature())
397 LOCK(Checkpoints::cs_hashSyncCheckpoint);
398 if (!mapBlockIndex.count(hashCheckpoint))
400 // We haven't received the checkpoint chain, keep the checkpoint as pending
401 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
402 Checkpoints::checkpointMessagePending = *this;
403 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
404 // Ask this guy to fill in what we're missing
407 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
408 // ask directly as well in case rejected earlier by duplicate
409 // proof-of-stake because getblocks may not get it this time
410 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
415 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
419 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
420 if (!pindexCheckpoint->IsInMainChain())
422 // checkpoint chain received but not yet main chain
424 if (!block.ReadFromDisk(pindexCheckpoint))
425 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
426 if (!block.SetBestChain(txdb, pindexCheckpoint))
428 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
429 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
437 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
438 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
439 Checkpoints::checkpointMessage = *this;
440 Checkpoints::hashPendingCheckpoint = 0;
441 Checkpoints::checkpointMessagePending.SetNull();
442 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());