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 ( 68600, std::make_pair(uint256("0xb646b0562080ab9411f85d4b2a1ca8b197c67ae170c5e328406871b44233cb06"), 1389867276) )
31 // TestNet has no checkpoints
32 static MapCheckpoints mapCheckpointsTestnet =
33 boost::assign::map_list_of
34 ( 0, std::make_pair(hashGenesisBlockTestNet, 1360105017) )
37 bool CheckHardened(int nHeight, const uint256& hash)
39 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
41 MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
42 if (i == checkpoints.end()) return true;
43 return hash == i->second.first;
46 int GetTotalBlocksEstimate()
48 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
50 return checkpoints.rbegin()->first;
53 int GetLastCheckpointTime()
55 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
57 return checkpoints.rbegin()->second.second;
60 CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
62 MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
64 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
66 const uint256& hash = i.second.first;
67 std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
68 if (t != mapBlockIndex.end())
74 // ppcoin: synchronized checkpoint (centrally broadcasted)
75 uint256 hashSyncCheckpoint = 0;
76 uint256 hashPendingCheckpoint = 0;
77 CSyncCheckpoint checkpointMessage;
78 CSyncCheckpoint checkpointMessagePending;
79 uint256 hashInvalidCheckpoint = 0;
80 CCriticalSection cs_hashSyncCheckpoint;
82 // ppcoin: get last synchronized checkpoint
83 CBlockIndex* GetLastSyncCheckpoint()
85 LOCK(cs_hashSyncCheckpoint);
86 if (!mapBlockIndex.count(hashSyncCheckpoint))
87 error("GetSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
89 return mapBlockIndex[hashSyncCheckpoint];
93 // ppcoin: only descendant of current sync-checkpoint is allowed
94 bool ValidateSyncCheckpoint(uint256 hashCheckpoint)
96 if (!mapBlockIndex.count(hashSyncCheckpoint))
97 return error("ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s", hashSyncCheckpoint.ToString().c_str());
98 if (!mapBlockIndex.count(hashCheckpoint))
99 return error("ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s", hashCheckpoint.ToString().c_str());
101 CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];
102 CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];
104 if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)
106 // Received an older checkpoint, trace back from current checkpoint
107 // to the same height of the received checkpoint to verify
108 // that current checkpoint should be a descendant block
109 CBlockIndex* pindex = pindexSyncCheckpoint;
110 while (pindex->nHeight > pindexCheckpointRecv->nHeight)
111 if (!(pindex = pindex->pprev))
112 return error("ValidateSyncCheckpoint: pprev null - block index structure failure");
113 if (pindex->GetBlockHash() != hashCheckpoint)
115 hashInvalidCheckpoint = hashCheckpoint;
116 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is conflicting with current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
118 return false; // ignore older checkpoint
121 // Received checkpoint should be a descendant block of the current
122 // checkpoint. Trace back to the same height of current checkpoint
124 CBlockIndex* pindex = pindexCheckpointRecv;
125 while (pindex->nHeight > pindexSyncCheckpoint->nHeight)
126 if (!(pindex = pindex->pprev))
127 return error("ValidateSyncCheckpoint: pprev2 null - block index structure failure");
128 if (pindex->GetBlockHash() != hashSyncCheckpoint)
130 hashInvalidCheckpoint = hashCheckpoint;
131 return error("ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());
136 bool WriteSyncCheckpoint(const uint256& hashCheckpoint)
138 pblocktree->TxnBegin();
139 if (!pblocktree->WriteSyncCheckpoint(hashCheckpoint))
141 pblocktree->TxnAbort();
142 return error("WriteSyncCheckpoint(): failed to write to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
144 if (!pblocktree->TxnCommit())
145 return error("WriteSyncCheckpoint(): failed to commit to db sync checkpoint %s", hashCheckpoint.ToString().c_str());
147 Checkpoints::hashSyncCheckpoint = hashCheckpoint;
151 bool AcceptPendingSyncCheckpoint()
153 LOCK(cs_hashSyncCheckpoint);
154 if (hashPendingCheckpoint != 0 && mapBlockIndex.count(hashPendingCheckpoint))
156 if (!ValidateSyncCheckpoint(hashPendingCheckpoint))
158 hashPendingCheckpoint = 0;
159 checkpointMessagePending.SetNull();
163 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashPendingCheckpoint];
164 if (!pindexCheckpoint->IsInMainChain())
167 if (!block.ReadFromDisk(pindexCheckpoint))
168 return error("AcceptPendingSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashPendingCheckpoint.ToString().c_str());
169 if (!SetBestChain(pindexCheckpoint))
171 hashInvalidCheckpoint = hashPendingCheckpoint;
172 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 const CBlockIndex *pindex = pindexBest;
197 // Search backward for a block within max span and maturity window
198 while (pindex->pprev && (pindex->GetBlockTime() + CHECKPOINT_MAX_SPAN > pindexBest->GetBlockTime() || pindex->nHeight + 8 > pindexBest->nHeight))
199 pindex = pindex->pprev;
200 return pindex->GetBlockHash();
203 // Check against synchronized checkpoint
204 bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)
206 if (fTestNet) return true; // Testnet has no checkpoints
207 int nHeight = pindexPrev->nHeight + 1;
209 LOCK(cs_hashSyncCheckpoint);
210 // sync-checkpoint should always be accepted block
211 assert(mapBlockIndex.count(hashSyncCheckpoint));
212 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
214 if (nHeight > pindexSync->nHeight)
216 // trace back to same height as sync-checkpoint
217 const CBlockIndex* pindex = pindexPrev;
218 while (pindex->nHeight > pindexSync->nHeight)
219 if (!(pindex = pindex->pprev))
220 return error("CheckSync: pprev null - block index structure failure");
221 if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)
222 return false; // only descendant of sync-checkpoint can pass check
224 if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)
225 return false; // same height with sync-checkpoint
226 if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))
227 return false; // lower height than sync-checkpoint
231 bool WantedByPendingSyncCheckpoint(uint256 hashBlock)
233 LOCK(cs_hashSyncCheckpoint);
234 if (hashPendingCheckpoint == 0)
236 if (hashBlock == hashPendingCheckpoint)
238 if (mapOrphanBlocks.count(hashPendingCheckpoint)
239 && hashBlock == WantedByOrphan(mapOrphanBlocks[hashPendingCheckpoint]))
244 // ppcoin: reset synchronized checkpoint to last hardened checkpoint
245 bool ResetSyncCheckpoint()
247 LOCK(cs_hashSyncCheckpoint);
248 const uint256& hash = mapCheckpoints.rbegin()->second.first;
249 if (mapBlockIndex.count(hash) && !mapBlockIndex[hash]->IsInMainChain())
251 // checkpoint block accepted but not yet in main chain
252 printf("ResetSyncCheckpoint: SetBestChain to hardened checkpoint %s\n", hash.ToString().c_str());
254 if (!block.ReadFromDisk(mapBlockIndex[hash]))
255 return error("ResetSyncCheckpoint: ReadFromDisk failed for hardened checkpoint %s", hash.ToString().c_str());
256 if (!SetBestChain(mapBlockIndex[hash]))
258 return error("ResetSyncCheckpoint: SetBestChain failed for hardened checkpoint %s", hash.ToString().c_str());
261 else if(!mapBlockIndex.count(hash))
263 // checkpoint block not yet accepted
264 hashPendingCheckpoint = hash;
265 checkpointMessagePending.SetNull();
266 printf("ResetSyncCheckpoint: pending for sync-checkpoint %s\n", hashPendingCheckpoint.ToString().c_str());
269 BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
271 const uint256& hash = i.second.first;
272 if (mapBlockIndex.count(hash) && mapBlockIndex[hash]->IsInMainChain())
274 if (!WriteSyncCheckpoint(hash))
275 return error("ResetSyncCheckpoint: failed to write sync checkpoint %s", hash.ToString().c_str());
276 printf("ResetSyncCheckpoint: sync-checkpoint reset to %s\n", hashSyncCheckpoint.ToString().c_str());
284 void AskForPendingSyncCheckpoint(CNode* pfrom)
286 LOCK(cs_hashSyncCheckpoint);
287 if (pfrom && hashPendingCheckpoint != 0 && (!mapBlockIndex.count(hashPendingCheckpoint)) && (!mapOrphanBlocks.count(hashPendingCheckpoint)))
288 pfrom->AskFor(CInv(MSG_BLOCK, hashPendingCheckpoint));
291 bool SetCheckpointPrivKey(std::string strPrivKey)
293 // Test signing a sync-checkpoint with genesis block
294 CSyncCheckpoint checkpoint;
295 checkpoint.hashCheckpoint = !fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet;
296 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
297 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
298 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
300 std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
302 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
303 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
306 // Test signing successful, proceed
307 CSyncCheckpoint::strMasterPrivKey = strPrivKey;
311 bool SendSyncCheckpoint(uint256 hashCheckpoint)
313 CSyncCheckpoint checkpoint;
314 checkpoint.hashCheckpoint = hashCheckpoint;
315 CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
316 sMsg << (CUnsignedSyncCheckpoint)checkpoint;
317 checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
319 if (CSyncCheckpoint::strMasterPrivKey.empty())
320 return error("SendSyncCheckpoint: Checkpoint master key unavailable.");
321 std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
323 key.SetPrivKey(CPrivKey(vchPrivKey.begin(), vchPrivKey.end())); // if key is not correct openssl may crash
324 if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
325 return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
327 if(!checkpoint.ProcessSyncCheckpoint(NULL))
329 printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
336 BOOST_FOREACH(CNode* pnode, vNodes)
337 checkpoint.RelayTo(pnode);
342 // Is the sync-checkpoint outside maturity window?
343 bool IsMatureSyncCheckpoint()
345 LOCK(cs_hashSyncCheckpoint);
346 // sync-checkpoint should always be accepted block
347 assert(mapBlockIndex.count(hashSyncCheckpoint));
348 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
349 return (nBestHeight >= pindexSync->nHeight + nCoinbaseMaturity ||
350 pindexSync->GetBlockTime() + nStakeMinAge < GetAdjustedTime());
353 // Is the sync-checkpoint too old?
354 bool IsSyncCheckpointTooOld(unsigned int nSeconds)
356 LOCK(cs_hashSyncCheckpoint);
357 // sync-checkpoint should always be accepted block
358 assert(mapBlockIndex.count(hashSyncCheckpoint));
359 const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];
360 return (pindexSync->GetBlockTime() + nSeconds < GetAdjustedTime());
364 // ppcoin: sync-checkpoint master key
365 const std::string CSyncCheckpoint::strMasterPubKey = "04a51b735f816de4ec3f891d5b38bbc91e1f7245c7c08d17990760b86b4d8fc3910a850ffecf73bfa8886f01739a0c4c4322201282d07b6e48ce931cc92af94850";
367 std::string CSyncCheckpoint::strMasterPrivKey = "";
369 // ppcoin: verify signature of sync-checkpoint message
370 bool CSyncCheckpoint::CheckSignature()
373 if (!key.SetPubKey(ParseHex(CSyncCheckpoint::strMasterPubKey)))
374 return error("CSyncCheckpoint::CheckSignature() : SetPubKey failed");
375 if (!key.Verify(Hash(vchMsg.begin(), vchMsg.end()), vchSig))
376 return error("CSyncCheckpoint::CheckSignature() : verify signature failed");
378 // Now unserialize the data
379 CDataStream sMsg(vchMsg, SER_NETWORK, PROTOCOL_VERSION);
380 sMsg >> *(CUnsignedSyncCheckpoint*)this;
384 // ppcoin: process synchronized checkpoint
385 bool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)
387 if (!CheckSignature())
390 LOCK(Checkpoints::cs_hashSyncCheckpoint);
391 if (!mapBlockIndex.count(hashCheckpoint))
393 // We haven't received the checkpoint chain, keep the checkpoint as pending
394 Checkpoints::hashPendingCheckpoint = hashCheckpoint;
395 Checkpoints::checkpointMessagePending = *this;
396 printf("ProcessSyncCheckpoint: pending for sync-checkpoint %s\n", hashCheckpoint.ToString().c_str());
397 // Ask this guy to fill in what we're missing
400 pfrom->PushGetBlocks(pindexBest, hashCheckpoint);
401 // ask directly as well in case rejected earlier by duplicate
402 // proof-of-stake because getblocks may not get it this time
403 pfrom->AskFor(CInv(MSG_BLOCK, mapOrphanBlocks.count(hashCheckpoint)? WantedByOrphan(mapOrphanBlocks[hashCheckpoint]) : hashCheckpoint));
408 if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))
411 CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];
412 if (!pindexCheckpoint->IsInMainChain())
414 // checkpoint chain received but not yet main chain
416 if (!block.ReadFromDisk(pindexCheckpoint))
417 return error("ProcessSyncCheckpoint: ReadFromDisk failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
418 if (!SetBestChain(pindexCheckpoint))
420 Checkpoints::hashInvalidCheckpoint = hashCheckpoint;
421 return error("ProcessSyncCheckpoint: SetBestChain failed for sync checkpoint %s", hashCheckpoint.ToString().c_str());
425 if (!Checkpoints::WriteSyncCheckpoint(hashCheckpoint))
426 return error("ProcessSyncCheckpoint(): failed to write sync checkpoint %s", hashCheckpoint.ToString().c_str());
427 Checkpoints::checkpointMessage = *this;
428 Checkpoints::hashPendingCheckpoint = 0;
429 Checkpoints::checkpointMessagePending.SetNull();
430 printf("ProcessSyncCheckpoint: sync-checkpoint at %s\n", hashCheckpoint.ToString().c_str());