1 // Copyright (c) 2009-2018 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <checkpoints.h>
6 
7 #include <chain.h>
8 #include <chainparams.h>
9 #include <reverse_iterator.h>
10 #include <validation.h>
11 
12 #include <stdint.h>
13 
14 namespace Checkpoints {
15 
CheckHardened(int nHeight,const uint256 & hash,const CCheckpointData & data)16     bool CheckHardened(int nHeight, const uint256& hash, const CCheckpointData& data)
17     {
18         const MapCheckpoints& checkpoints = data.mapCheckpoints;
19 
20         MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
21         if (i == checkpoints.end()) return true;
22         return hash == i->second;
23     }
24 
25     //! Returns last CBlockIndex* that is a checkpoint
GetLastCheckpoint(const CCheckpointData & data)26     CBlockIndex* GetLastCheckpoint(const CCheckpointData& data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
27     {
28         const MapCheckpoints& checkpoints = data.mapCheckpoints;
29 
30         for (const MapCheckpoints::value_type& i : reverse_iterate(checkpoints))
31         {
32             const uint256& hash = i.second;
33             CBlockIndex* pindex = LookupBlockIndex(hash);
34             if (pindex) {
35                 return pindex;
36             }
37         }
38         return nullptr;
39     }
40 
41     // Automatically select a suitable sync-checkpoint
AutoSelectSyncCheckpoint()42     const CBlockIndex* AutoSelectSyncCheckpoint()
43     {
44         const CBlockIndex *pindexBest = ::ChainActive().Tip();
45         const CBlockIndex *pindex = pindexBest;
46         // Search backward for a block within max span and maturity window
47         int checkpointSpan = Params().GetConsensus().CheckpointSpan(pindexBest->nHeight);
48         while (pindex->pprev && pindex->nHeight + checkpointSpan > pindexBest->nHeight)
49             pindex = pindex->pprev;
50         return pindex;
51     }
52 
53     // Check against synchronized checkpoint
CheckSync(int nHeight)54     bool CheckSync(int nHeight)
55     {
56         const CBlockIndex* pindexSync;
57         if(nHeight)
58             pindexSync = AutoSelectSyncCheckpoint();
59 
60         if(nHeight && nHeight <= pindexSync->nHeight)
61             return false;
62         return true;
63     }
64 } // namespace Checkpoints
65