Bitcoin ABC 0.31.0
P2P Digital Currency
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 <common/args.h>
6#include <dbwrapper.h>
8#include <node/blockstorage.h>
10#include <util/fs_helpers.h>
11#include <validation.h>
12
13#include <map>
14
34constexpr uint8_t DB_BLOCK_HASH{'s'};
35constexpr uint8_t DB_BLOCK_HEIGHT{'t'};
36constexpr uint8_t DB_FILTER_POS{'P'};
37
38// 16 MiB
39constexpr unsigned int MAX_FLTR_FILE_SIZE = 0x1000000;
41// 1 MiB
42constexpr unsigned int FLTR_FILE_CHUNK_SIZE = 0x100000;
43
51constexpr size_t CF_HEADERS_CACHE_MAX_SZ{2000};
52
53namespace {
54
55struct DBVal {
56 uint256 hash;
57 uint256 header;
58 FlatFilePos pos;
59
60 SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
61};
62
63struct DBHeightKey {
64 int height;
65
66 DBHeightKey() : height(0) {}
67 explicit DBHeightKey(int height_in) : height(height_in) {}
68
69 template <typename Stream> void Serialize(Stream &s) const {
71 ser_writedata32be(s, height);
72 }
73
74 template <typename Stream> void Unserialize(Stream &s) {
75 const uint8_t prefix{ser_readdata8(s)};
76 if (prefix != DB_BLOCK_HEIGHT) {
77 throw std::ios_base::failure(
78 "Invalid format for block filter index DB height key");
79 }
80 height = ser_readdata32be(s);
81 }
82};
83
84struct DBHashKey {
85 BlockHash hash;
86
87 explicit DBHashKey(const BlockHash &hash_in) : hash(hash_in) {}
88
89 SERIALIZE_METHODS(DBHashKey, obj) {
90 uint8_t prefix{DB_BLOCK_HASH};
92 if (prefix != DB_BLOCK_HASH) {
93 throw std::ios_base::failure(
94 "Invalid format for block filter index DB hash key");
95 }
96
97 READWRITE(obj.hash);
98 }
99};
100
101}; // namespace
102
103static std::map<BlockFilterType, BlockFilterIndex> g_filter_indexes;
104
105BlockFilterIndex::BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain,
106 BlockFilterType filter_type,
107 size_t n_cache_size, bool f_memory,
108 bool f_wipe)
109 : BaseIndex(std::move(chain),
110 BlockFilterTypeName(filter_type) + " block filter index"),
111 m_filter_type(filter_type) {
112 const std::string &filter_name = BlockFilterTypeName(filter_type);
113 if (filter_name.empty()) {
114 throw std::invalid_argument("unknown filter_type");
115 }
116
117 fs::path path =
118 gArgs.GetDataDirNet() / "indexes" / "blockfilter" / filter_name;
120
121 m_db = std::make_unique<BaseIndex::DB>(path / "db", n_cache_size, f_memory,
122 f_wipe);
123 m_filter_fileseq = std::make_unique<FlatFileSeq>(std::move(path), "fltr",
125}
126
128 const std::optional<interfaces::BlockKey> &block) {
129 if (!m_db->Read(DB_FILTER_POS, m_next_filter_pos)) {
130 // Check that the cause of the read failure is that the key does not
131 // exist. Any other errors indicate database corruption or a disk
132 // failure, and starting the index would cause further corruption.
133 if (m_db->Exists(DB_FILTER_POS)) {
134 return error(
135 "%s: Cannot read current %s state; index may be corrupted",
136 __func__, GetName());
137 }
138
139 // If the DB_FILTER_POS is not set, then initialize to the first
140 // location.
143 }
144 return true;
145}
146
148 const FlatFilePos &pos = m_next_filter_pos;
149
150 // Flush current filter file to disk.
151 AutoFile file{m_filter_fileseq->Open(pos)};
152 if (file.IsNull()) {
153 return error("%s: Failed to open filter file %d", __func__, pos.nFile);
154 }
155 if (!FileCommit(file.Get())) {
156 return error("%s: Failed to commit filter file %d", __func__,
157 pos.nFile);
158 }
159
160 batch.Write(DB_FILTER_POS, pos);
161 return BaseIndex::CommitInternal(batch);
162}
163
165 BlockFilter &filter) const {
166 AutoFile filein{m_filter_fileseq->Open(pos, true)};
167 if (filein.IsNull()) {
168 return false;
169 }
170
171 BlockHash block_hash;
172 std::vector<uint8_t> encoded_filter;
173 try {
174 filein >> block_hash >> encoded_filter;
175 filter =
176 BlockFilter(GetFilterType(), block_hash, std::move(encoded_filter));
177 } catch (const std::exception &e) {
178 return error("%s: Failed to deserialize block filter from disk: %s",
179 __func__, e.what());
180 }
181
182 return true;
183}
184
186 const BlockFilter &filter) {
187 assert(filter.GetFilterType() == GetFilterType());
188
189 size_t data_size =
192
193 // If writing the filter would overflow the file, flush and move to the next
194 // one.
195 if (pos.nPos + data_size > MAX_FLTR_FILE_SIZE) {
196 AutoFile last_file{m_filter_fileseq->Open(pos)};
197 if (last_file.IsNull()) {
198 LogPrintf("%s: Failed to open filter file %d\n", __func__,
199 pos.nFile);
200 return 0;
201 }
202 if (!TruncateFile(last_file.Get(), pos.nPos)) {
203 LogPrintf("%s: Failed to truncate filter file %d\n", __func__,
204 pos.nFile);
205 return 0;
206 }
207 if (!FileCommit(last_file.Get())) {
208 LogPrintf("%s: Failed to commit filter file %d\n", __func__,
209 pos.nFile);
210 return 0;
211 }
212
213 pos.nFile++;
214 pos.nPos = 0;
215 }
216
217 // Pre-allocate sufficient space for filter data.
218 bool out_of_space;
219 m_filter_fileseq->Allocate(pos, data_size, out_of_space);
220 if (out_of_space) {
221 LogPrintf("%s: out of disk space\n", __func__);
222 return 0;
223 }
224
225 AutoFile fileout{m_filter_fileseq->Open(pos)};
226 if (fileout.IsNull()) {
227 LogPrintf("%s: Failed to open filter file %d\n", __func__, pos.nFile);
228 return 0;
229 }
230
231 fileout << filter.GetBlockHash() << filter.GetEncodedFilter();
232 return data_size;
233}
234
236 const CBlockIndex *pindex) {
237 CBlockUndo block_undo;
238 uint256 prev_header;
239
240 if (pindex->nHeight > 0) {
241 if (!m_chainstate->m_blockman.UndoReadFromDisk(block_undo, *pindex)) {
242 return false;
243 }
244
245 std::pair<BlockHash, DBVal> read_out;
246 if (!m_db->Read(DBHeightKey(pindex->nHeight - 1), read_out)) {
247 return false;
248 }
249
250 BlockHash expected_block_hash = pindex->pprev->GetBlockHash();
251 if (read_out.first != expected_block_hash) {
252 return error("%s: previous block header belongs to unexpected "
253 "block %s; expected %s",
254 __func__, read_out.first.ToString(),
255 expected_block_hash.ToString());
256 }
257
258 prev_header = read_out.second.header;
259 }
260
261 BlockFilter filter(m_filter_type, block, block_undo);
262
263 size_t bytes_written = WriteFilterToDisk(m_next_filter_pos, filter);
264 if (bytes_written == 0) {
265 return false;
266 }
267
268 std::pair<BlockHash, DBVal> value;
269 value.first = pindex->GetBlockHash();
270 value.second.hash = filter.GetHash();
271 value.second.header = filter.ComputeHeader(prev_header);
272 value.second.pos = m_next_filter_pos;
273
274 if (!m_db->Write(DBHeightKey(pindex->nHeight), value)) {
275 return false;
276 }
277
278 m_next_filter_pos.nPos += bytes_written;
279 return true;
280}
281
283 const std::string &index_name,
284 int start_height, int stop_height) {
285 DBHeightKey key(start_height);
286 db_it.Seek(key);
287
288 for (int height = start_height; height <= stop_height; ++height) {
289 if (!db_it.GetKey(key) || key.height != height) {
290 return error("%s: unexpected key in %s: expected (%c, %d)",
291 __func__, index_name, DB_BLOCK_HEIGHT, height);
292 }
293
294 std::pair<BlockHash, DBVal> value;
295 if (!db_it.GetValue(value)) {
296 return error("%s: unable to read value in %s at key (%c, %d)",
297 __func__, index_name, DB_BLOCK_HEIGHT, height);
298 }
299
300 batch.Write(DBHashKey(value.first), std::move(value.second));
301
302 db_it.Next();
303 }
304 return true;
305}
306
307bool BlockFilterIndex::Rewind(const CBlockIndex *current_tip,
308 const CBlockIndex *new_tip) {
309 assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip);
310
311 CDBBatch batch(*m_db);
312 std::unique_ptr<CDBIterator> db_it(m_db->NewIterator());
313
314 // During a reorg, we need to copy all filters for blocks that are getting
315 // disconnected from the height index to the hash index so we can still find
316 // them when the height index entries are overwritten.
317 if (!CopyHeightIndexToHashIndex(*db_it, batch, m_name, new_tip->nHeight,
318 current_tip->nHeight)) {
319 return false;
320 }
321
322 // The latest filter position gets written in Commit by the call to the
323 // BaseIndex::Rewind. But since this creates new references to the filter,
324 // the position should get updated here atomically as well in case Commit
325 // fails.
327 if (!m_db->WriteBatch(batch)) {
328 return false;
329 }
330
331 return BaseIndex::Rewind(current_tip, new_tip);
332}
333
334static bool LookupOne(const CDBWrapper &db, const CBlockIndex *block_index,
335 DBVal &result) {
336 // First check if the result is stored under the height index and the value
337 // there matches the block hash. This should be the case if the block is on
338 // the active chain.
339 std::pair<BlockHash, DBVal> read_out;
340 if (!db.Read(DBHeightKey(block_index->nHeight), read_out)) {
341 return false;
342 }
343 if (read_out.first == block_index->GetBlockHash()) {
344 result = std::move(read_out.second);
345 return true;
346 }
347
348 // If value at the height index corresponds to an different block, the
349 // result will be stored in the hash index.
350 return db.Read(DBHashKey(block_index->GetBlockHash()), result);
351}
352
353static bool LookupRange(CDBWrapper &db, const std::string &index_name,
354 int start_height, const CBlockIndex *stop_index,
355 std::vector<DBVal> &results) {
356 if (start_height < 0) {
357 return error("%s: start height (%d) is negative", __func__,
358 start_height);
359 }
360 if (start_height > stop_index->nHeight) {
361 return error("%s: start height (%d) is greater than stop height (%d)",
362 __func__, start_height, stop_index->nHeight);
363 }
364
365 size_t results_size =
366 static_cast<size_t>(stop_index->nHeight - start_height + 1);
367 std::vector<std::pair<BlockHash, DBVal>> values(results_size);
368
369 DBHeightKey key(start_height);
370 std::unique_ptr<CDBIterator> db_it(db.NewIterator());
371 db_it->Seek(DBHeightKey(start_height));
372 for (int height = start_height; height <= stop_index->nHeight; ++height) {
373 if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
374 return false;
375 }
376
377 size_t i = static_cast<size_t>(height - start_height);
378 if (!db_it->GetValue(values[i])) {
379 return error("%s: unable to read value in %s at key (%c, %d)",
380 __func__, index_name, DB_BLOCK_HEIGHT, height);
381 }
382
383 db_it->Next();
384 }
385
386 results.resize(results_size);
387
388 // Iterate backwards through block indexes collecting results in order to
389 // access the block hash of each entry in case we need to look it up in the
390 // hash index.
391 for (const CBlockIndex *block_index = stop_index;
392 block_index && block_index->nHeight >= start_height;
393 block_index = block_index->pprev) {
394 BlockHash block_hash = block_index->GetBlockHash();
395
396 size_t i = static_cast<size_t>(block_index->nHeight - start_height);
397 if (block_hash == values[i].first) {
398 results[i] = std::move(values[i].second);
399 continue;
400 }
401
402 if (!db.Read(DBHashKey(block_hash), results[i])) {
403 return error("%s: unable to read value in %s at key (%c, %s)",
404 __func__, index_name, DB_BLOCK_HASH,
405 block_hash.ToString());
406 }
407 }
408
409 return true;
410}
411
413 BlockFilter &filter_out) const {
414 DBVal entry;
415 if (!LookupOne(*m_db, block_index, entry)) {
416 return false;
417 }
418
419 return ReadFilterFromDisk(entry.pos, filter_out);
420}
421
423 uint256 &header_out) {
425
426 bool is_checkpoint{block_index->nHeight % CFCHECKPT_INTERVAL == 0};
427
428 if (is_checkpoint) {
429 // Try to find the block in the headers cache if this is a checkpoint
430 // height.
431 auto header = m_headers_cache.find(block_index->GetBlockHash());
432 if (header != m_headers_cache.end()) {
433 header_out = header->second;
434 return true;
435 }
436 }
437
438 DBVal entry;
439 if (!LookupOne(*m_db, block_index, entry)) {
440 return false;
441 }
442
443 if (is_checkpoint && m_headers_cache.size() < CF_HEADERS_CACHE_MAX_SZ) {
444 // Add to the headers cache if this is a checkpoint height.
445 m_headers_cache.emplace(block_index->GetBlockHash(), entry.header);
446 }
447
448 header_out = entry.header;
449 return true;
450}
451
453 int start_height, const CBlockIndex *stop_index,
454 std::vector<BlockFilter> &filters_out) const {
455 std::vector<DBVal> entries;
456 if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
457 return false;
458 }
459
460 filters_out.resize(entries.size());
461 auto filter_pos_it = filters_out.begin();
462 for (const auto &entry : entries) {
463 if (!ReadFilterFromDisk(entry.pos, *filter_pos_it)) {
464 return false;
465 }
466 ++filter_pos_it;
467 }
468
469 return true;
470}
471
473 int start_height, const CBlockIndex *stop_index,
474 std::vector<uint256> &hashes_out) const
475
476{
477 std::vector<DBVal> entries;
478 if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
479 return false;
480 }
481
482 hashes_out.clear();
483 hashes_out.reserve(entries.size());
484 for (const auto &entry : entries) {
485 hashes_out.push_back(entry.hash);
486 }
487 return true;
488}
489
491 auto it = g_filter_indexes.find(filter_type);
492 return it != g_filter_indexes.end() ? &it->second : nullptr;
493}
494
495void ForEachBlockFilterIndex(std::function<void(BlockFilterIndex &)> fn) {
496 for (auto &entry : g_filter_indexes) {
497 fn(entry.second);
498 }
499}
500
502 std::function<std::unique_ptr<interfaces::Chain>()> make_chain,
503 BlockFilterType filter_type, size_t n_cache_size, bool f_memory,
504 bool f_wipe) {
505 auto result = g_filter_indexes.emplace(
506 std::piecewise_construct, std::forward_as_tuple(filter_type),
507 std::forward_as_tuple(make_chain(), filter_type, n_cache_size, f_memory,
508 f_wipe));
509 return result.second;
510}
511
513 return g_filter_indexes.erase(filter_type);
514}
515
517 g_filter_indexes.clear();
518}
ArgsManager gArgs
Definition: args.cpp:38
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:215
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:528
Base class for indices of blockchain data.
Definition: base.h:37
virtual bool CommitInternal(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
Definition: base.cpp:232
const std::string & GetName() const LIFETIMEBOUND
Get the name of the index for display in logs.
Definition: base.h:140
const std::string m_name
Definition: base.h:100
Chainstate * m_chainstate
Definition: base.h:99
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:243
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 CommitInternal(CDBBatch &batch) override
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
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
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:102
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:78
void Write(const K &key, const V &value)
Definition: dbwrapper.h:103
bool GetValue(V &value)
Definition: dbwrapper.h:184
bool GetKey(K &key)
Definition: dbwrapper.h:173
void Seek(const K &key)
Definition: dbwrapper.h:163
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:757
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:169
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:125
bool error(const char *fmt, const Args &...args)
Definition: logging.h:263
#define LogPrintf(...)
Definition: logging.h:227
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:179
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:817
CAddrDb db
Definition: main.cpp:35
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:83
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:74
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
Definition: serialize.h:213
void Unserialize(Stream &, char)=delete
void ser_writedata8(Stream &s, uint8_t obj)
Lowest-level serialization and conversion.
Definition: serialize.h:55
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1258
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:103
#define READWRITE(...)
Definition: serialize.h:166
void Serialize(Stream &, char)=delete
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())