Coverage Report

Created: 2026-10-19 15:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/index/blockfilterindex.cpp
Line
Count
Source
1
// Copyright (c) 2018-present 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 <index/db_key.h>
15
#include <interfaces/chain.h>
16
#include <interfaces/types.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/byte_units.h>
23
#include <util/fs.h>
24
#include <util/hasher.h>
25
#include <util/log.h>
26
#include <util/syserror.h>
27
28
#include <cerrno>
29
#include <exception>
30
#include <map>
31
#include <optional>
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
 * The logic for keys is shared with other indexes, see index/db_key.h.
50
 */
51
constexpr uint8_t DB_FILTER_POS{'P'};
52
53
constexpr unsigned int MAX_FLTR_FILE_SIZE{16_MiB};
54
/** The pre-allocation chunk size for fltr?????.dat files */
55
constexpr unsigned int FLTR_FILE_CHUNK_SIZE{1_MiB};
56
/** Maximum size of the cfheaders cache
57
 *  We have a limit to prevent a bug in filling this cache
58
 *  potentially turning into an OOM. At 2000 entries, this cache
59
 *  is big enough for a 2,000,000 length block chain, which
60
 *  we should be enough until ~2047. */
61
constexpr size_t CF_HEADERS_CACHE_MAX_SZ{2000};
62
63
namespace {
64
65
std::string BlockFilterThreadName(BlockFilterType filter_type)
66
51
{
67
51
    switch (filter_type) {
68
51
    case BlockFilterType::BASIC: return "blkfltbscidx";
69
0
    case BlockFilterType::INVALID: return "";
70
51
    } // no default case, so the compiler can warn about missing cases
71
51
    assert(false);
72
0
}
73
74
struct DBVal {
75
    uint256 hash;
76
    uint256 header;
77
    FlatFilePos pos;
78
79
12.1k
    SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
blockfilterindex.cpp:void (anonymous namespace)::DBVal::SerializationOps<DataStream, (anonymous namespace)::DBVal, ActionUnserialize>((anonymous namespace)::DBVal&, DataStream&, ActionUnserialize)
Line
Count
Source
79
2.97k
    SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
blockfilterindex.cpp:void (anonymous namespace)::DBVal::SerializationOps<SpanReader, (anonymous namespace)::DBVal, ActionUnserialize>((anonymous namespace)::DBVal&, SpanReader&, ActionUnserialize)
Line
Count
Source
79
1.06k
    SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
blockfilterindex.cpp:void (anonymous namespace)::DBVal::SerializationOps<DataStream, (anonymous namespace)::DBVal const, ActionSerialize>((anonymous namespace)::DBVal const&, DataStream&, ActionSerialize)
Line
Count
Source
79
8.09k
    SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
80
};
81
82
}; // namespace
83
84
static std::map<BlockFilterType, BlockFilterIndex> g_filter_indexes;
85
86
BlockFilterIndex::BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain, BlockFilterType filter_type,
87
                                   size_t n_cache_size, bool f_memory, bool f_wipe)
88
51
    : BaseIndex(std::move(chain), BlockFilterTypeName(filter_type) + " block filter index", BlockFilterThreadName(filter_type))
89
51
    , m_filter_type(filter_type)
