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) )
31 ( 160000, std::make_pair(uint256("0x000000000001cb1133043d38d077c0e93f66c8b2566779f10f182137d1e34a68"), 1425150237) )
32 ( 200000, std::make_pair(uint256("0x0000000000029f8bbf66e6ea6f3e5db55009404aae0fe395a53dd33142b2bff2"), 1441127233) )
35 // TestNet has no checkpoints
36 static MapCheckpoints mapCheckpointsTestnet =
37 boost::assign::map_list_of
38 ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
41 bool CheckHardened(int nHeight, const uint256& hash)
43 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
45 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
46 if (i == checkpoints.end()) return true;
47 return hash == i->second.first;
50 int GetTotalBlocksEstimate()
52 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
54 return checkpoints.rbegin()->first;
57 unsigned int GetLastCheckpointTime()
59 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
61 return checkpoints.rbegin()->second.second;
64 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
66 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
68 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
70 const uint256& hash = i.second.first;
71 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
72 if (t != mapBlockIndex.end())
78 // ppcoin: synchronized checkpoint (centrally broadcasted)
79 uint256 hashSyncCheckpoint = 0;
80 uint256 hashPendingCheckpoint = 0;
81 CSyncCheckpoint checkpointMessage;
82 CSyncCheckpoint checkpointMessagePending;
83 uint256 hashInvalidCheckpoint = 0;
84 CCriticalSection cs_hashSyncCheckpoint;
86 // ppcoin: get last synchronized checkpoint
87 CBlockIndex* GetLastSyncCheckpoint()
89 LOCK(cs_hashSyncCheckpoint);
90 if (!mapBlockIndex.count(hashSyncCheckpoint))
91 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
93 return mapBlockIndex[hashSyncCheckpoint];
97 // ppcoin: only descendant of current sync-checkpoint is allowed
98 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
100 if (!mapBlockIndex.count(hashSyncCheckpoint))
101 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
102 if (!mapBlockIndex.count(hashCheckpoint))
103 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
105 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
106 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
108 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
110 // Received an older checkpoint, trace back from current checkpoint
111 // to the same height of the received checkpoint to verify
112 // that current checkpoint should be a descendant block
113 CBlockIndex* pindex = pindexSyncCheckpoint;
114 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
115 if (!(pindex = pindex->pprev))
116 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
117 if (pindex->GetBlockHash() != hashCheckpoint)
119 hashInvalidCheckpoint = hashCheckpoint;
120 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
122 return false; // ignore older checkpoint
125 // Received checkpoint should be a descendant block of the current
126 // checkpoint. Trace back to the same height of current checkpoint
128 CBlockIndex* pindex = pindexCheckpointRecv;
129 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
130 if (!(pindex = pindex->pprev))
131 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
132 if (pindex->GetBlockHash() != hashSyncCheckpoint)
134 hashInvalidCheckpoint = hashCheckpoint;
135 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
140 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
144 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
147 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
149 if (!txdb.TxnCommit())
150 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
156 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
160 bool AcceptPendingSyncCheckpoint()
162 LOCK(cs_hashSyncCheckpoint);
163 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
165 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
167 hashPendingCheckpoint = 0;
168 checkpointMessagePending.SetNull();
173 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
174 if (!pindexCheckpoint->IsInMainChain())
177 if (!block.ReadFromDisk(pindexCheckpoint))
178 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
179 if (!block.SetBestChain(txdb, pindexCheckpoint))
181 hashInvalidCheckpoint = hashPendingCheckpoint;
182 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
189 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
190 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
191 hashPendingCheckpoint = 0;
192 checkpointMessage = checkpointMessagePending;
193 checkpointMessagePending.SetNull();
194 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
195 // relay the checkpoint
196 if (!checkpointMessage.IsNull())
198 BOOST_FOREACH(CNode* pnode, vNodes)
199 checkpointMessage.RelayTo(pnode);
206 // Automatically select a suitable sync-checkpoint
207 uint256 AutoSelectSyncCheckpoint()
209 const CBlockIndex *pindex = pindexBest;
210 // Search backward for a block within max span and maturity window
211 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
212 pindex = pindex->pprev;
213 return pindex->GetBlockHash();
216 // Check against synchronized checkpoint
217 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
219 if (fTestNet) return true; // Testnet has no checkpoints
220 int nHeight = pindexPrev->nHeight + 1;
222 LOCK(cs_hashSyncCheckpoint);
223 // sync-checkpoint should always be accepted block
224 assert(mapBlockIndex.count(hashSyncCheckpoint));
225 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
227 if (nHeight > pindexSync->nHeight)
229 // trace back to same height as sync-checkpoint
230 const CBlockIndex* pindex = pindexPrev;
231 while (pindex->nHeight > pindexSync->nHeight)
232 if (!(pindex = pindex->pprev))
233 return error("CheckSync: pprev null - block index structure failure");
234 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
235 return false; // only descendant of sync-checkpoint can pass check
237 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
238 return false; // same height with sync-checkpoint
239 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
240 return false; // lower height than sync-checkpoint
244 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
246 LOCK(cs_hashSyncCheckpoint);
247 if (hashPendingCheckpoint == 0)
249 if (hashBlock == hashPendingCheckpoint)
251 if (mapOrphanBlocks.count(hashPendingCheckpoint)
252 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
257 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
258 bool ResetSyncCheckpoint()
260 LOCK(cs_hashSyncCheckpoint);
261 const uint256& hash = mapCheckpoints.rbegin()->second.first;
262 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
264 // checkpoint block accepted but not yet in main chain
265 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
268 if (!block.ReadFromDisk(mapBlockIndex[hash]))
269 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
270 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
272 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
280 else if(!mapBlockIndex.count(hash))
282 // checkpoint block not yet accepted
283 hashPendingCheckpoint = hash;
284 checkpointMessagePending.SetNull();
285 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
288 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
290 const uint256& hash = i.second.first;
291 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
293 if (!WriteSyncCheckpoint(hash))
294 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
295 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
303 void AskForPendingSyncCheckpoint(CNode* pfrom)
305 LOCK(cs_hashSyncCheckpoint);
306 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
307 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
310 bool SetCheckpointPrivKey(std::string strPrivKey)
312 // Test signing a sync-checkpoint with genesis block
313 CSyncCheckpoint checkpoint;
314 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
315 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
316 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
317 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
319 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
321 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
322 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
325 // Test signing successful, proceed
326 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
330 bool SendSyncCheckpoint(uint256 hashCheckpoint)
332 CSyncCheckpoint checkpoint;
333 checkpoint.hashCheckpoint = hashCheckpoint;
334 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
335 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
336 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
338 if (CSyncCheckpoint::strMasterPrivKey.empty())
339 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
340 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
342 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
343 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
344 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
346 if(!checkpoint.ProcessSyncCheckpoint(NULL))
348 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
355 BOOST_FOREACH(CNode* pnode, vNodes)
356 checkpoint.RelayTo(pnode);
361 // Is the sync-checkpoint outside maturity window?
362 bool IsMatureSyncCheckpoint()
364 LOCK(cs_hashSyncCheckpoint);
365 // sync-checkpoint should always be accepted block
366 assert(mapBlockIndex.count(hashSyncCheckpoint));
367 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
368 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
369 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
373 // ppcoin: sync-checkpoint master key
374 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
376 std::string CSyncCheckpoint::strMasterPrivKey = "";
378 // ppcoin: verify signature of sync-checkpoint message
379 bool CSyncCheckpoint::CheckSignature()
382 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
383 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
384 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
385 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
387 // Now unserialize the data
388 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
389 sMsg >> *(CUnsignedSyncCheckpoint*)this;
393 // process synchronized checkpoint
394 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
396 if (!CheckSignature())
399 LOCK(Checkpoints::cs_hashSyncCheckpoint);
400 if (!mapBlockIndex.count(hashCheckpoint))
402 // We haven't received the checkpoint chain, keep the checkpoint as pending
403 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
404 Checkpoints::checkpointMessagePending = *this;
405 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
406 // Ask this guy to fill in what we're missing
409 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
410 // ask directly as well in case rejected earlier by duplicate
411 // proof-of-stake because getblocks may not get it this time
412 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
417 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
421 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
422 if (!pindexCheckpoint->IsInMainChain())
424 // checkpoint chain received but not yet main chain
426 if (!block.ReadFromDisk(pindexCheckpoint))
427 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
428 if (!block.SetBestChain(txdb, pindexCheckpoint))
430 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
431 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
439 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
440 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
441 Checkpoints::checkpointMessage = *this;
442 Checkpoints::hashPendingCheckpoint = 0;
443 Checkpoints::checkpointMessagePending.SetNull();
444 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());