Branch data     Line data    Source code 
       1                 :             : // Copyright (c) 2018-2022 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 <index/blockfilterindex.h>
       6                 :             : 
       7                 :             : #include <blockfilter.h>
       8                 :             : #include <chain.h>
       9                 :             : #include <common/args.h>
      10                 :             : #include <dbwrapper.h>
      11                 :             : #include <flatfile.h>
      12                 :             : #include <hash.h>
      13                 :             : #include <index/base.h>
      14                 :             : #include <interfaces/chain.h>
      15                 :             : #include <interfaces/types.h>
      16                 :             : #include <logging.h>
      17                 :             : #include <serialize.h>
      18                 :             : #include <streams.h>
      19                 :             : #include <sync.h>
      20                 :             : #include <uint256.h>
      21                 :             : #include <util/check.h>
      22                 :             : #include <util/fs.h>
      23                 :             : #include <util/hasher.h>
      24                 :             : #include <util/syserror.h>
      25                 :             : 
      26                 :             : #include <cerrno>
      27                 :             : #include <exception>
      28                 :             : #include <ios>
      29                 :             : #include <map>
      30                 :             : #include <optional>
      31                 :             : #include <span>
      32                 :             : #include <stdexcept>
      33                 :             : #include <string>
      34                 :             : #include <tuple>
      35                 :             : #include <utility>
      36                 :             : #include <vector>
      37                 :             : 
      38                 :             : /* The index database stores three items for each block: the disk location of the encoded filter,
      39                 :             :  * its dSHA256 hash, and the header. Those belonging to blocks on the active chain are indexed by
      40                 :             :  * height, and those belonging to blocks that have been reorganized out of the active chain are
      41                 :             :  * indexed by block hash. This ensures that filter data for any block that becomes part of the
      42                 :             :  * active chain can always be retrieved, alleviating timing concerns.
      43                 :             :  *
      44                 :             :  * The filters themselves are stored in flat files and referenced by the LevelDB entries. This
      45                 :             :  * minimizes the amount of data written to LevelDB and keeps the database values constant size. The
      46                 :             :  * disk location of the next block filter to be written (represented as a FlatFilePos) is stored
      47                 :             :  * under the DB_FILTER_POS key.
      48                 :             :  *
      49                 :             :  * Keys for the height index have the type [DB_BLOCK_HEIGHT, uint32 (BE)]. The height is represented
      50                 :             :  * as big-endian so that sequential reads of filters by height are fast.
      51                 :             :  * Keys for the hash index have the type [DB_BLOCK_HASH, uint256].
      52                 :             :  */
      53                 :             : constexpr uint8_t DB_BLOCK_HASH{'s'};
      54                 :             : constexpr uint8_t DB_BLOCK_HEIGHT{'t'};
      55                 :             : constexpr uint8_t DB_FILTER_POS{'P'};
      56                 :             : 
      57                 :             : constexpr unsigned int MAX_FLTR_FILE_SIZE = 0x1000000; // 16 MiB
      58                 :             : /** The pre-allocation chunk size for fltr?????.dat files */
      59                 :             : constexpr unsigned int FLTR_FILE_CHUNK_SIZE = 0x100000; // 1 MiB
      60                 :             : /** Maximum size of the cfheaders cache
      61                 :             :  *  We have a limit to prevent a bug in filling this cache
      62                 :             :  *  potentially turning into an OOM. At 2000 entries, this cache
      63                 :             :  *  is big enough for a 2,000,000 length block chain, which
      64                 :             :  *  we should be enough until ~2047. */
      65                 :             : constexpr size_t CF_HEADERS_CACHE_MAX_SZ{2000};
      66                 :             : 
      67                 :             : namespace {
      68                 :             : 
      69                 :        1078 : struct DBVal {
      70                 :             :     uint256 hash;
      71                 :             :     uint256 header;
      72                 :             :     FlatFilePos pos;
      73                 :             : 
      74                 :         811 :     SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
      75                 :             : };
      76                 :             : 
      77                 :             : struct DBHeightKey {
      78                 :             :     int height;
      79                 :             : 
      80         [ +  - ]:         547 :     explicit DBHeightKey(int height_in) : height(height_in) {}
      81                 :             : 
      82                 :             :     template<typename Stream>
      83                 :         982 :     void Serialize(Stream& s) const
      84                 :             :     {
      85                 :         982 :         ser_writedata8(s, DB_BLOCK_HEIGHT);
      86                 :         982 :         ser_writedata32be(s, height);
      87                 :         982 :     }
      88                 :             : 
      89                 :             :     template<typename Stream>
      90                 :         443 :     void Unserialize(Stream& s)
      91                 :             :     {
      92                 :         443 :         const uint8_t prefix{ser_readdata8(s)};
      93         [ -  + ]:         443 :         if (prefix != DB_BLOCK_HEIGHT) {
      94         [ #  # ]:           0 :             throw std::ios_base::failure("Invalid format for block filter index DB height key");
      95                 :             :         }
      96                 :         443 :         height = ser_readdata32be(s);
      97                 :         443 :     }
      98                 :             : };
      99                 :             : 
     100                 :             : struct DBHashKey {
     101                 :             :     uint256 hash;
     102                 :             : 
     103         [ +  - ]:          10 :     explicit DBHashKey(const uint256& hash_in) : hash(hash_in) {}
     104                 :             : 
     105                 :          25 :     SERIALIZE_METHODS(DBHashKey, obj) {
     106                 :          25 :         uint8_t prefix{DB_BLOCK_HASH};
     107                 :          25 :         READWRITE(prefix);
     108         [ -  + ]:          25 :         if (prefix != DB_BLOCK_HASH) {
     109         [ #  # ]:           0 :             throw std::ios_base::failure("Invalid format for block filter index DB hash key");
     110                 :             :         }
     111                 :             : 
     112                 :          25 :         READWRITE(obj.hash);
     113                 :          25 :     }
     114                 :             : };
     115                 :             : 
     116                 :             : }; // namespace
     117                 :             : 
     118                 :             : static std::map<BlockFilterType, BlockFilterIndex> g_filter_indexes;
     119                 :             : 
     120                 :           4 : BlockFilterIndex::BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain, BlockFilterType filter_type,
     121                 :           4 :                                    size_t n_cache_size, bool f_memory, bool f_wipe)
     122         [ +  - ]:           4 :     : BaseIndex(std::move(chain), BlockFilterTypeName(filter_type) + " block filter index")
     123   [ +  -  +  - ]:           8 :     , m_filter_type(filter_type)
     124                 :             : {
     125         [ +  - ]:           4 :     const std::string& filter_name = BlockFilterTypeName(filter_type);
     126   [ -  +  -  - ]:           4 :     if (filter_name.empty()) throw std::invalid_argument("unknown filter_type");
     127                 :             : 
     128   [ -  +  +  -  :          32 :     fs::path path = gArgs.GetDataDirNet() / "indexes" / "blockfilter" / fs::u8path(filter_name);
          +  -  +  -  +  
                      - ]
     129         [ +  - ]:           4 :     fs::create_directories(path);
     130                 :             : 
     131   [ +  -  +  -  :          12 :     m_db = std::make_unique<BaseIndex::DB>(path / "db", n_cache_size, f_memory, f_wipe);
                   +  - ]
     132         [ +  - ]:           4 :     m_filter_fileseq = std::make_unique<FlatFileSeq>(std::move(path), "fltr", FLTR_FILE_CHUNK_SIZE);
     133                 :           4 : }
     134                 :             : 
     135                 :         120 : interfaces::Chain::NotifyOptions BlockFilterIndex::CustomOptions()
     136                 :             : {
     137                 :         120 :     interfaces::Chain::NotifyOptions options;
     138                 :         120 :     options.connect_undo_data = true;
     139                 :         120 :     return options;
     140                 :             : }
     141                 :             : 
     142                 :           1 : bool BlockFilterIndex::CustomInit(const std::optional<interfaces::BlockRef>& block)
     143                 :             : {
     144         [ +  - ]:           1 :     if (!m_db->Read(DB_FILTER_POS, m_next_filter_pos)) {
     145                 :             :         // Check that the cause of the read failure is that the key does not exist. Any other errors
     146                 :             :         // indicate database corruption or a disk failure, and starting the index would cause
     147                 :             :         // further corruption.
     148         [ -  + ]:           1 :         if (m_db->Exists(DB_FILTER_POS)) {
     149                 :           0 :             LogError("Cannot read current %s state; index may be corrupted",
     150                 :             :                       GetName());
     151                 :           0 :             return false;
     152                 :             :         }
     153                 :             : 
     154                 :             :         // If the DB_FILTER_POS is not set, then initialize to the first location.
     155                 :           1 :         m_next_filter_pos.nFile = 0;
     156                 :           1 :         m_next_filter_pos.nPos = 0;
     157                 :             :     }
     158                 :             : 
     159         [ -  + ]:           1 :     if (block) {
     160                 :           0 :         auto op_last_header = ReadFilterHeader(block->height, block->hash);
     161         [ #  # ]:           0 :         if (!op_last_header) {
     162                 :           0 :             LogError("Cannot read last block filter header; index may be corrupted");
     163                 :           0 :             return false;
     164                 :             :         }
     165                 :           0 :         m_last_header = *op_last_header;
     166                 :             :     }
     167                 :             : 
     168                 :             :     return true;
     169                 :             : }
     170                 :             : 
     171                 :           1 : bool BlockFilterIndex::CustomCommit(CDBBatch& batch)
     172                 :             : {
     173                 :           1 :     const FlatFilePos& pos = m_next_filter_pos;
     174                 :             : 
     175                 :             :     // Flush current filter file to disk.
     176                 :           2 :     AutoFile file{m_filter_fileseq->Open(pos)};
     177         [ -  + ]:           1 :     if (file.IsNull()) {
     178         [ #  # ]:           0 :         LogError("Failed to open filter file %d", pos.nFile);
     179                 :             :         return false;
     180                 :             :     }
     181   [ +  -  -  + ]:           1 :     if (!file.Commit()) {
     182         [ #  # ]:           0 :         LogError("Failed to commit filter file %d", pos.nFile);
     183         [ #  # ]:           0 :         (void)file.fclose();
     184                 :             :         return false;
     185                 :             :     }
     186   [ +  -  -  + ]:           2 :     if (file.fclose() != 0) {
     187   [ #  #  #  # ]:           0 :         LogError("Failed to close filter file %d after commit: %s", pos.nFile, SysErrorString(errno));
     188                 :           0 :         return false;
     189                 :             :     }
     190                 :             : 
     191         [ +  - ]:           1 :     batch.Write(DB_FILTER_POS, pos);
     192                 :             :     return true;
     193                 :           1 : }
     194                 :             : 
     195                 :         333 : bool BlockFilterIndex::ReadFilterFromDisk(const FlatFilePos& pos, const uint256& hash, BlockFilter& filter) const
     196                 :             : {
     197                 :         666 :     AutoFile filein{m_filter_fileseq->Open(pos, true)};
     198         [ +  - ]:         333 :     if (filein.IsNull()) {
     199                 :             :         return false;
     200                 :             :     }
     201                 :             : 
     202                 :             :     // Check that the hash of the encoded_filter matches the one stored in the db.
     203                 :         333 :     uint256 block_hash;
     204                 :         333 :     std::vector<uint8_t> encoded_filter;
     205                 :         333 :     try {
     206   [ +  -  +  - ]:         333 :         filein >> block_hash >> encoded_filter;
     207   [ +  -  -  + ]:         333 :         if (Hash(encoded_filter) != hash) {
     208         [ #  # ]:           0 :             LogError("Checksum mismatch in filter decode.");
     209                 :             :             return false;
     210                 :             :         }
     211         [ +  - ]:         666 :         filter = BlockFilter(GetFilterType(), block_hash, std::move(encoded_filter), /*skip_decode_check=*/true);
     212                 :             :     }
     213         [ -  - ]:           0 :     catch (const std::exception& e) {
     214         [ -  - ]:           0 :         LogError("Failed to deserialize block filter from disk: %s", e.what());
     215                 :           0 :         return false;
     216                 :           0 :     }
     217                 :             : 
     218                 :         333 :     return true;
     219                 :         333 : }
     220                 :             : 
     221                 :         110 : size_t BlockFilterIndex::WriteFilterToDisk(FlatFilePos& pos, const BlockFilter& filter)
     222                 :             : {
     223         [ -  + ]:         110 :     assert(filter.GetFilterType() == GetFilterType());
     224                 :             : 
     225                 :         110 :     size_t data_size =
     226                 :         110 :         GetSerializeSize(filter.GetBlockHash()) +
     227                 :         110 :         GetSerializeSize(filter.GetEncodedFilter());
     228                 :             : 
     229                 :             :     // If writing the filter would overflow the file, flush and move to the next one.
     230         [ -  + ]:         110 :     if (pos.nPos + data_size > MAX_FLTR_FILE_SIZE) {
     231                 :           0 :         AutoFile last_file{m_filter_fileseq->Open(pos)};
     232         [ #  # ]:           0 :         if (last_file.IsNull()) {
     233         [ #  # ]:           0 :             LogError("Failed to open filter file %d", pos.nFile);
     234                 :             :             return 0;
     235                 :             :         }
     236   [ #  #  #  # ]:           0 :         if (!last_file.Truncate(pos.nPos)) {
     237         [ #  # ]:           0 :             LogError("Failed to truncate filter file %d", pos.nFile);
     238                 :             :             return 0;
     239                 :             :         }
     240   [ #  #  #  # ]:           0 :         if (!last_file.Commit()) {
     241         [ #  # ]:           0 :             LogError("Failed to commit filter file %d", pos.nFile);
     242         [ #  # ]:           0 :             (void)last_file.fclose();
     243                 :             :             return 0;
     244                 :             :         }
     245   [ #  #  #  # ]:           0 :         if (last_file.fclose() != 0) {
     246   [ #  #  #  # ]:           0 :             LogError("Failed to close filter file %d after commit: %s", pos.nFile, SysErrorString(errno));
     247                 :           0 :             return 0;
     248                 :             :         }
     249                 :             : 
     250                 :           0 :         pos.nFile++;
     251                 :           0 :         pos.nPos = 0;
     252                 :           0 :     }
     253                 :             : 
     254                 :             :     // Pre-allocate sufficient space for filter data.
     255                 :         110 :     bool out_of_space;
     256                 :         110 :     m_filter_fileseq->Allocate(pos, data_size, out_of_space);
     257         [ -  + ]:         110 :     if (out_of_space) {
     258                 :           0 :         LogError("out of disk space");
     259                 :           0 :         return 0;
     260                 :             :     }
     261                 :             : 
     262                 :         220 :     AutoFile fileout{m_filter_fileseq->Open(pos)};
     263         [ -  + ]:         110 :     if (fileout.IsNull()) {
     264         [ #  # ]:           0 :         LogError("Failed to open filter file %d", pos.nFile);
     265                 :             :         return 0;
     266                 :             :     }
     267                 :             : 
     268   [ +  -  +  - ]:         110 :     fileout << filter.GetBlockHash() << filter.GetEncodedFilter();
     269                 :             : 
     270   [ +  -  -  + ]:         220 :     if (fileout.fclose() != 0) {
     271   [ #  #  #  # ]:           0 :         LogError("Failed to close filter file %d: %s", pos.nFile, SysErrorString(errno));
     272                 :           0 :         return 0;
     273                 :             :     }
     274                 :             : 
     275                 :             :     return data_size;
     276                 :         110 : }
     277                 :             : 
     278                 :           5 : std::optional<uint256> BlockFilterIndex::ReadFilterHeader(int height, const uint256& expected_block_hash)
     279                 :             : {
     280                 :           5 :     std::pair<uint256, DBVal> read_out;
     281         [ -  + ]:           5 :     if (!m_db->Read(DBHeightKey(height), read_out)) {
     282                 :           0 :         return std::nullopt;
     283                 :             :     }
     284                 :             : 
     285         [ -  + ]:           5 :     if (read_out.first != expected_block_hash) {
     286   [ #  #  #  # ]:           0 :         LogError("previous block header belongs to unexpected block %s; expected %s",
     287                 :             :                  read_out.first.ToString(), expected_block_hash.ToString());
     288                 :           0 :         return std::nullopt;
     289                 :             :     }
     290                 :             : 
     291                 :           5 :     return read_out.second.header;
     292                 :             : }
     293                 :             : 
     294                 :         110 : bool BlockFilterIndex::CustomAppend(const interfaces::BlockInfo& block)
     295                 :             : {
     296                 :         110 :     BlockFilter filter(m_filter_type, *Assert(block.data), *Assert(block.undo_data));
     297         [ +  - ]:         110 :     const uint256& header = filter.ComputeHeader(m_last_header);
     298         [ +  - ]:         110 :     bool res = Write(filter, block.height, header);
     299         [ +  - ]:         110 :     if (res) m_last_header = header; // update last header
     300                 :         110 :     return res;
     301                 :         110 : }
     302                 :             : 
     303                 :         110 : bool BlockFilterIndex::Write(const BlockFilter& filter, uint32_t block_height, const uint256& filter_header)
     304                 :             : {
     305                 :         110 :     size_t bytes_written = WriteFilterToDisk(m_next_filter_pos, filter);
     306         [ +  - ]:         110 :     if (bytes_written == 0) return false;
     307                 :             : 
     308                 :         110 :     std::pair<uint256, DBVal> value;
     309                 :         110 :     value.first = filter.GetBlockHash();
     310                 :         110 :     value.second.hash = filter.GetHash();
     311                 :         110 :     value.second.header = filter_header;
     312                 :         110 :     value.second.pos = m_next_filter_pos;
     313                 :             : 
     314         [ +  - ]:         110 :     if (!m_db->Write(DBHeightKey(block_height), value)) {
     315                 :             :         return false;
     316                 :             :     }
     317                 :             : 
     318                 :         110 :     m_next_filter_pos.nPos += bytes_written;
     319                 :         110 :     return true;
     320                 :             : }
     321                 :             : 
     322                 :           5 : [[nodiscard]] static bool CopyHeightIndexToHashIndex(CDBIterator& db_it, CDBBatch& batch,
     323                 :             :                                                      const std::string& index_name, int height)
     324                 :             : {
     325                 :           5 :     DBHeightKey key(height);
     326                 :           5 :     db_it.Seek(key);
     327                 :             : 
     328   [ +  -  +  - ]:           5 :     if (!db_it.GetKey(key) || key.height != height) {
     329                 :           0 :         LogError("unexpected key in %s: expected (%c, %d)",
     330                 :             :                   index_name, DB_BLOCK_HEIGHT, height);
     331                 :           0 :         return false;
     332                 :             :     }
     333                 :             : 
     334                 :           5 :     std::pair<uint256, DBVal> value;
     335         [ -  + ]:           5 :     if (!db_it.GetValue(value)) {
     336                 :           0 :         LogError("unable to read value in %s at key (%c, %d)",
     337                 :             :                  index_name, DB_BLOCK_HEIGHT, height);
     338                 :           0 :         return false;
     339                 :             :     }
     340                 :             : 
     341                 :           5 :     batch.Write(DBHashKey(value.first), std::move(value.second));
     342                 :           5 :     return true;
     343                 :             : }
     344                 :             : 
     345                 :           5 : bool BlockFilterIndex::CustomRemove(const interfaces::BlockInfo& block)
     346                 :             : {
     347                 :           5 :     CDBBatch batch(*m_db);
     348   [ +  -  +  - ]:           5 :     std::unique_ptr<CDBIterator> db_it(m_db->NewIterator());
     349                 :             : 
     350                 :             :     // During a reorg, we need to copy block filter that is getting disconnected from the
     351                 :             :     // height index to the hash index so we can still find it when the height index entry
     352                 :             :     // is overwritten.
     353   [ +  -  +  - ]:           5 :     if (!CopyHeightIndexToHashIndex(*db_it, batch, m_name, block.height)) {
     354                 :             :         return false;
     355                 :             :     }
     356                 :             : 
     357                 :             :     // The latest filter position gets written in Commit by the call to the BaseIndex::Rewind.
     358                 :             :     // But since this creates new references to the filter, the position should get updated here
     359                 :             :     // atomically as well in case Commit fails.
     360         [ +  - ]:           5 :     batch.Write(DB_FILTER_POS, m_next_filter_pos);
     361   [ +  -  +  - ]:           5 :     if (!m_db->WriteBatch(batch)) return false;
     362                 :             : 
     363                 :             :     // Update cached header to the previous block hash
     364   [ +  -  +  -  :           5 :     m_last_header = *Assert(ReadFilterHeader(block.height - 1, *Assert(block.prev_hash)));
                   +  - ]
     365                 :           5 :     return true;
     366                 :           5 : }
     367                 :             : 
     368                 :         430 : static bool LookupOne(const CDBWrapper& db, const CBlockIndex* block_index, DBVal& result)
     369                 :             : {
     370                 :             :     // First check if the result is stored under the height index and the value there matches the
     371                 :             :     // block hash. This should be the case if the block is on the active chain.
     372                 :         430 :     std::pair<uint256, DBVal> read_out;
     373         [ +  + ]:         430 :     if (!db.Read(DBHeightKey(block_index->nHeight), read_out)) {
     374                 :             :         return false;
     375                 :             :     }
     376         [ +  + ]:         228 :     if (read_out.first == block_index->GetBlockHash()) {
     377                 :         218 :         result = std::move(read_out.second);
     378                 :         218 :         return true;
     379                 :             :     }
     380                 :             : 
     381                 :             :     // If value at the height index corresponds to an different block, the result will be stored in
     382                 :             :     // the hash index.
     383                 :          10 :     return db.Read(DBHashKey(block_index->GetBlockHash()), result);
     384                 :             : }
     385                 :             : 
     386                 :         432 : static bool LookupRange(CDBWrapper& db, const std::string& index_name, int start_height,
     387                 :             :                         const CBlockIndex* stop_index, std::vector<DBVal>& results)
     388                 :             : {
     389         [ -  + ]:         432 :     if (start_height < 0) {
     390                 :           0 :         LogError("start height (%d) is negative", start_height);
     391                 :           0 :         return false;
     392                 :             :     }
     393         [ -  + ]:         432 :     if (start_height > stop_index->nHeight) {
     394                 :           0 :         LogError("start height (%d) is greater than stop height (%d)",
     395                 :             :                  start_height, stop_index->nHeight);
     396                 :           0 :         return false;
     397                 :             :     }
     398                 :             : 
     399                 :         432 :     size_t results_size = static_cast<size_t>(stop_index->nHeight - start_height + 1);
     400                 :         432 :     std::vector<std::pair<uint256, DBVal>> values(results_size);
     401                 :             : 
     402                 :         432 :     DBHeightKey key(start_height);
     403   [ +  -  +  - ]:         432 :     std::unique_ptr<CDBIterator> db_it(db.NewIterator());
     404         [ +  - ]:         432 :     db_it->Seek(DBHeightKey(start_height));
     405         [ +  + ]:         870 :     for (int height = start_height; height <= stop_index->nHeight; ++height) {
     406   [ +  -  +  +  :         640 :         if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
          +  -  +  -  -  
                      + ]
     407                 :         202 :             return false;
     408                 :             :         }
     409                 :             : 
     410                 :         438 :         size_t i = static_cast<size_t>(height - start_height);
     411   [ +  -  -  + ]:         438 :         if (!db_it->GetValue(values[i])) {
     412         [ #  # ]:           0 :             LogError("unable to read value in %s at key (%c, %d)",
     413                 :             :                      index_name, DB_BLOCK_HEIGHT, height);
     414                 :             :             return false;
     415                 :             :         }
     416                 :             : 
     417         [ +  - ]:         438 :         db_it->Next();
     418                 :             :     }
     419                 :             : 
     420         [ +  - ]:         230 :     results.resize(results_size);
     421                 :             : 
     422                 :             :     // Iterate backwards through block indexes collecting results in order to access the block hash
     423                 :             :     // of each entry in case we need to look it up in the hash index.
     424                 :         438 :     for (const CBlockIndex* block_index = stop_index;
     425   [ +  +  +  + ]:         668 :          block_index && block_index->nHeight >= start_height;
     426                 :         438 :          block_index = block_index->pprev) {
     427                 :         438 :         uint256 block_hash = block_index->GetBlockHash();
     428                 :             : 
     429                 :         438 :         size_t i = static_cast<size_t>(block_index->nHeight - start_height);
     430         [ +  + ]:         438 :         if (block_hash == values[i].first) {
     431                 :         428 :             results[i] = std::move(values[i].second);
     432                 :         428 :             continue;
     433                 :             :         }
     434                 :             : 
     435   [ +  -  -  + ]:          10 :         if (!db.Read(DBHashKey(block_hash), results[i])) {
     436   [ #  #  #  # ]:           0 :             LogError("unable to read value in %s at key (%c, %s)",
     437                 :             :                      index_name, DB_BLOCK_HASH, block_hash.ToString());
     438                 :           0 :             return false;
     439                 :             :         }
     440                 :             :     }
     441                 :             : 
     442                 :             :     return true;
     443                 :         432 : }
     444                 :             : 
     445                 :         215 : bool BlockFilterIndex::LookupFilter(const CBlockIndex* block_index, BlockFilter& filter_out) const
     446                 :             : {
     447                 :         215 :     DBVal entry;
     448         [ +  + ]:         215 :     if (!LookupOne(*m_db, block_index, entry)) {
     449                 :             :         return false;
     450                 :             :     }
     451                 :             : 
     452                 :         114 :     return ReadFilterFromDisk(entry.pos, entry.hash, filter_out);
     453                 :             : }
     454                 :             : 
     455                 :         215 : bool BlockFilterIndex::LookupFilterHeader(const CBlockIndex* block_index, uint256& header_out)
     456                 :             : {
     457                 :         215 :     LOCK(m_cs_headers_cache);
     458                 :             : 
     459                 :         215 :     bool is_checkpoint{block_index->nHeight % CFCHECKPT_INTERVAL == 0};
     460                 :             : 
     461         [ +  + ]:         215 :     if (is_checkpoint) {
     462                 :             :         // Try to find the block in the headers cache if this is a checkpoint height.
     463                 :           2 :         auto header = m_headers_cache.find(block_index->GetBlockHash());
     464         [ -  + ]:           2 :         if (header != m_headers_cache.end()) {
     465                 :           0 :             header_out = header->second;
     466                 :           0 :             return true;
     467                 :             :         }
     468                 :             :     }
     469                 :             : 
     470                 :         215 :     DBVal entry;
     471   [ +  -  +  + ]:         215 :     if (!LookupOne(*m_db, block_index, entry)) {
     472                 :             :         return false;
     473                 :             :     }
     474                 :             : 
     475   [ +  +  +  - ]:         114 :     if (is_checkpoint &&
     476         [ +  - ]:           1 :         m_headers_cache.size() < CF_HEADERS_CACHE_MAX_SZ) {
     477                 :             :         // Add to the headers cache if this is a checkpoint height.
     478         [ +  - ]:           1 :         m_headers_cache.emplace(block_index->GetBlockHash(), entry.header);
     479                 :             :     }
     480                 :             : 
     481                 :         114 :     header_out = entry.header;
     482                 :         114 :     return true;
     483                 :         215 : }
     484                 :             : 
     485                 :         216 : bool BlockFilterIndex::LookupFilterRange(int start_height, const CBlockIndex* stop_index,
     486                 :             :                                          std::vector<BlockFilter>& filters_out) const
     487                 :             : {
     488                 :         216 :     std::vector<DBVal> entries;
     489   [ +  -  +  + ]:         216 :     if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
     490                 :             :         return false;
     491                 :             :     }
     492                 :             : 
     493   [ -  +  +  - ]:         115 :     filters_out.resize(entries.size());
     494                 :         115 :     auto filter_pos_it = filters_out.begin();
     495         [ +  + ]:         334 :     for (const auto& entry : entries) {
     496   [ +  -  +  - ]:         219 :         if (!ReadFilterFromDisk(entry.pos, entry.hash, *filter_pos_it)) {
     497                 :             :             return false;
     498                 :             :         }
     499                 :         219 :         ++filter_pos_it;
     500                 :             :     }
     501                 :             : 
     502                 :             :     return true;
     503                 :         216 : }
     504                 :             : 
     505                 :         216 : bool BlockFilterIndex::LookupFilterHashRange(int start_height, const CBlockIndex* stop_index,
     506                 :             :                                              std::vector<uint256>& hashes_out) const
     507                 :             : 
     508                 :             : {
     509                 :         216 :     std::vector<DBVal> entries;
     510   [ +  -  +  + ]:         216 :     if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
     511                 :             :         return false;
     512                 :             :     }
     513                 :             : 
     514         [ -  + ]:         115 :     hashes_out.clear();
     515   [ -  +  +  - ]:         115 :     hashes_out.reserve(entries.size());
     516         [ +  + ]:         334 :     for (const auto& entry : entries) {
     517         [ +  - ]:         219 :         hashes_out.push_back(entry.hash);
     518                 :             :     }
     519                 :             :     return true;
     520                 :         216 : }
     521                 :             : 
     522                 :          13 : BlockFilterIndex* GetBlockFilterIndex(BlockFilterType filter_type)
     523                 :             : {
     524                 :          13 :     auto it = g_filter_indexes.find(filter_type);
     525         [ +  + ]:          13 :     return it != g_filter_indexes.end() ? &it->second : nullptr;
     526                 :             : }
     527                 :             : 
     528                 :           1 : void ForEachBlockFilterIndex(std::function<void (BlockFilterIndex&)> fn)
     529                 :             : {
     530         [ +  + ]:           2 :     for (auto& entry : g_filter_indexes) fn(entry.second);
     531                 :           1 : }
     532                 :             : 
     533                 :           3 : bool InitBlockFilterIndex(std::function<std::unique_ptr<interfaces::Chain>()> make_chain, BlockFilterType filter_type,
     534                 :             :                           size_t n_cache_size, bool f_memory, bool f_wipe)
     535                 :             : {
     536                 :           6 :     auto result = g_filter_indexes.emplace(std::piecewise_construct,
     537         [ +  - ]:           3 :                                            std::forward_as_tuple(filter_type),
     538         [ +  - ]:           3 :                                            std::forward_as_tuple(make_chain(), filter_type,
     539                 :             :                                                                  n_cache_size, f_memory, f_wipe));
     540                 :           3 :     return result.second;
     541                 :             : }
     542                 :             : 
     543                 :           2 : bool DestroyBlockFilterIndex(BlockFilterType filter_type)
     544                 :             : {
     545                 :           2 :     return g_filter_indexes.erase(filter_type);
     546                 :             : }
     547                 :             : 
     548                 :           2 : void DestroyAllBlockFilterIndexes()
     549                 :             : {
     550                 :           2 :     g_filter_indexes.clear();
     551                 :           2 : }
        
               |