90
51
{
91
51
    const std::string& filter_name = BlockFilterTypeName(filter_type);
92
51
    if (filter_name.empty()) throw std::invalid_argument("unknown filter_type");
93
94
51
    fs::path path = gArgs.GetDataDirNet() / "indexes" / "blockfilter" / fs::u8path(filter_name);
95
51
    fs::create_directories(path);
96
97
51
    m_db = std::make_unique<BaseIndex::DB>(path / "db", n_cache_size, f_memory, f_wipe);
98
51
    m_filter_fileseq = std::make_unique<FlatFileSeq>(std::move(path), "fltr", FLTR_FILE_CHUNK_SIZE);
99
51
}
100
101
interfaces::Chain::NotifyOptions BlockFilterIndex::CustomOptions()
102
8.22k
{
103
8.22k
    interfaces::Chain::NotifyOptions options;
104
8.22k
    options.connect_undo_data = true;
105
8.22k
    return options;
106
8.22k
}
107
108
bool BlockFilterIndex::CustomInit(const std::optional<interfaces::BlockRef>& block)
109
53
{
110
53
    if (!m_db->Read(DB_FILTER_POS, m_next_filter_pos)) {
111
        // Check that the cause of the read failure is that the key does not exist. Any other errors
112
        // indicate database corruption or a disk failure, and starting the index would cause
113
        // further corruption.
114
24
        if (m_db->Exists(DB_FILTER_POS)) {
115
0
            LogError("Cannot read current %s state; index may be corrupted",
116
0
                      GetName());
117
0
            return false;
118
0
        }
119
120
        // If the DB_FILTER_POS is not set, then initialize to the first location.
121
24
        m_next_filter_pos.nFile = 0;
122
24
        m_next_filter_pos.nPos = 0;
123
24
    }
124
125
53
    if (block) {
126
29
        auto op_last_header = ReadFilterHeader(block->height, block->hash);
127
29
        if (!op_last_header) {
128
0
            LogError("Cannot read last block filter header; index may be corrupted");
129
0
            return false;
130
0
        }
131
29
        m_last_header = *op_last_header;
132
29
    }
133
134
53
    return true;
135
53
}
136
137
bool BlockFilterIndex::CustomCommit(CDBBatch& batch)
138
66
{
139
66
    const FlatFilePos& pos = m_next_filter_pos;
140
141
    // Flush current filter file to disk.
142
66
    AutoFile file{m_filter_fileseq->Open(pos)};
143
66
    if (file.IsNull()) {
144
0
        LogError("Failed to open filter file %d", pos.nFile);
145
0
        return false;
146
0
    }
147
66
    if (!file.Commit()) {
148
0
        LogError("Failed to commit filter file %d", pos.nFile);
149
0
        (void)file.fclose();
150
0
        return false;
151
0
    }
152
66
    if (file.fclose() != 0) {
153
0
        LogError("Failed to close filter file %d after commit: %s", pos.nFile, SysErrorString(errno));
154
0
        return false;
155
0
    }
156
157
66
    batch.Write(DB_FILTER_POS, pos);
158
66
    return true;
159
66
}
160
161
bool BlockFilterIndex::ReadFilterFromDisk(const FlatFilePos& pos, const uint256& hash, BlockFilter& filter) const
162
1.39k
{
163
1.39k
    AutoFile filein{m_filter_fileseq->Open(pos, true)};
164
1.39k
    if (filein.IsNull()) {
165
0
        return false;
166
0
    }
167
168
    // Check that the hash of the encoded_filter matches the one stored in the db.
169
1.39k
    uint256 block_hash;
170
1.39k
    std::vector<uint8_t> encoded_filter;
171
1.39k
    try {
172
1.39k
        filein >> block_hash >> encoded_filter;
173
1.39k
        if (Hash(encoded_filter) != hash) {
174
0
            LogError("Checksum mismatch in filter decode.");
175
0
            return false;
176
0
        }
177
1.39k
        filter = BlockFilter(GetFilterType(), block_hash, std::move(encoded_filter), /*skip_decode_check=*/true);
178
1.39k
    }
179
1.39k
    catch (const std::exception& e) {
180
0
        LogError("Failed to deserialize block filter from disk: %s", e.what());
181
0
        return false;
182
0
    }
183
184
1.39k
    return true;
185
1.39k
}
186
187
size_t BlockFilterIndex::WriteFilterToDisk(FlatFilePos& pos, const BlockFilter& filter)
188
7.98k
{
189
7.98k
    assert(filter.GetFilterType() == GetFilterType());
190
191
7.98k
    uint64_t data_size{
192
7.98k
        GetSerializeSize(filter.GetBlockHash()) +
193
7.98k
        GetSerializeSize(filter.GetEncodedFilter())};
194
195
    // If writing the filter would overflow the file, flush and move to the next one.
196
7.98k
    if (pos.nPos + data_size > MAX_FLTR_FILE_SIZE) {
197
0
        AutoFile last_file{m_filter_fileseq->Open(pos)};
198
0
        if (last_file.IsNull()) {
199
0
            LogError("Failed to open filter file %d", pos.nFile);
200
0
            return 0;
201
0
        }
202
0
        if (!last_file.Truncate(pos.nPos)) {
203
0
            LogError("Failed to truncate filter file %d", pos.nFile);
204
0
            return 0;
205
0
        }
206
0
        if (!last_file.Commit()) {
207
0
            LogError("Failed to commit filter file %d", pos.nFile);
208
0
            (void)last_file.fclose();
209
0
            return 0;
210
0
        }
211
0
        if (last_file.fclose() != 0) {
212
0
            LogError("Failed to close filter file %d after commit: %s", pos.nFile, SysErrorString(errno));
213
0
            return 0;
214
0
        }
215
216
0
        pos.nFile++;
217
0
        pos.nPos = 0;
218
0
    }
219
220
    // Pre-allocate sufficient space for filter data.
221
7.98k
    bool out_of_space;
222
7.98k
    m_filter_fileseq->Allocate(pos, data_size, out_of_space);
223
7.98k
    if (out_of_space) {
224
0
        LogError("out of disk space");
225
0
        return 0;
226
0
    }
227
228
7.98k
    AutoFile fileout{m_filter_fileseq->Open(pos)};
229
7.98k
    if (fileout.IsNull()) {
230
0
        LogError("Failed to open filter file %d", pos.nFile);
231
0
        return 0;
232
0
    }
233
234
7.98k
    fileout << filter.GetBlockHash() << filter.GetEncodedFilter();
235
236
7.98k
    if (fileout.fclose() != 0) {
237
0
        LogError("Failed to close filter file %d: %s", pos.nFile, SysErrorString(errno));
238
0
        return 0;
239
0
    }
240
241
7.98k
    return data_size;
242
7.98k
}
243
244
std::optional<uint256> BlockFilterIndex::ReadFilterHeader(int height, const uint256& expected_block_hash)
245
141
{
246
141
    std::pair<uint256, DBVal> read_out;
247
141
    if (!m_db->Read(index_util::DBHeightKey(height), read_out)) {
248
0
        return std::nullopt;
249
0
    }
250
251
141
    if (read_out.first != expected_block_hash) {
252
0
        LogError("previous block header belongs to unexpected block %s; expected %s",
253
0
                 read_out.first.ToString(), expected_block_hash.ToString());
254
0
        return std::nullopt;
255
0
    }
256
257
141
    return read_out.second.header;
258
141
}
259
260
bool BlockFilterIndex::CustomAppend(const interfaces::BlockInfo& block)
261
7.98k
{
262
7.98k
    BlockFilter filter(m_filter_type, *Assert(block.data), *Assert(block.undo_data));
263
7.98k
    const uint256& header = filter.ComputeHeader(m_last_header);
264
7.98k
    bool res = Write(filter, block.height, header);
265
7.98k
    if (res) m_last_header = header; // update last header
266
7.98k
    return res;
267
7.98k
}
268
269
bool BlockFilterIndex::Write(const BlockFilter& filter, uint32_t block_height, const uint256& filter_header)
270
7.98k
{
271
7.98k
    size_t bytes_written = WriteFilterToDisk(m_next_filter_pos, filter);
272
7.98k
    if (bytes_written == 0) return false;
273
274
7.98k
    std::pair<uint256, DBVal> value;
275
7.98k
    value.first = filter.GetBlockHash();
276
7.98k
    value.second.hash = filter.GetHash();
277
7.98k
    value.second.header = filter_header;
278
7.98k
    value.second.pos = m_next_filter_pos;
279
280
7.98k
    m_db->Write(index_util::DBHeightKey(block_height), value);
281
282
7.98k
    m_next_filter_pos.nPos += bytes_written;
283
7.98k
    return true;
284
7.98k
}
285
286
bool BlockFilterIndex::CustomRemove(const interfaces::BlockInfo& block)
287
112
{
288
112
    CDBBatch batch(*m_db);
289
112
    std::unique_ptr<CDBIterator> db_it(m_db->NewIterator());
290
291
    // During a reorg, we need to copy block filter that is getting disconnected from the
292
    // height index to the hash index so we can still find it when the height index entry
293
    // is overwritten.
294
112
    if (!index_util::CopyHeightIndexToHashIndex<DBVal>(*db_it, batch, m_name, block.height)) {
295
0
        return false;
296
0
    }
297
298
    // The latest filter position gets written in Commit by the call to the BaseIndex::Rewind.
299
    // But since this creates new references to the filter, the position should get updated here
300
    // atomically as well in case Commit fails.
301
112
    batch.Write(DB_FILTER_POS, m_next_filter_pos);
302
112
    m_db->WriteBatch(batch);
303
304
    // Update cached header to the previous block hash
305
112
    m_last_header = *Assert(ReadFilterHeader(block.height - 1, *Assert(block.prev_hash)));
306
112
    return true;
307
112
}
308
309
static bool LookupRange(CDBWrapper& db, const std::string& index_name, int start_height,
310
                        const CBlockIndex* stop_index, std::vector<DBVal>& results)
