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) )
33 ( 221047, std::make_pair(uint256("0xa28aef712e7aa0c285bfe29351ca21ed416689139e3063ef770fc826a8b9e9da"), 1449431646) )
36 // TestNet has no checkpoints
37 static MapCheckpoints mapCheckpointsTestnet =
38 boost::assign::map_list_of
39 ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
42 bool CheckHardened(int nHeight, const uint256& hash)
44 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
46 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
47 if (i == checkpoints.end()) return true;
48 return hash == i->second.first;
51 int GetTotalBlocksEstimate()
53 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
55 return checkpoints.rbegin()->first;
58 unsigned int GetLastCheckpointTime()
60 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
62 return checkpoints.rbegin()->second.second;
65 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
67 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
69 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
71 const uint256& hash = i.second.first;
72 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
73 if (t != mapBlockIndex.end())
79 // ppcoin: synchronized checkpoint (centrally broadcasted)
80 uint256 hashSyncCheckpoint = 0;
81 uint256 hashPendingCheckpoint = 0;
82 CSyncCheckpoint checkpointMessage;
83 CSyncCheckpoint checkpointMessagePending;
84 uint256 hashInvalidCheckpoint = 0;
85 CCriticalSection cs_hashSyncCheckpoint;
87 // ppcoin: get last synchronized checkpoint
88 CBlockIndex* GetLastSyncCheckpoint()
90 LOCK(cs_hashSyncCheckpoint);
91 if (!mapBlockIndex.count(hashSyncCheckpoint))
92 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
94 return mapBlockIndex[hashSyncCheckpoint];
98 // ppcoin: only descendant of current sync-checkpoint is allowed
99 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
101 if (!mapBlockIndex.count(hashSyncCheckpoint))
102 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
103 if (!mapBlockIndex.count(hashCheckpoint))
104 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
106 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
107 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
109 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
111 // Received an older checkpoint, trace back from current checkpoint
112 // to the same height of the received checkpoint to verify
113 // that current checkpoint should be a descendant block
114 CBlockIndex* pindex = pindexSyncCheckpoint;
115 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
116 if (!(pindex = pindex->pprev))
117 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
118 if (pindex->GetBlockHash() != hashCheckpoint)
120 hashInvalidCheckpoint = hashCheckpoint;
121 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
123 return false; // ignore older checkpoint
126 // Received checkpoint should be a descendant block of the current
127 // checkpoint. Trace back to the same height of current checkpoint
129 CBlockIndex* pindex = pindexCheckpointRecv;
130 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
131 if (!(pindex = pindex->pprev))
132 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
133 if (pindex->GetBlockHash() != hashSyncCheckpoint)
135 hashInvalidCheckpoint = hashCheckpoint;
136 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
141 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
145 if (!txdb.WriteSyncCheckpoint(hashCheckpoint))
148 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
150 if (!txdb.TxnCommit())
151 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
157 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
161 bool AcceptPendingSyncCheckpoint()
163 LOCK(cs_hashSyncCheckpoint);
164 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
166 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
168 hashPendingCheckpoint = 0;
169 checkpointMessagePending.SetNull();
174 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
175 if (!pindexCheckpoint->IsInMainChain())
178 if (!block.ReadFromDisk(pindexCheckpoint))
179 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
180 if (!block.SetBestChain(txdb, pindexCheckpoint))
182 hashInvalidCheckpoint = hashPendingCheckpoint;
183 return error("AcceptPendingSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
190 if (!WriteSyncCheckpoint(hashPendingCheckpoint))
191 return error("AcceptPendingSyncCheckpoint(): failed to write sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
192 hashPendingCheckpoint = 0;
193 checkpointMessage = checkpointMessagePending;
194 checkpointMessagePending.SetNull();
195 printf("AcceptPendingSyncCheckpoint : sync-checkpoint at %s\n", hashSyncCheckpoint.ToString().c_str());
196 // relay the checkpoint
197 if (!checkpointMessage.IsNull())
199 BOOST_FOREACH(CNode* pnode, vNodes)
200 checkpointMessage.RelayTo(pnode);
207 // Automatically select a suitable sync-checkpoint
208 uint256 AutoSelectSyncCheckpoint()
210 const CBlockIndex *pindex = pindexBest;
211 // Search backward for a block within max span and maturity window
212 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
213 pindex = pindex->pprev;
214 return pindex->GetBlockHash();
217 // Check against synchronized checkpoint
218 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
220 if (fTestNet) return true; // Testnet has no checkpoints
221 int nHeight = pindexPrev->nHeight + 1;
223 LOCK(cs_hashSyncCheckpoint);
224 // sync-checkpoint should always be accepted block
225 assert(mapBlockIndex.count(hashSyncCheckpoint));
226 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
228 if (nHeight > pindexSync->nHeight)
230 // trace back to same height as sync-checkpoint
231 const CBlockIndex* pindex = pindexPrev;
232 while (pindex->nHeight > pindexSync->nHeight)
233 if (!(pindex = pindex->pprev))
234 return error("CheckSync: pprev null - block index structure failure");
235 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
236 return false; // only descendant of sync-checkpoint can pass check
238 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
239 return false; // same height with sync-checkpoint
240 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
241 return false; // lower height than sync-checkpoint
245 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
247 LOCK(cs_hashSyncCheckpoint);
248 if (hashPendingCheckpoint == 0)
250 if (hashBlock == hashPendingCheckpoint)
252 if (mapOrphanBlocks.count(hashPendingCheckpoint)
253 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
258 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
259 bool ResetSyncCheckpoint()
261 LOCK(cs_hashSyncCheckpoint);
262 const uint256& hash = mapCheckpoints.rbegin()->second.first;
263 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
265 // checkpoint block accepted but not yet in main chain
266 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
269 if (!block.ReadFromDisk(mapBlockIndex[hash]))
270 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
271 if (!block.SetBestChain(txdb, mapBlockIndex[hash]))
273 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
281 else if(!mapBlockIndex.count(hash))
283 // checkpoint block not yet accepted
284 hashPendingCheckpoint = hash;
285 checkpointMessagePending.SetNull();
286 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
289 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
291 const uint256& hash = i.second.first;
292 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
294 if (!WriteSyncCheckpoint(hash))
295 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
296 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
304 void AskForPendingSyncCheckpoint(CNode* pfrom)
306 LOCK(cs_hashSyncCheckpoint);
307 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
308 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
311 bool SetCheckpointPrivKey(std::string strPrivKey)
313 // Test signing a sync-checkpoint with genesis block
314 CSyncCheckpoint checkpoint;
315 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
316 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
317 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
318 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
320 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
322 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
323 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
326 // Test signing successful, proceed
327 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
331 bool SendSyncCheckpoint(uint256 hashCheckpoint)
333 CSyncCheckpoint checkpoint;
334 checkpoint.hashCheckpoint = hashCheckpoint;
335 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
336 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
337 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
339 if (CSyncCheckpoint::strMasterPrivKey.empty())
340 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
341 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
343 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
344 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
345 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
347 if(!checkpoint.ProcessSyncCheckpoint(NULL))
349 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
356 BOOST_FOREACH(CNode* pnode, vNodes)
357 checkpoint.RelayTo(pnode);
362 // Is the sync-checkpoint outside maturity window?
363 bool IsMatureSyncCheckpoint()
365 LOCK(cs_hashSyncCheckpoint);
366 // sync-checkpoint should always be accepted block
367 assert(mapBlockIndex.count(hashSyncCheckpoint));
368 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
369 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
370 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
374 // ppcoin: sync-checkpoint master key
375 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
377 std::string CSyncCheckpoint::strMasterPrivKey = "";
379 // ppcoin: verify signature of sync-checkpoint message
380 bool CSyncCheckpoint::CheckSignature()
383 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
384 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
385 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
386 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
388 // Now unserialize the data
389 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
390 sMsg >> *(CUnsignedSyncCheckpoint*)this;
394 // process synchronized checkpoint
395 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
397 if (!CheckSignature())
400 LOCK(Checkpoints::cs_hashSyncCheckpoint);
401 if (!mapBlockIndex.count(hashCheckpoint))
403 // We haven't received the checkpoint chain, keep the checkpoint as pending
404 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
405 Checkpoints::checkpointMessagePending = *this;
406 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
407 // Ask this guy to fill in what we're missing
410 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
411 // ask directly as well in case rejected earlier by duplicate
412 // proof-of-stake because getblocks may not get it this time
413 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
418 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
422 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
423 if (!pindexCheckpoint->IsInMainChain())
425 // checkpoint chain received but not yet main chain
427 if (!block.ReadFromDisk(pindexCheckpoint))
428 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
429 if (!block.SetBestChain(txdb, pindexCheckpoint))
431 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
432 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
440 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
441 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
442 Checkpoints::checkpointMessage = *this;
443 Checkpoints::hashPendingCheckpoint = 0;
444 Checkpoints::checkpointMessagePending.SetNull();
445 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());