16 #include <validation.h> 60 explicit DBHeightKey(
int height_in) : height(height_in) {}
62 template<
typename Stream>
69 template<
typename Stream>
74 throw std::ios_base::failure(
"Invalid format for block filter index DB height key");
83 explicit DBHashKey(
const uint256& hash_in) : hash(hash_in) {}
89 throw std::ios_base::failure(
"Invalid format for block filter index DB hash key");
101 size_t n_cache_size,
bool f_memory,
bool f_wipe)
103 , m_filter_type(filter_type)
106 if (filter_name.empty())
throw std::invalid_argument(
"unknown filter_type");
111 m_db = std::make_unique<BaseIndex::DB>(path /
"db", n_cache_size, f_memory, f_wipe);
122 return error(
"%s: Cannot read current %s state; index may be corrupted",
140 return error(
"%s: Failed to open filter file %d", __func__, pos.
nFile);
143 return error(
"%s: Failed to commit filter file %d", __func__, pos.
nFile);
153 if (filein.IsNull()) {
159 std::vector<uint8_t> encoded_filter;
161 filein >> block_hash >> encoded_filter;
162 if (
Hash(encoded_filter) != hash)
return error(
"Checksum mismatch in filter decode.");
165 catch (
const std::exception& e) {
166 return error(
"%s: Failed to deserialize block filter from disk: %s", __func__, e.what());
183 if (last_file.IsNull()) {
184 LogPrintf(
"%s: Failed to open filter file %d\n", __func__, pos.
nFile);
188 LogPrintf(
"%s: Failed to truncate filter file %d\n", __func__, pos.
nFile);
192 LogPrintf(
"%s: Failed to commit filter file %d\n", __func__, pos.
nFile);
204 LogPrintf(
"%s: out of disk space\n", __func__);
209 if (fileout.IsNull()) {
210 LogPrintf(
"%s: Failed to open filter file %d\n", __func__, pos.
nFile);
231 std::pair<uint256, DBVal> read_out;
232 if (!
m_db->Read(DBHeightKey(block.
height - 1), read_out)) {
237 if (read_out.first != expected_block_hash) {
238 return error(
"%s: previous block header belongs to unexpected block %s; expected %s",
239 __func__, read_out.first.ToString(), expected_block_hash.
ToString());
242 prev_header = read_out.second.header;
248 if (bytes_written == 0)
return false;
250 std::pair<uint256, DBVal> value;
251 value.first = block.
hash;
252 value.second.hash = filter.
GetHash();
256 if (!
m_db->Write(DBHeightKey(block.
height), value)) {
265 const std::string& index_name,
266 int start_height,
int stop_height)
268 DBHeightKey key(start_height);
271 for (
int height = start_height; height <= stop_height; ++height) {
272 if (!db_it.
GetKey(key) || key.height != height) {
273 return error(
"%s: unexpected key in %s: expected (%c, %d)",
277 std::pair<uint256, DBVal> value;
279 return error(
"%s: unable to read value in %s at key (%c, %d)",
283 batch.
Write(DBHashKey(value.first), std::move(value.second));
293 std::unique_ptr<CDBIterator> db_it(
m_db->NewIterator());
306 if (!
m_db->WriteBatch(batch))
return false;
315 std::pair<uint256, DBVal> read_out;
316 if (!db.
Read(DBHeightKey(block_index->
nHeight), read_out)) {
320 result = std::move(read_out.second);
330 const CBlockIndex* stop_index, std::vector<DBVal>& results)
332 if (start_height < 0) {
333 return error(
"%s: start height (%d) is negative", __func__, start_height);
335 if (start_height > stop_index->
nHeight) {
336 return error(
"%s: start height (%d) is greater than stop height (%d)",
337 __func__, start_height, stop_index->
nHeight);
340 size_t results_size =
static_cast<size_t>(stop_index->
nHeight - start_height + 1);
341 std::vector<std::pair<uint256, DBVal>>
values(results_size);
343 DBHeightKey key(start_height);
344 std::unique_ptr<CDBIterator> db_it(db.
NewIterator());
345 db_it->Seek(DBHeightKey(start_height));
346 for (
int height = start_height; height <= stop_index->
nHeight; ++height) {
347 if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
351 size_t i =
static_cast<size_t>(height - start_height);
352 if (!db_it->GetValue(
values[i])) {
353 return error(
"%s: unable to read value in %s at key (%c, %d)",
360 results.resize(results_size);
365 block_index && block_index->
nHeight >= start_height;
366 block_index = block_index->pprev) {
367 uint256 block_hash = block_index->GetBlockHash();
369 size_t i =
static_cast<size_t>(block_index->nHeight - start_height);
370 if (block_hash ==
values[i].first) {
371 results[i] = std::move(
values[i].second);
375 if (!db.
Read(DBHashKey(block_hash), results[i])) {
376 return error(
"%s: unable to read value in %s at key (%c, %s)",
402 auto header = m_headers_cache.find(block_index->
GetBlockHash());
403 if (header != m_headers_cache.end()) {
404 header_out = header->second;
417 m_headers_cache.emplace(block_index->
GetBlockHash(), entry.header);
420 header_out = entry.header;
425 std::vector<BlockFilter>& filters_out)
const 427 std::vector<DBVal> entries;
432 filters_out.resize(entries.size());
433 auto filter_pos_it = filters_out.begin();
434 for (
const auto& entry : entries) {
445 std::vector<uint256>& hashes_out)
const 448 std::vector<DBVal> entries;
454 hashes_out.reserve(entries.size());
455 for (
const auto& entry : entries) {
456 hashes_out.push_back(entry.hash);
473 size_t n_cache_size,
bool f_memory,
bool f_wipe)
476 std::forward_as_tuple(filter_type),
477 std::forward_as_tuple(make_chain(), filter_type,
478 n_cache_size, f_memory, f_wipe));
479 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...
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. ...
uint8_t ser_readdata8(Stream &s)
Batch of changes queued to be written to a CDBWrapper.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances...
static bool LookupRange(CDBWrapper &db, const std::string &index_name, int start_height, const CBlockIndex *stop_index, std::vector< DBVal > &results)
void Unserialize(Stream &, char)=delete
BlockFilterIndex * GetBlockFilterIndex(BlockFilterType filter_type)
Get a block filter index by type.
constexpr uint8_t DB_BLOCK_HEIGHT
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 We have a limit to prevent a bug in filling this cache potentiall...
constexpr unsigned int MAX_FLTR_FILE_SIZE
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
std::unique_ptr< BaseIndex::DB > m_db
Non-refcounted RAII wrapper for FILE*.
uint256 GetHash() const
Compute the filter hash.
size_t GetSerializeSize(const T &t, int nVersion=0)
const uint256 & GetBlockHash() const LIFETIMEBOUND
uint256 GetBlockHash() const
Block data sent with blockConnected, blockDisconnected notifications.
static bool CopyHeightIndexToHashIndex(CDBIterator &db_it, CDBBatch &batch, const std::string &index_name, int start_height, int stop_height)
Base class for indices of blockchain data.
constexpr uint8_t DB_FILTER_POS
size_t WriteFilterToDisk(FlatFilePos &pos, const BlockFilter &filter)
const uint256 * prev_hash
const std::string & GetName() const LIFETIMEBOUND
Get the name of the index for display in logs.
bool CustomInit(const std::optional< interfaces::BlockKey > &block) override
Initialize internal state from the database and block index.
bool LookupFilterHeader(const CBlockIndex *block_index, uint256 &header_out) EXCLUSIVE_LOCKS_REQUIRED(!m_cs_headers_cache)
Get a single filter header by block.
Complete block filter struct as defined in BIP 157.
void DestroyAllBlockFilterIndexes()
Destroy all open block filter indexes.
CDBIterator * NewIterator()
void Serialize(Stream &, char)=delete
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
constexpr unsigned int FLTR_FILE_CHUNK_SIZE
The pre-allocation chunk size for fltr?????.dat files.
void Write(const K &key, const V &value)
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 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.
std::string ToString() const
void ser_writedata32be(Stream &s, uint32_t obj)
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...
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool Read(const K &key, V &value) const
bool CustomRewind(const interfaces::BlockKey ¤t_tip, const interfaces::BlockKey &new_tip) override
Rewind index to an earlier chain tip during a chain reorg.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
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.
bool TruncateFile(FILE *file, unsigned int length)
bool error(const char *fmt, const Args &... args)
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
Hash/height pair to help track and identify blocks.
Chainstate * m_chainstate
static std::map< BlockFilterType, BlockFilterIndex > g_filter_indexes
uint32_t ser_readdata32be(Stream &s)
constexpr uint8_t DB_BLOCK_HASH
bool CustomCommit(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
bool CustomAppend(const interfaces::BlockInfo &block) override
Write update index entries for a newly connected block.
int nHeight
height of the entry in the chain. The genesis block has height 0
uint256 Hash(const T &in1)
Compute the 256-bit hash of an object.
const std::vector< unsigned char > & GetEncodedFilter() const LIFETIMEBOUND
bool ReadFilterFromDisk(const FlatFilePos &pos, const uint256 &hash, BlockFilter &filter) const
static path u8path(const std::string &utf8_str)
BlockFilterType GetFilterType() const
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
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.
static bool LookupOne(const CDBWrapper &db, const CBlockIndex *block_index, DBVal &result)
void ser_writedata8(Stream &s, uint8_t obj)
#define Assert(val)
Identity function.
const fs::path & GetDataDirNet() const
Get data directory path with appended network identifier.
const std::string & BlockFilterTypeName(BlockFilterType filter_type)
Get the human-readable name for a filter type.