311
448
{
312
448
    if (start_height < 0) {
313
0
        LogError("start height (%d) is negative", start_height);
314
0
        return false;
315
0
    }
316
448
    if (start_height > stop_index->nHeight) {
317
0
        LogError("start height (%d) is greater than stop height (%d)",
318
0
                 start_height, stop_index->nHeight);
319
0
        return false;
320
0
    }
321
322
448
    size_t results_size = static_cast<size_t>(stop_index->nHeight - start_height + 1);
323
448
    std::vector<std::pair<uint256, DBVal>> values(results_size);
324
325
448
    index_util::DBHeightKey key(start_height);
326
448
    std::unique_ptr<CDBIterator> db_it(db.NewIterator());
327
448
    db_it->Seek(index_util::DBHeightKey(start_height));
328
3.31k
    for (int height = start_height; height <= stop_index->nHeight; ++height) {
329
3.06k
        if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
330
202
            return false;
331
202
        }
332
333
2.86k
        size_t i = static_cast<size_t>(height - start_height);
334
2.86k
        if (!db_it->GetValue(values[i])) {
335
0
            LogError("unable to read value in %s at key (%c, %d)",
336
0
                     index_name, index_util::DB_BLOCK_HEIGHT, height);
337
0
            return false;
338
0
        }
339
340
2.86k
        db_it->Next();
341
2.86k
    }
