12#include <validation.h>
67 DBHeightKey() =
default;
68 explicit DBHeightKey(
int height_in) : height(height_in) {}
70 template <
typename Stream>
void Serialize(Stream &s)
const {
75 template <
typename Stream>
void Unserialize(Stream &s) {
78 throw std::ios_base::failure(
79 "Invalid format for block filter index DB height key");
88 explicit DBHashKey(
const BlockHash &hash_in) : hash(hash_in) {}
94 throw std::ios_base::failure(
95 "Invalid format for block filter index DB hash key");
108 size_t n_cache_size,
bool f_memory,
112 m_filter_type(filter_type) {
114 if (filter_name.empty()) {
115 throw std::invalid_argument(
"unknown filter_type");
122 m_db = std::make_unique<BaseIndex::DB>(path /
"db", n_cache_size, f_memory,
129 const std::optional<interfaces::BlockKey> &block) {
136 "%s: Cannot read current %s state; index may be corrupted\n",
155 LogError(
"%s: Failed to open filter file %d\n", __func__, pos.
nFile);
159 LogError(
"%s: Failed to commit filter file %d\n", __func__, pos.
nFile);
170 if (filein.IsNull()) {
175 std::vector<uint8_t> encoded_filter;
177 filein >> block_hash >> encoded_filter;
180 }
catch (
const std::exception &e) {
181 LogError(
"%s: Failed to deserialize block filter from disk: %s\n",
201 if (last_file.IsNull()) {
202 LogPrintf(
"%s: Failed to open filter file %d\n", __func__,
207 LogPrintf(
"%s: Failed to truncate filter file %d\n", __func__,
212 LogPrintf(
"%s: Failed to commit filter file %d\n", __func__,
225 LogPrintf(
"%s: out of disk space\n", __func__);
230 if (fileout.IsNull()) {
231 LogPrintf(
"%s: Failed to open filter file %d\n", __func__, pos.
nFile);
249 std::pair<BlockHash, DBVal> read_out;
250 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
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(),
263 prev_header = read_out.second.header;
269 if (bytes_written == 0) {
273 std::pair<BlockHash, DBVal> value;
275 value.second.hash = filter.
GetHash();
279 if (!
m_db->Write(DBHeightKey(pindex->
nHeight), value)) {
288 const std::string &index_name,
289 int start_height,
int stop_height) {
290 DBHeightKey key(start_height);
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__,
300 std::pair<BlockHash, DBVal> value;
302 LogError(
"%s: unable to read value in %s at key (%c, %d)\n",
307 batch.
Write(DBHashKey(value.first), std::move(value.second));
319 std::unique_ptr<CDBIterator> db_it(
m_db->NewIterator());
334 if (!
m_db->WriteBatch(batch)) {
346 std::pair<BlockHash, DBVal> read_out;
347 if (!
db.Read(DBHeightKey(block_index->
nHeight), read_out)) {
351 result = std::move(read_out.second);
362 std::vector<DBVal> &results) {
363 if (start_height < 0) {
364 LogError(
"%s: start height (%d) is negative\n", __func__, start_height);
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);
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);
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) {
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",
395 results.resize(results_size);
401 block_index && block_index->
nHeight >= start_height;
402 block_index = block_index->pprev) {
403 BlockHash block_hash = block_index->GetBlockHash();
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);
411 if (!
db.Read(DBHashKey(block_hash), results[i])) {
412 LogError(
"%s: unable to read value in %s at key (%c, %s)\n",
441 auto header = m_headers_cache.find(block_index->
GetBlockHash());
442 if (header != m_headers_cache.end()) {
443 header_out = header->second;
455 m_headers_cache.emplace(block_index->
GetBlockHash(), entry.header);
458 header_out = entry.header;
464 std::vector<BlockFilter> &filters_out)
const {
465 std::vector<DBVal> entries;
470 filters_out.resize(entries.size());
471 auto filter_pos_it = filters_out.begin();
472 for (
const auto &entry : entries) {
484 std::vector<uint256> &hashes_out)
const
487 std::vector<DBVal> entries;
493 hashes_out.reserve(entries.size());
494 for (
const auto &entry : entries) {
495 hashes_out.push_back(entry.hash);
512 std::function<std::unique_ptr<interfaces::Chain>()> make_chain,
516 std::piecewise_construct, std::forward_as_tuple(filter_type),
517 std::forward_as_tuple(make_chain(), filter_type, n_cache_size, f_memory,
519 return result.second;
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.
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.
Non-refcounted RAII wrapper for FILE*.
Base class for indices of blockchain data.
const std::string & GetName() const LIFETIMEBOUND
Get the name of the index for display in logs.
Chainstate * m_chainstate
virtual bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip)
Rewind index to an earlier chain tip during a chain reorg.
Complete block filter struct as defined in BIP 157.
uint256 ComputeHeader(const uint256 &prev_header) const
Compute the filter header given the previous one.
BlockFilterType GetFilterType() const
const BlockHash & GetBlockHash() const
uint256 GetHash() const
Compute the filter hash.
const std::vector< uint8_t > & GetEncodedFilter() const
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
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
Undo information for a CBlock.
Batch of changes queued to be written to a CDBWrapper.
void Write(const K &key, const V &value)
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
std::string ToString() const
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
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)
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
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...
Implement std::hash so RCUPtr can be used as a key for maps or sets.
void Serialize(Stream &, V)=delete
uint8_t ser_readdata8(Stream &s)
void ser_writedata32be(Stream &s, uint32_t obj)
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
void Unserialize(Stream &, V)=delete
void ser_writedata8(Stream &s, uint8_t obj)
Lowest-level serialization and conversion.
size_t GetSerializeSize(const T &t, int nVersion=0)
uint32_t ser_readdata32be(Stream &s)
A BlockHash is a unqiue identifier for a block.