9 #include <validation.h> 60 template <
typename Stream,
typename Operation>
61 inline void SerializationOp(Stream &s, Operation ser_action) {
71 DBHeightKey() : height(0) {}
72 explicit DBHeightKey(
int height_in) : height(height_in) {}
74 template <
typename Stream>
void Serialize(Stream &s)
const {
79 template <
typename Stream>
void Unserialize(Stream &s) {
82 throw std::ios_base::failure(
83 "Invalid format for block filter index DB height key");
92 explicit DBHashKey(
const BlockHash &hash_in) : hash(hash_in) {}
96 template <
typename Stream,
typename Operation>
97 inline void SerializationOp(Stream &s, Operation ser_action) {
101 throw std::ios_base::failure(
102 "Invalid format for block filter index DB hash key");
114 size_t n_cache_size,
bool f_memory,
116 : m_filter_type(filter_type) {
118 if (filter_name.empty()) {
119 throw std::invalid_argument(
"unknown filter_type");
122 fs::path path =
GetDataDir() /
"indexes" /
"blockfilter" / filter_name;
123 fs::create_directories(path);
125 m_name = filter_name +
" block filter index";
126 m_db = std::make_unique<BaseIndex::DB>(path /
"db", n_cache_size, f_memory,
139 "%s: Cannot read current %s state; index may be corrupted",
157 return error(
"%s: Failed to open filter file %d", __func__, pos.
nFile);
160 return error(
"%s: Failed to commit filter file %d", __func__,
172 if (filein.IsNull()) {
177 std::vector<uint8_t> encoded_filter;
179 filein >> block_hash >> encoded_filter;
182 }
catch (
const std::exception &e) {
183 return error(
"%s: Failed to deserialize block filter from disk: %s",
203 if (last_file.IsNull()) {
204 LogPrintf(
"%s: Failed to open filter file %d\n", __func__,
209 LogPrintf(
"%s: Failed to truncate filter file %d\n", __func__,
214 LogPrintf(
"%s: Failed to commit filter file %d\n", __func__,
227 LogPrintf(
"%s: out of disk space\n", __func__);
232 if (fileout.IsNull()) {
233 LogPrintf(
"%s: Failed to open filter file %d\n", __func__, pos.
nFile);
251 std::pair<BlockHash, DBVal> read_out;
252 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
257 if (read_out.first != expected_block_hash) {
258 return error(
"%s: previous block header belongs to unexpected " 259 "block %s; expected %s",
260 __func__, read_out.first.ToString(),
264 prev_header = read_out.second.header;
270 if (bytes_written == 0) {
274 std::pair<BlockHash, DBVal> value;
276 value.second.hash = filter.
GetHash();
280 if (!
m_db->Write(DBHeightKey(pindex->
nHeight), value)) {
289 const std::string &index_name,
290 int start_height,
int stop_height) {
291 DBHeightKey key(start_height);
294 for (
int height = start_height; height <= stop_height; ++height) {
295 if (!db_it.
GetKey(key) || key.height != height) {
296 return error(
"%s: unexpected key in %s: expected (%c, %d)",
300 std::pair<BlockHash, DBVal> value;
302 return error(
"%s: unable to read value in %s at key (%c, %d)",
306 batch.
Write(DBHashKey(value.first), std::move(value.second));
318 std::unique_ptr<CDBIterator> db_it(
m_db->NewIterator());
333 if (!
m_db->WriteBatch(batch)) {
345 std::pair<BlockHash, DBVal> read_out;
346 if (!db.
Read(DBHeightKey(block_index->
nHeight), read_out)) {
350 result = std::move(read_out.second);
361 std::vector<DBVal> &results) {
362 if (start_height < 0) {
363 return error(
"%s: start height (%d) is negative", __func__,
366 if (start_height > stop_index->
nHeight) {
367 return error(
"%s: start height (%d) is greater than stop height (%d)",
368 __func__, start_height, stop_index->
nHeight);
371 size_t results_size =
372 static_cast<size_t>(stop_index->
nHeight - start_height + 1);
373 std::vector<std::pair<BlockHash, DBVal>> values(results_size);
375 DBHeightKey key(start_height);
376 std::unique_ptr<CDBIterator> db_it(db.
NewIterator());
377 db_it->Seek(DBHeightKey(start_height));
378 for (
int height = start_height; height <= stop_index->
nHeight; ++height) {
379 if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
383 size_t i =
static_cast<size_t>(height - start_height);
384 if (!db_it->GetValue(values[i])) {
385 return error(
"%s: unable to read value in %s at key (%c, %d)",
392 results.resize(results_size);
398 block_index && block_index->
nHeight >= start_height;
399 block_index = block_index->pprev) {
400 BlockHash block_hash = block_index->GetBlockHash();
402 size_t i =
static_cast<size_t>(block_index->nHeight - start_height);
403 if (block_hash == values[i].first) {
404 results[i] = std::move(values[i].second);
408 if (!db.
Read(DBHashKey(block_hash), results[i])) {
409 return error(
"%s: unable to read value in %s at key (%c, %s)",
437 auto header = m_headers_cache.find(block_index->
GetBlockHash());
438 if (header != m_headers_cache.end()) {
439 header_out = header->second;
451 m_headers_cache.emplace(block_index->
GetBlockHash(), entry.header);
454 header_out = entry.header;
460 std::vector<BlockFilter> &filters_out)
const {
461 std::vector<DBVal> entries;
466 filters_out.resize(entries.size());
467 auto filter_pos_it = filters_out.begin();
468 for (
const auto &entry : entries) {
480 std::vector<uint256> &hashes_out)
const 483 std::vector<DBVal> entries;
489 hashes_out.reserve(entries.size());
490 for (
const auto &entry : entries) {
491 hashes_out.push_back(entry.hash);
508 bool f_memory,
bool f_wipe) {
510 std::piecewise_construct, std::forward_as_tuple(filter_type),
511 std::forward_as_tuple(filter_type, n_cache_size, f_memory, f_wipe));
512 return result.second;
bool LookupFilter(const CBlockIndex *block_index, BlockFilter &filter_out) const
Get a single filter by block.
BlockFilterIndex is used to store and retrieve block filters, hashes, and headers for a range of bloc...
constexpr char DB_BLOCK_HEIGHT
bool FileCommit(FILE *file)
constexpr char DB_BLOCK_HASH
The index database stores three items for each block: the disk location of the encoded filter...
virtual bool Init()
Initialize internal state from the database and block index.
uint8_t ser_readdata8(Stream &s)
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Batch of changes queued to be written to a CDBWrapper.
static bool LookupRange(CDBWrapper &db, const std::string &index_name, int start_height, const CBlockIndex *stop_index, std::vector< DBVal > &results)
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
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.
constexpr unsigned int MAX_FLTR_FILE_SIZE
bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip) override
Rewind index to an earlier chain tip during a chain reorg.
const BlockHash & GetBlockHash() const
static void LogPrintf(const char *fmt, const Args &... args)
bool WriteBlock(const CBlock &block, const CBlockIndex *pindex) override
Write update index entries for a newly connected block.
bool InitBlockFilterIndex(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. ...
virtual bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip)
Rewind index to an earlier chain tip during a chain reorg.
std::unique_ptr< BaseIndex::DB > m_db
CDBIterator * NewIterator()
uint256 GetHash() const
Compute the filter hash.
size_t GetSerializeSize(const T &t, int nVersion=0)
void Serialize(Stream &s, char a)
constexpr char DB_FILTER_POS
const std::vector< uint8_t > & GetEncodedFilter() const
BlockHash GetBlockHash() const
static bool CopyHeightIndexToHashIndex(CDBIterator &db_it, CDBBatch &batch, const std::string &index_name, int start_height, int stop_height)
bool ReadFilterFromDisk(const FlatFilePos &pos, BlockFilter &filter) const
size_t WriteFilterToDisk(FlatFilePos &pos, const BlockFilter &filter)
Complete block filter struct as defined in BIP 157.
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex *pindex)
BlockFilterIndex(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.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
const fs::path & GetDataDir(bool fNetSpecific)
constexpr unsigned int FLTR_FILE_CHUNK_SIZE
The pre-allocation chunk size for fltr?????.dat files.
void Write(const K &key, const V &value)
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.
virtual bool CommitInternal(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
std::string ToString() const
void ser_writedata32be(Stream &s, uint32_t obj)
bool Read(const K &key, V &value) const
BlockFilterType m_filter_type
static constexpr int CFCHECKPT_INTERVAL
Interval between compact filter checkpoints.
uint256 ComputeHeader(const uint256 &prev_header) const
Compute the filter header given the previous one.
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
bool TruncateFile(FILE *file, unsigned int length)
A BlockHash is a unqiue identifier for a block.
The block chain is a tree shaped structure starting with the genesis block at the root...
bool DestroyBlockFilterIndex(BlockFilterType filter_type)
Destroy the block filter index with the given type.
Undo information for a CBlock.
FlatFilePos m_next_filter_pos
BlockFilterType GetFilterType() const
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out)
Get a single filter header by block.
static std::map< BlockFilterType, BlockFilterIndex > g_filter_indexes
uint32_t ser_readdata32be(Stream &s)
void Unserialize(Stream &s, char &a)
bool CommitInternal(CDBBatch &batch) override
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
std::unique_ptr< FlatFileSeq > m_filter_fileseq
int nHeight
height of the entry in the chain. The genesis block has height 0
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
bool Init() override
Initialize internal state from the database and block index.
BlockFilterType GetFilterType() 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 error(const char *fmt, const Args &... args)
static bool LookupOne(const CDBWrapper &db, const CBlockIndex *block_index, DBVal &result)
Non-refcounted RAII wrapper for FILE*.
void ser_writedata8(Stream &s, uint8_t obj)
Lowest-level serialization and conversion.
const char * GetName() const override
Get the name of the index for display in logs.
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.