342
343
246
    results.resize(results_size);
344
345
    // Iterate backwards through block indexes collecting results in order to access the block hash
346
    // of each entry in case we need to look it up in the hash index.
347
246
    for (const CBlockIndex* block_index = stop_index;
348
3.11k
         block_index && block_index->nHeight >= start_height;
349
2.86k
         block_index = block_index->pprev) {
350
2.86k
        uint256 block_hash = block_index->GetBlockHash();
351
352
2.86k
        size_t i = static_cast<size_t>(block_index->nHeight - start_height);
353
2.86k
        if (block_hash == values[i].first) {
354
2.85k
            results[i] = std::move(values[i].second);
355
2.85k
            continue;
356
2.85k
        }
357
358
12
        if (!db.Read(index_util::DBHashKey(block_hash), results[i])) {
359
0
            LogError("unable to read value in %s at key (%c, %s)",
360
0
                     index_name, index_util::DB_BLOCK_HASH, block_hash.ToString());
361
0
            return false;
362
0
        }
363
12
    }
364
365
246
    return true;
366
246
}
367
368
bool BlockFilterIndex::LookupFilter(const CBlockIndex* block_index, BlockFilter& filter_out) const
369
955
{
370
955
    DBVal entry;
371
955
    if (!index_util::LookUpOne(*m_db, {block_index->GetBlockHash(), block_index->nHeight}, entry)) {
372
203
        return false;
373
203
    }
374
375
752
    return ReadFilterFromDisk(entry.pos, entry.hash, filter_out);
376
955
}
377
378
bool BlockFilterIndex::LookupFilterHeader(const CBlockIndex* block_index, uint256& header_out)
379
243
{
380
243
    LOCK(m_cs_headers_cache);
381
382
243
    bool is_checkpoint{block_index->nHeight % CFCHECKPT_INTERVAL == 0};
383
384
243
    if (is_checkpoint) {
385
        // Try to find the block in the headers cache if this is a checkpoint height.
386
13
        auto header = m_headers_cache.find(block_index->GetBlockHash());
387
13
        if (header != m_headers_cache.end()) {
388
6
            header_out = header->second;
389
6
            return true;
390
6
        }
391
13
    }
392
393
237
    DBVal entry;
394
237
    if (!index_util::LookUpOne(*m_db, {block_index->GetBlockHash(), block_index->nHeight}, entry)) {
395
101
        return false;
396
101
    }
397
398
136
    if (is_checkpoint &&
399
136
        m_headers_cache.size() < CF_HEADERS_CACHE_MAX_SZ) {
400
        // Add to the headers cache if this is a checkpoint height.
401
6
        m_headers_cache.emplace(block_index->GetBlockHash(), entry.header);
402
6
    }
403
404
136
    header_out = entry.header;
405
136
    return true;
406
237
}
407
408
bool BlockFilterIndex::LookupFilterRange(int start_height, const CBlockIndex* stop_index,
409
                                         std::vector<BlockFilter>& filters_out) const
