Bitcoin ABC 0.32.5
P2P Digital Currency
blockfilterindex.cpp
Go to the documentation of this file.
1// Copyright (c) 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 <clientversion.h>
6#include <common/args.h>
7#include <dbwrapper.h>
9#include <node/blockstorage.h>
11#include <util/fs_helpers.h>
12#include <validation.h>
13
14#include <map>
15
35constexpr uint8_t DB_BLOCK_HASH{'s'};
36constexpr uint8_t DB_BLOCK_HEIGHT{'t'};
37constexpr uint8_t DB_FILTER_POS{'P'};
38
39// 16 MiB
40constexpr unsigned int MAX_FLTR_FILE_SIZE = 0x1000000;
42// 1 MiB
43constexpr unsigned int FLTR_FILE_CHUNK_SIZE = 0x100000;
44
52constexpr size_t CF_HEADERS_CACHE_MAX_SZ{2000};
53
54namespace {
55
56struct DBVal {
57 uint256 hash;
58 uint256 header;
59 FlatFilePos pos;
60
61 SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
62};
63
64struct DBHeightKey {
65 int height{0};
66
67 DBHeightKey() = default;
68 explicit DBHeightKey(int height_in) : height(height_in) {}
69
70 template <typename Stream> void Serialize(Stream &s) const {
72 ser_writedata32be(s, height);
73 }
74
75 template <typename Stream> void Unserialize(Stream &s) {
76 const uint8_t prefix{ser_readdata8(s)};
77 if (prefix != DB_BLOCK_HEIGHT) {
78 throw std::ios_base::failure(
79 "Invalid format for block filter index DB height key");
80 }
81 height = ser_readdata32be(s);
82 }
83};
84
85struct DBHashKey {
86 BlockHash hash;
87
88 explicit DBHashKey(const BlockHash &hash_in) : hash(hash_in) {}
89
90 SERIALIZE_METHODS(DBHashKey, obj) {
91 uint8_t prefix{DB_BLOCK_HASH};
93 if (prefix != DB_BLOCK_HASH) {
94 throw std::ios_base::failure(
95 "Invalid format for block filter index DB hash key");
96 }
97
98 READWRITE(obj.hash);
99 }
100};
101
102}; // namespace
103
104static std::map<BlockFilterType, BlockFilterIndex> g_filter_indexes;
105
106BlockFilterIndex::BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain,
107 BlockFilterType filter_type,
108 size_t n_cache_size, bool f_memory,
109 bool f_wipe)
110 : BaseIndex(std::move(chain),
111 BlockFilterTypeName(filter_type) + " block filter index"),
112 m_filter_type(filter_type) {
113 const std::string &filter_name = BlockFilterTypeName(filter_type);
114 if (filter_name.empty()) {
115 throw std::invalid_argument("unknown filter_type");
116 }
117
118 fs::path path =
119 gArgs.GetDataDirNet() / "indexes" / "blockfilter" / filter_name;
121
122 m_db = std::make_unique<BaseIndex::DB>(path / "db", n_cache_size, f_memory,
123 f_wipe);
124 m_filter_fileseq = std::make_unique<FlatFileSeq>(std::move(path), "fltr",
126}
127
129 const std::optional<interfaces::BlockKey> &block) {
130 if (!m_db->Read(DB_FILTER_POS, m_next_filter_pos)) {
131 // Check that the cause of the read failure is that the key does not
132 // exist. Any other errors indicate database corruption or a disk
133 // failure, and starting the index would cause further corruption.
134 if (m_db->Exists(DB_FILTER_POS)) {
135 LogError(
136 "%s: Cannot read current %s state; index may be corrupted\n",
137 __func__, GetName());
138 return false;
139 }
140
141 // If the DB_FILTER_POS is not set, then initialize to the first
142 // location.
145 }
146 return true;
147}
148
150 const FlatFilePos &pos = m_next_filter_pos;
151
152 // Flush current filter file to disk.
153 AutoFile file{m_filter_fileseq->Open(pos)};
154 if (file.IsNull()) {
155 LogError("%s: Failed to open filter file %d\n", __func__, pos.nFile);
156 return false;
157 }
158 if (!FileCommit(file.Get())) {
159 LogError("%s: Failed to commit filter file %d\n", __func__, pos.nFile);
160 return false;
161 }
162
163 batch.Write(DB_FILTER_POS, pos);
164 return true;
165}
166
168 BlockFilter &filter) const {
169 AutoFile filein{m_filter_fileseq->Open(pos, true)};
170 if (filein.IsNull()) {
171 return false;
172 }
173
174 BlockHash block_hash;
175 std::vector<uint8_t> encoded_filter;
176 try {
177 filein >> block_hash >> encoded_filter;
178 filter =
179 BlockFilter(GetFilterType(), block_hash, std::move(encoded_filter));
180 } catch (const std::exception &e) {
181 LogError("%s: Failed to deserialize block filter from disk: %s\n",
182 __func__, e.what());
183 return false;
184 }
185
186 return true;
187}
188
190 const BlockFilter &filter) {
191 assert(filter.GetFilterType() == GetFilterType());
192
193 size_t data_size =
196
197 // If writing the filter would overflow the file, flush and move to the next
198 // one.
199 if (pos.nPos + data_size > MAX_FLTR_FILE_SIZE) {
200 AutoFile last_file{m_filter_fileseq->Open(pos)};
201 if (last_file.IsNull()) {
202 LogPrintf("%s: Failed to open filter file %d\n", __func__,
203 pos.nFile);
204 return 0;
205 }
206 if (!TruncateFile(last_file.Get(), pos.nPos)) {
207 LogPrintf("%s: Failed to truncate filter file %d\n", __func__,
208 pos.nFile);
209 return 0;
210 }
211 if (!FileCommit(last_file.Get())) {
212 LogPrintf("%s: Failed to commit filter file %d\n", __func__,
213 pos.nFile);
214 return 0;
215 }
216
217 pos.nFile++;
218 pos.nPos = 0;
219 }
220
221 // Pre-allocate sufficient space for filter data.
222 bool out_of_space;
223 m_filter_fileseq->Allocate(pos, data_size, out_of_space);
224 if (out_of_space) {
225 LogPrintf("%s: out of disk space\n", __func__);
226 return 0;
227 }
228
229 AutoFile fileout{m_filter_fileseq->Open(pos)};
230 if (fileout.IsNull()) {
231 LogPrintf("%s: Failed to open filter file %d\n", __func__, pos.nFile);
232 return 0;
233 }
234
235 fileout << filter.GetBlockHash() << filter.GetEncodedFilter();
236 return data_size;
237}
238
240 const CBlockIndex *pindex) {
241 CBlockUndo block_undo;
242 uint256 prev_header;
243
244 if (pindex->nHeight > 0) {
245 if (!m_chainstate->m_blockman.UndoReadFromDisk(block_undo, *pindex)) {
246 return false;
247 }
248
249 std::pair<BlockHash, DBVal> read_out;
250 if (!m_db->Read(DBHeightKey(pindex->nHeight - 1), read_out)) {
251 return false;
252 }
253
254 BlockHash expected_block_hash = pindex->pprev->GetBlockHash();
255 if (read_out.first != expected_block_hash) {
256 LogError("%s: previous block header belongs to unexpected "
257 "block %s; expected %s\n",
258 __func__, read_out.first.ToString(),
259 expected_block_hash.ToString());
260 return false;
261 }
262
263 prev_header = read_out.second.header;
264 }
265
266 BlockFilter filter(m_filter_type, block, block_undo);
267
268 size_t bytes_written = WriteFilterToDisk(m_next_filter_pos, filter);
269 if (bytes_written == 0) {
270 return false;
271 }
272
273 std::pair<BlockHash, DBVal> value;
274 value.first = pindex->GetBlockHash();
275 value.second.hash = filter.GetHash();
276 value.second.header = filter.ComputeHeader(prev_header);
277 value.second.pos = m_next_filter_pos;
278
279 if (!m_db->Write(DBHeightKey(pindex->nHeight), value)) {
280 return false;
281 }
282
283 m_next_filter_pos.nPos += bytes_written;
284 return true;
285}
286
288 const std::string &index_name,
289 int start_height, int stop_height) {
290 DBHeightKey key(start_height);
291 db_it.Seek(key);
292
293 for (int height = start_height; height <= stop_height; ++height) {
294 if (!db_it.GetKey(key) || key.height != height) {
295 LogError("%s: unexpected key in %s: expected (%c, %d)\n", __func__,
296 index_name, DB_BLOCK_HEIGHT, height);
297 return false;
298 }
299
300 std::pair<BlockHash, DBVal> value;
301 if (!db_it.GetValue(value)) {
302 LogError("%s: unable to read value in %s at key (%c, %d)\n",
303 __func__, index_name, DB_BLOCK_HEIGHT, height);
304 return false;
305 }
306
307 batch.Write(DBHashKey(value.first), std::move(value.second));
308
309 db_it.Next();
310 }
311 return true;
312}
313
314bool BlockFilterIndex::Rewind(const CBlockIndex *current_tip,
315 const CBlockIndex *new_tip) {
316 assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
317
318 CDBBatch batch(*m_db);
319 std::unique_ptr<CDBIterator> db_it(m_db->NewIterator());
320
321 // During a reorg, we need to copy all filters for blocks that are getting
322 // disconnected from the height index to the hash index so we can still find
323 // them when the height index entries are overwritten.
324 if (!CopyHeightIndexToHashIndex(*db_it, batch, m_name, new_tip->nHeight,
325 current_tip->nHeight)) {
326 return false;
327 }
328
329 // The latest filter position gets written in Commit by the call to the
330 // BaseIndex::Rewind. But since this creates new references to the filter,
331 // the position should get updated here atomically as well in case Commit
332 // fails.
334 if (!m_db->WriteBatch(batch)) {
335 return false;
336 }
337
338 return BaseIndex::Rewind(current_tip, new_tip);
339}
340
341static bool LookupOne(const CDBWrapper &db, const CBlockIndex *block_index,
342 DBVal &result) {
343 // First check if the result is stored under the height index and the value
344 // there matches the block hash. This should be the case if the block is on
345 // the active chain.
346 std::pair<BlockHash, DBVal> read_out;
347 if (!db.Read(DBHeightKey(block_index->nHeight), read_out)) {
348 return false;
349 }
350 if (read_out.first == block_index->GetBlockHash()) {
351 result = std::move(read_out.second);
352 return true;
353 }
354
355 // If value at the height index corresponds to an different block, the
356 // result will be stored in the hash index.
357 return db.Read(DBHashKey(block_index->GetBlockHash()), result);
358}
359
360static bool LookupRange(CDBWrapper &db, const std::string &index_name,
361 int start_height, const CBlockIndex *stop_index,
362 std::vector<DBVal> &results) {
363 if (start_height < 0) {
364 LogError("%s: start height (%d) is negative\n", __func__, start_height);
365 return false;
366 }
367 if (start_height > stop_index->nHeight) {
368 LogError("%s: start height (%d) is greater than stop height (%d)\n",
369 __func__, start_height, stop_index->nHeight);
370 return false;
371 }
372
373 size_t results_size =
374 static_cast<size_t>(stop_index->nHeight - start_height + 1);
375 std::vector<std::pair<BlockHash, DBVal>> values(results_size);
376
377 DBHeightKey key(start_height);
378 std::unique_ptr<CDBIterator> db_it(db.NewIterator());
379 db_it->Seek(DBHeightKey(start_height));
380 for (int height = start_height; height <= stop_index->nHeight; ++height) {
381 if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
382 return false;
383 }
384
385 size_t i = static_cast<size_t>(height - start_height);
386 if (!db_it->GetValue(values[i])) {
387 LogError("%s: unable to read value in %s at key (%c, %d)\n",
388 __func__, index_name, DB_BLOCK_HEIGHT, height);
389 return false;
390 }
391
392 db_it->Next();
393 }
394
395 results.resize(results_size);
396
397 // Iterate backwards through block indexes collecting results in order to
398 // access the block hash of each entry in case we need to look it up in the
399 // hash index.
400 for (const CBlockIndex *block_index = stop_index;
401 block_index && block_index->nHeight >= start_height;
402 block_index = block_index->pprev) {
403 BlockHash block_hash = block_index->GetBlockHash();
404
405 size_t i = static_cast<size_t>(block_index->nHeight - start_height);
406 if (block_hash == values[i].first) {
407 results[i] = std::move(values[i].second);
408 continue;
409 }
410
411 if (!db.Read(DBHashKey(block_hash), results[i])) {
412 LogError("%s: unable to read value in %s at key (%c, %s)\n",
413 __func__, index_name, DB_BLOCK_HASH,
414 block_hash.ToString());
415 return false;
416 }
417 }
418
419 return true;
420}
421
423 BlockFilter &filter_out) const {
424 DBVal entry;
425 if (!LookupOne(*m_db, block_index, entry)) {
426 return false;
427 }
428
429 return ReadFilterFromDisk(entry.pos, filter_out);
430}
431
433 uint256 &header_out) {
435
436 bool is_checkpoint{block_index->nHeight % CFCHECKPT_INTERVAL == 0};
437
438 if (is_checkpoint) {
439 // Try to find the block in the headers cache if this is a checkpoint
440 // height.
441 auto header = m_headers_cache.find(block_index->GetBlockHash());
442 if (header != m_headers_cache.end()) {
443 header_out = header->second;
444 return true;
445 }
446 }
447
448 DBVal entry;
449 if (!LookupOne(*m_db, block_index, entry)) {
450 return false;
451 }
452
453 if (is_checkpoint && m_headers_cache.size() < CF_HEADERS_CACHE_MAX_SZ) {
454 // Add to the headers cache if this is a checkpoint height.
455 m_headers_cache.emplace(block_index->GetBlockHash(), entry.header);
456 }
457
458 header_out = entry.header;
459 return true;
460}
461
463 int start_height, const CBlockIndex *stop_index,
464 std::vector<BlockFilter> &filters_out) const {
465 std::vector<DBVal> entries;
466 if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
467 return false;
468 }
469
470 filters_out.resize(entries.size());
471 auto filter_pos_it = filters_out.begin();
472 for (const auto &entry : entries) {
473 if (!ReadFilterFromDisk(entry.pos, *filter_pos_it)) {
474 return false;
475 }
476 ++filter_pos_it;
477 }
478
479 return true;
480}
481
483 int start_height, const CBlockIndex *stop_index,
484 std::vector<uint256> &hashes_out) const
485
486{
487 std::vector<DBVal> entries;
488 if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
489 return false;
490 }
491
492 hashes_out.clear();
493 hashes_out.reserve(entries.size());
494 for (const auto &entry : entries) {
495 hashes_out.push_back(entry.hash);
496 }
497 return true;
498}
499
501 auto it = g_filter_indexes.find(filter_type);
502 return it != g_filter_indexes.end() ? &it->second : nullptr;
503}
504
505void ForEachBlockFilterIndex(std::function<void(BlockFilterIndex &)> fn) {
506 for (auto &entry : g_filter_indexes) {
507 fn(entry.second);
508 }
509}
510
512 std::function<std::unique_ptr<interfaces::Chain>()> make_chain,
513 BlockFilterType filter_type, size_t n_cache_size, bool f_memory,
514 bool f_wipe) {
515 auto result = g_filter_indexes.emplace(
516 std::piecewise_construct, std::forward_as_tuple(filter_type),
517 std::forward_as_tuple(make_chain(), filter_type, n_cache_size, f_memory,
518 f_wipe));
519 return result.second;
520}
521
523 return g_filter_indexes.erase(filter_type);
524}
525
527 g_filter_indexes.clear();
528}
ArgsManager gArgs
Definition: args.cpp:40
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
BlockFilterType
Definition: blockfilter.h:88
constexpr unsigned int FLTR_FILE_CHUNK_SIZE
The pre-allocation chunk size for fltr?????.dat files.
bool DestroyBlockFilterIndex(BlockFilterType filter_type)
Destroy the block filter index with the given type.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
static bool CopyHeightIndexToHashIndex(CDBIterator &db_it, CDBBatch &batch, const std::string &index_name, int start_height, int stop_height)
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
constexpr uint8_t DB_FILTER_POS
static bool LookupOne(const CDBWrapper &db, const CBlockIndex *block_index, DBVal &result)
constexpr unsigned int MAX_FLTR_FILE_SIZE
constexpr uint8_t DB_BLOCK_HASH
The index database stores three items for each block: the disk location of the encoded filter,...
void ForEachBlockFilterIndex(std::function< void(BlockFilterIndex &)> fn)
Iterate over all running block filter indexes, invoking fn on each.
constexpr size_t CF_HEADERS_CACHE_MAX_SZ
Maximum size of the cfheaders cache.
bool InitBlockFilterIndex(std::function< std::unique_ptr< interfaces::Chain >()> make_chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory, bool f_wipe)
Initialize a block filter index for the given type if one does not already exist.
static bool LookupRange(CDBWrapper &db, const std::string &index_name, int start_height, const CBlockIndex *stop_index, std::vector< DBVal > &results)
constexpr uint8_t DB_BLOCK_HEIGHT
static std::map< BlockFilterType, BlockFilterIndex > g_filter_indexes
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:239
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:515
Base class for indices of blockchain data.
Definition: base.h:37
const std::string & GetName() const LIFETIMEBOUND
Get the name of the index for display in logs.
Definition: base.h:143
const std::string m_name
Definition: base.h:103
Chainstate * m_chainstate
Definition: base.h:102
virtual bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip)
Rewind index to an earlier chain tip during a chain reorg.
Definition: base.cpp:252
Complete block filter struct as defined in BIP 157.
Definition: blockfilter.h:111
uint256 ComputeHeader(const uint256 &prev_header) const
Compute the filter header given the previous one.
BlockFilterType GetFilterType() const
Definition: blockfilter.h:130
const BlockHash & GetBlockHash() const
Definition: blockfilter.h:131
uint256 GetHash() const
Compute the filter hash.
const std::vector< uint8_t > & GetEncodedFilter() const
Definition: blockfilter.h:134
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
std::unique_ptr< BaseIndex::DB > m_db
bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip) override
Rewind index to an earlier chain tip during a chain reorg.
bool ReadFilterFromDisk(const FlatFilePos &pos, BlockFilter &filter) const
bool LookupFilterRange(int start_height, const CBlockIndex *stop_index, std::vector< BlockFilter > &filters_out) const
Get a range of filters between two heights on a chain.
bool CustomInit(const std::optional< interfaces::BlockKey > &block) override
Initialize internal state from the database and block index.
BlockFilterType GetFilterType() const
bool CustomCommit(CDBBatch &batch) override
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
BlockFilterType m_filter_type
BlockFilterIndex(std::unique_ptr< interfaces::Chain > chain, BlockFilterType filter_type, size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
Constructs the index, which becomes available to be queried.
bool WriteBlock(const CBlock &block, const CBlockIndex *pindex) override
Write update index entries for a newly connected block.
std::unique_ptr< FlatFileSeq > m_filter_fileseq
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
bool LookupFilterHashRange(int start_height, const CBlockIndex *stop_index, std::vector< uint256 > &hashes_out) const
Get a range of filter hashes between two heights on a chain.
size_t WriteFilterToDisk(FlatFilePos &pos, const BlockFilter &filter)
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
FlatFilePos m_next_filter_pos
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
Definition: blockindex.cpp:62
BlockHash GetBlockHash() const
Definition: blockindex.h:130
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
Undo information for a CBlock.
Definition: undo.h:73
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:77
void Write(const K &key, const V &value)
Definition: dbwrapper.h:100
bool GetValue(V &value)
Definition: dbwrapper.h:181
bool GetKey(K &key)
Definition: dbwrapper.h:170
void Seek(const K &key)
Definition: dbwrapper.h:160
void Next()
Definition: dbwrapper.cpp:259
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:791
std::string ToString() const
Definition: uint256.h:80
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
256-bit opaque blob.
Definition: uint256.h:129
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
bool TruncateFile(FILE *file, unsigned int length)
Definition: fs_helpers.cpp:170
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:126
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition: fs.h:184
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
const char * prefix
Definition: rest.cpp:813
CAddrDb db
Definition: main.cpp:35
void Serialize(Stream &, V)=delete
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:86
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:77
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
Definition: serialize.h:289
void Unserialize(Stream &, V)=delete
void ser_writedata8(Stream &s, uint8_t obj)
Lowest-level serialization and conversion.
Definition: serialize.h:58
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1280
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:106
#define READWRITE(...)
Definition: serialize.h:189
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
int nFile
Definition: flatfile.h:15
unsigned int nPos
Definition: flatfile.h:16
#define LOCK(cs)
Definition: sync.h:306
assert(!tx.IsCoinBase())