410
230
{
411
230
    std::vector<DBVal> entries;
412
230
    if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
413
101
        return false;
414
101
    }
415
416
129
    filters_out.resize(entries.size());
417
129
    auto filter_pos_it = filters_out.begin();
418
647
    for (const auto& entry : entries) {
419
647
        if (!ReadFilterFromDisk(entry.pos, entry.hash, *filter_pos_it)) {
420
0
            return false;
421
0
        }
422
647
        ++filter_pos_it;
423
647
    }
424
425
129
    return true;
426
129
}
427
428
bool BlockFilterIndex::LookupFilterHashRange(int start_height, const CBlockIndex* stop_index,
429
                                             std::vector<uint256>& hashes_out) const
430
431
218
{
432
218
    std::vector<DBVal> entries;
433
218
    if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
434
101
        return false;
435
101
    }
436
437
117
    hashes_out.clear();
438
117
    hashes_out.reserve(entries.size());
439
2.21k
    for (const auto& entry : entries) {
440
2.21k
        hashes_out.push_back(entry.hash);
441
2.21k
    }
442
117
    return true;
443
218
}
444
445
BlockFilterIndex* GetBlockFilterIndex(BlockFilterType filter_type)
446
1.54k
{
447
1.54k
    auto it = g_filter_indexes.find(filter_type);
448
1.54k
    return it != g_filter_indexes.end() ? &it->second : nullptr;
449
1.54k
}
450
451
void ForEachBlockFilterIndex(std::function<void (BlockFilterIndex&)> fn)
452
63
{
453
63
    for (auto& entry : g_filter_indexes) fn(entry.second);
454
63
}
455
456
bool InitBlockFilterIndex(std::function<std::unique_ptr<interfaces::Chain>()> make_chain, BlockFilterType filter_type,
457
                          size_t n_cache_size, bool f_memory, bool f_wipe)
458
45
{
459
45
    auto result = g_filter_indexes.emplace(std::piecewise_construct,
460
45
                                           std::forward_as_tuple(filter_type),
461
45
                                           std::forward_as_tuple(make_chain(), filter_type,
462
45
                                                                 n_cache_size, f_memory, f_wipe));
463
45
    return result.second;
464
45
}
465
466
bool DestroyBlockFilterIndex(BlockFilterType filter_type)
467
4
{
468
4
    return g_filter_indexes.erase(filter_type);
469
4
}
470
471
void DestroyAllBlockFilterIndexes()
472
1.44k
{
473
1.44k
    g_filter_indexes.clear();
474
1.44k
}