Branch data Line data Source code
1 : : // Copyright (c) 2018-present 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 <index/blockfilterindex.h>
6 : :
7 : : #include <blockfilter.h>
8 : : #include <chain.h>
9 : : #include <common/args.h>
10 : : #include <dbwrapper.h>
11 : : #include <flatfile.h>
12 : : #include <hash.h>
13 : : #include <index/base.h>
14 : : #include <index/db_key.h>
15 : : #include <interfaces/chain.h>
16 : : #include <interfaces/types.h>
17 : : #include <serialize.h>
18 : : #include <streams.h>
19 : : #include <sync.h>
20 : : #include <uint256.h>
21 : : #include <util/check.h>
22 : : #include <util/byte_units.h>
23 : : #include <util/fs.h>
24 : : #include <util/hasher.h>
25 : : #include <util/log.h>
26 : : #include <util/syserror.h>
27 : :
28 : : #include <cerrno>
29 : : #include <exception>
30 : : #include <optional>
31 : : #include <stdexcept>
32 : : #include <string>
33 : : #include <utility>
34 : : #include <vector>
35 : :
36 : : /* The index database stores three items for each block: the disk location of the encoded filter,
37 : : * its dSHA256 hash, and the header. Those belonging to blocks on the active chain are indexed by
38 : : * height, and those belonging to blocks that have been reorganized out of the active chain are
39 : : * indexed by block hash. This ensures that filter data for any block that becomes part of the
40 : : * active chain can always be retrieved, alleviating timing concerns.
41 : : *
42 : : * The filters themselves are stored in flat files and referenced by the LevelDB entries. This
43 : : * minimizes the amount of data written to LevelDB and keeps the database values constant size. The
44 : : * disk location of the next block filter to be written (represented as a FlatFilePos) is stored
45 : : * under the DB_FILTER_POS key.
46 : : *
47 : : * The logic for keys is shared with other indexes, see index/db_key.h.
48 : : */
49 : : constexpr uint8_t DB_FILTER_POS{'P'};
50 : :
51 : : constexpr uint64_t MAX_FLTR_FILE_SIZE{16_MiB};
52 : : /** The pre-allocation chunk size for fltr?????.dat files */
53 : : constexpr uint64_t FLTR_FILE_CHUNK_SIZE{1_MiB};
54 : : /** Maximum size of the cfheaders cache
55 : : * We have a limit to prevent a bug in filling this cache
56 : : * potentially turning into an OOM. At 2000 entries, this cache
57 : : * is big enough for a 2,000,000 length block chain, which
58 : : * we should be enough until ~2047. */
59 : : constexpr size_t CF_HEADERS_CACHE_MAX_SZ{2000};
60 : :
61 : : namespace {
62 : :
63 : 61 : std::string BlockFilterThreadName(BlockFilterType filter_type)
64 : : {
65 [ + - - ]: 61 : switch (filter_type) {
66 : 61 : case BlockFilterType::BASIC: return "blkfltbscidx";
67 : 0 : case BlockFilterType::INVALID: return "";
68 : : } // no default case, so the compiler can warn about missing cases
69 : 0 : AssertUnreachable();
70 : : }
71 : :
72 : 5938 : struct DBVal {
73 : : uint256 hash;
74 : : uint256 header;
75 : : FlatFilePos pos;
76 : :
77 : 23475 : SERIALIZE_METHODS(DBVal, obj) { READWRITE(obj.hash, obj.header, obj.pos); }
78 : : };
79 : :
80 : : }; // namespace
81 : :
82 : 61 : BlockFilterIndex::BlockFilterIndex(std::unique_ptr<interfaces::Chain> chain, BlockFilterType filter_type,
83 : 61 : size_t n_cache_size, bool f_memory, bool f_wipe)
84 [ + - + - ]: 122 : : BaseIndex(std::move(chain), BlockFilterTypeName(filter_type) + " block filter index", BlockFilterThreadName(filter_type))
85 [ + - + - ]: 183 : , m_filter_type(filter_type)
86 : : {
87 [ + - ]: 61 : const std::string& filter_name = BlockFilterTypeName(filter_type);
88 [ - + - - ]: 61 : if (filter_name.empty()) throw std::invalid_argument("unknown filter_type");
89 : :
90 [ - + + - : 427 : fs::path path = gArgs.GetDataDirNet() / "indexes" / "blockfilter" / fs::u8path(filter_name);
+ - + - +
- ]
91 [ + - ]: 61 : fs::create_directories(path);
92 : :
93 [ + - + - : 184 : m_db = std::make_unique<BaseIndex::DB>(path / "db", n_cache_size, f_memory, f_wipe);
+ + ]
94 [ + - ]: 60 : m_filter_fileseq = std::make_unique<FlatFileSeq>(std::move(path), "fltr", FLTR_FILE_CHUNK_SIZE);
95 : 63 : }
96 : :
97 : 19510 : interfaces::Chain::NotifyOptions BlockFilterIndex::CustomOptions()
98 : : {
99 : 19510 : interfaces::Chain::NotifyOptions options;
100 : 19510 : options.connect_undo_data = true;
101 : 19510 : return options;
102 : : }
103 : :
104 : 65 : bool BlockFilterIndex::CustomInit(const std::optional<interfaces::BlockRef>& block)
105 : : {
106 [ + + ]: 65 : if (!m_db->Read(DB_FILTER_POS, m_next_filter_pos)) {
107 : : // Check that the cause of the read failure is that the key does not exist. Any other errors
108 : : // indicate database corruption or a disk failure, and starting the index would cause
109 : : // further corruption.
110 [ - + ]: 30 : if (m_db->Exists(DB_FILTER_POS)) {
111 : 0 : LogError("Cannot read current %s state; index may be corrupted",
112 : : GetName());
113 : 0 : return false;
114 : : }
115 : :
116 : : // If the DB_FILTER_POS is not set, then initialize to the first location.
117 : 30 : m_next_filter_pos.nFile = 0;
118 : 30 : m_next_filter_pos.nPos = 0;
119 : : }
120 : :
121 [ + + ]: 65 : if (block) {
122 : 35 : auto op_last_header = ReadFilterHeader(block->height, block->hash);
123 [ - + ]: 35 : if (!op_last_header) {
124 : 0 : LogError("Cannot read last block filter header; index may be corrupted");
125 : 0 : return false;
126 : : }
127 : 35 : m_last_header = *op_last_header;
128 : : }
129 : :
130 : : return true;
131 : : }
132 : :
133 : 91 : bool BlockFilterIndex::CustomCommit(CDBBatch& batch)
134 : : {
135 : 91 : const FlatFilePos& pos = m_next_filter_pos;
136 : :
137 : : // Flush current filter file to disk.
138 : 182 : AutoFile file{m_filter_fileseq->Open(pos)};
139 [ - + ]: 91 : if (file.IsNull()) {
140 [ # # ]: 0 : LogError("Failed to open filter file %d", pos.nFile);
141 : : return false;
142 : : }
143 [ + - - + ]: 91 : if (!file.Commit()) {
144 [ # # ]: 0 : LogError("Failed to commit filter file %d", pos.nFile);
145 [ # # ]: 0 : (void)file.fclose();
146 : : return false;
147 : : }
148 [ + - - + ]: 182 : if (file.fclose() != 0) {
149 [ # # # # ]: 0 : LogError("Failed to close filter file %d after commit: %s", pos.nFile, SysErrorString(errno));
150 : 0 : return false;
151 : : }
152 : :
153 [ + - ]: 91 : batch.Write(DB_FILTER_POS, pos);
154 : : return true;
155 : 91 : }
156 : :
157 : 1408 : bool BlockFilterIndex::ReadFilterFromDisk(const FlatFilePos& pos, const uint256& hash, BlockFilter& filter) const
158 : : {
159 : 2816 : AutoFile filein{m_filter_fileseq->Open(pos, true)};
160 [ + - ]: 1408 : if (filein.IsNull()) {
161 : : return false;
162 : : }
163 : :
164 : : // Check that the hash of the encoded_filter matches the one stored in the db.
165 : 1408 : uint256 block_hash;
166 : 1408 : std::vector<uint8_t> encoded_filter;
167 : 1408 : try {
168 [ + - + - ]: 1408 : filein >> block_hash >> encoded_filter;
169 [ + - ]: 1408 : if (Hash(encoded_filter) != hash) {
170 [ - - ]: 1408 : LogError("Checksum mismatch in filter decode.");
171 : : return false;
172 : : }
173 [ + - ]: 2816 : filter = BlockFilter(GetFilterType(), block_hash, std::move(encoded_filter), /*skip_decode_check=*/true);
174 : : }
175 [ - - ]: 0 : catch (const std::exception& e) {
176 [ - - ]: 0 : LogError("Failed to deserialize block filter from disk: %s", e.what());
177 : 0 : return false;
178 : 0 : }
179 : :
180 : 1408 : return true;
181 : 1408 : }
182 : :
183 : 19173 : uint64_t BlockFilterIndex::WriteFilterToDisk(FlatFilePos& pos, const BlockFilter& filter)
184 : : {
185 [ - + ]: 19173 : assert(filter.GetFilterType() == GetFilterType());
186 : :
187 : 19173 : uint64_t data_size{
188 : 19173 : GetSerializeSize(filter.GetBlockHash()) +
189 : 19173 : GetSerializeSize(filter.GetEncodedFilter())};
190 : :
191 : : // If writing the filter would overflow the file, flush and move to the next one.
192 [ - + ]: 19173 : if (pos.nPos + data_size > MAX_FLTR_FILE_SIZE) {
193 : 0 : AutoFile last_file{m_filter_fileseq->Open(pos)};
194 [ # # ]: 0 : if (last_file.IsNull()) {
195 [ # # ]: 0 : LogError("Failed to open filter file %d", pos.nFile);
196 : : return 0;
197 : : }
198 [ # # # # ]: 0 : if (!last_file.Truncate(pos.nPos)) {
199 [ # # ]: 0 : LogError("Failed to truncate filter file %d", pos.nFile);
200 : : return 0;
201 : : }
202 [ # # # # ]: 0 : if (!last_file.Commit()) {
203 [ # # ]: 0 : LogError("Failed to commit filter file %d", pos.nFile);
204 [ # # ]: 0 : (void)last_file.fclose();
205 : : return 0;
206 : : }
207 [ # # # # ]: 0 : if (last_file.fclose() != 0) {
208 [ # # # # ]: 0 : LogError("Failed to close filter file %d after commit: %s", pos.nFile, SysErrorString(errno));
209 : 0 : return 0;
210 : : }
211 : :
212 : 0 : pos.nFile++;
213 : 0 : pos.nPos = 0;
214 : 0 : }
215 : :
216 : : // Pre-allocate sufficient space for filter data.
217 : 19173 : bool out_of_space;
218 : 19173 : m_filter_fileseq->Allocate(pos, data_size, out_of_space);
219 [ - + ]: 19173 : if (out_of_space) {
220 : 0 : LogError("out of disk space");
221 : 0 : return 0;
222 : : }
223 : :
224 : 38346 : AutoFile fileout{m_filter_fileseq->Open(pos)};
225 [ - + ]: 19173 : if (fileout.IsNull()) {
226 [ # # ]: 0 : LogError("Failed to open filter file %d", pos.nFile);
227 : : return 0;
228 : : }
229 : :
230 [ + - + - ]: 19173 : fileout << filter.GetBlockHash() << filter.GetEncodedFilter();
231 : :
232 [ + - - + ]: 38346 : if (fileout.fclose() != 0) {
233 [ # # # # ]: 0 : LogError("Failed to close filter file %d: %s", pos.nFile, SysErrorString(errno));
234 : 0 : return 0;
235 : : }
236 : :
237 : : return data_size;
238 : 19173 : }
239 : :
240 : 190 : std::optional<uint256> BlockFilterIndex::ReadFilterHeader(int height, const uint256& expected_block_hash)
241 : : {
242 : 190 : std::pair<uint256, DBVal> read_out;
243 [ - + ]: 190 : if (!m_db->Read(index_util::DBHeightKey(height), read_out)) {
244 : 0 : return std::nullopt;
245 : : }
246 : :
247 [ + - ]: 190 : if (read_out.first != expected_block_hash) {
248 [ # # # # ]: 0 : LogError("previous block header belongs to unexpected block %s; expected %s",
249 : : read_out.first.ToString(), expected_block_hash.ToString());
250 : 0 : return std::nullopt;
251 : : }
252 : :
253 : 190 : return read_out.second.header;
254 : : }
255 : :
256 : 19173 : bool BlockFilterIndex::CustomAppend(const interfaces::BlockInfo& block)
257 : : {
258 : 19173 : BlockFilter filter(m_filter_type, *Assert(block.data), *Assert(block.undo_data));
259 [ + - ]: 19173 : const uint256& header = filter.ComputeHeader(m_last_header);
260 [ + - ]: 19173 : bool res = Write(filter, block.height, header);
261 [ + - ]: 19173 : if (res) m_last_header = header; // update last header
262 : 19173 : return res;
263 : 19173 : }
264 : :
265 : 19173 : bool BlockFilterIndex::Write(const BlockFilter& filter, uint32_t block_height, const uint256& filter_header)
266 : : {
267 : 19173 : uint64_t bytes_written{WriteFilterToDisk(m_next_filter_pos, filter)};
268 [ + - ]: 19173 : if (bytes_written == 0) return false;
269 : :
270 : 19173 : std::pair<uint256, DBVal> value;
271 : 19173 : value.first = filter.GetBlockHash();
272 : 19173 : value.second.hash = filter.GetHash();
273 : 19173 : value.second.header = filter_header;
274 : 19173 : value.second.pos = m_next_filter_pos;
275 : :
276 : 19173 : m_db->Write(index_util::DBHeightKey(block_height), value);
277 : :
278 : 19173 : m_next_filter_pos.nPos += bytes_written;
279 : 19173 : return true;
280 : : }
281 : :
282 : 155 : bool BlockFilterIndex::CustomRemove(const interfaces::BlockInfo& block)
283 : : {
284 : 155 : CDBBatch batch(*m_db);
285 [ + - + - ]: 155 : std::unique_ptr<CDBIterator> db_it(m_db->NewIterator());
286 : :
287 : : // During a reorg, we need to copy block filter that is getting disconnected from the
288 : : // height index to the hash index so we can still find it when the height index entry
289 : : // is overwritten.
290 [ + - + - ]: 155 : if (!index_util::CopyHeightIndexToHashIndex<DBVal>(*db_it, batch, m_name, block.height)) {
291 : : return false;
292 : : }
293 : :
294 : : // The latest filter position gets written in Commit by the call to the BaseIndex::Rewind.
295 : : // But since this creates new references to the filter, the position should get updated here
296 : : // atomically as well in case Commit fails.
297 [ + - ]: 155 : batch.Write(DB_FILTER_POS, m_next_filter_pos);
298 [ + - ]: 155 : m_db->WriteBatch(batch);
299 : :
300 : : // Update cached header to the previous block hash
301 [ + - + - : 155 : m_last_header = *Assert(ReadFilterHeader(block.height - 1, *Assert(block.prev_hash)));
+ - ]
302 : 155 : return true;
303 : 155 : }
304 : :
305 : 450 : static bool LookupRange(CDBWrapper& db, const std::string& index_name, int start_height,
306 : : const CBlockIndex* stop_index, std::vector<DBVal>& results)
307 : : {
308 [ - + ]: 450 : if (start_height < 0) {
309 : 0 : LogError("start height (%d) is negative", start_height);
310 : 0 : return false;
311 : : }
312 [ - + ]: 450 : if (start_height > stop_index->nHeight) {
313 : 0 : LogError("start height (%d) is greater than stop height (%d)",
314 : : start_height, stop_index->nHeight);
315 : 0 : return false;
316 : : }
317 : :
318 : 450 : size_t results_size = static_cast<size_t>(stop_index->nHeight - start_height + 1);
319 : 450 : std::vector<std::pair<uint256, DBVal>> values(results_size);
320 : :
321 [ + - ]: 450 : index_util::DBHeightKey key(start_height);
322 [ + - + - ]: 450 : std::unique_ptr<CDBIterator> db_it(db.NewIterator());
323 [ + - ]: 450 : db_it->Seek(index_util::DBHeightKey(start_height));
324 [ + + ]: 3318 : for (int height = start_height; height <= stop_index->nHeight; ++height) {
325 [ + - + + : 3070 : if (!db_it->Valid() || !db_it->GetKey(key) || key.height != height) {
+ - + - -
+ ]
326 : 202 : return false;
327 : : }
328 : :
329 : 2868 : size_t i = static_cast<size_t>(height - start_height);
330 [ + - - + ]: 2868 : if (!db_it->GetValue(values[i])) {
331 [ # # ]: 0 : LogError("unable to read value in %s at key (%c, %d)",
332 : : index_name, index_util::DB_BLOCK_HEIGHT, height);
333 : : return false;
334 : : }
335 : :
336 [ + - ]: 2868 : db_it->Next();
337 : : }
338 : :
339 [ + - ]: 248 : results.resize(results_size);
340 : :
341 : : // Iterate backwards through block indexes collecting results in order to access the block hash
342 : : // of each entry in case we need to look it up in the hash index.
343 : 2868 : for (const CBlockIndex* block_index = stop_index;
344 [ + + + + ]: 3116 : block_index && block_index->nHeight >= start_height;
345 : 2868 : block_index = block_index->pprev) {
346 : 2868 : uint256 block_hash = block_index->GetBlockHash();
347 : :
348 : 2868 : size_t i = static_cast<size_t>(block_index->nHeight - start_height);
349 [ + + ]: 2868 : if (block_hash == values[i].first) {
350 : 2856 : results[i] = std::move(values[i].second);
351 : 2856 : continue;
352 : : }
353 : :
354 [ + - - + ]: 12 : if (!db.Read(index_util::DBHashKey(block_hash), results[i])) {
355 [ # # # # ]: 0 : LogError("unable to read value in %s at key (%c, %s)",
356 : : index_name, index_util::DB_BLOCK_HASH, block_hash.ToString());
357 : 0 : return false;
358 : : }
359 : : }
360 : :
361 : : return true;
362 : 450 : }
363 : :
364 : 963 : bool BlockFilterIndex::LookupFilter(const CBlockIndex* block_index, BlockFilter& filter_out) const
365 : : {
366 : 963 : DBVal entry;
367 [ + + ]: 963 : if (!index_util::LookUpOne(*m_db, {block_index->GetBlockHash(), block_index->nHeight}, entry)) {
368 : : return false;
369 : : }
370 : :
371 : 759 : return ReadFilterFromDisk(entry.pos, entry.hash, filter_out);
372 : : }
373 : :
374 : 249 : bool BlockFilterIndex::LookupFilterHeader(const CBlockIndex* block_index, uint256& header_out)
375 : : {
376 : 249 : LOCK(m_cs_headers_cache);
377 : :
378 : 249 : bool is_checkpoint{block_index->nHeight % CFCHECKPT_INTERVAL == 0};
379 : :
380 [ + + ]: 249 : if (is_checkpoint) {
381 : : // Try to find the block in the headers cache if this is a checkpoint height.
382 : 13 : auto header = m_headers_cache.find(block_index->GetBlockHash());
383 [ + + ]: 13 : if (header != m_headers_cache.end()) {
384 : 6 : header_out = header->second;
385 : 6 : return true;
386 : : }
387 : : }
388 : :
389 : 243 : DBVal entry;
390 [ + - + + ]: 243 : if (!index_util::LookUpOne(*m_db, {block_index->GetBlockHash(), block_index->nHeight}, entry)) {
391 : : return false;
392 : : }
393 : :
394 [ + + + - ]: 142 : if (is_checkpoint &&
395 [ + - ]: 6 : m_headers_cache.size() < CF_HEADERS_CACHE_MAX_SZ) {
396 : : // Add to the headers cache if this is a checkpoint height.
397 [ + - ]: 6 : m_headers_cache.emplace(block_index->GetBlockHash(), entry.header);
398 : : }
399 : :
400 : 142 : header_out = entry.header;
401 : 142 : return true;
402 : 249 : }
403 : :
404 : 232 : bool BlockFilterIndex::LookupFilterRange(int start_height, const CBlockIndex* stop_index,
405 : : std::vector<BlockFilter>& filters_out) const
406 : : {
407 : 232 : std::vector<DBVal> entries;
408 [ + - + + ]: 232 : if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
409 : : return false;
410 : : }
411 : :
412 [ - + + - ]: 131 : filters_out.resize(entries.size());
413 : 131 : auto filter_pos_it = filters_out.begin();
414 [ + + ]: 780 : for (const auto& entry : entries) {
415 [ + - + - ]: 649 : if (!ReadFilterFromDisk(entry.pos, entry.hash, *filter_pos_it)) {
416 : : return false;
417 : : }
418 : 649 : ++filter_pos_it;
419 : : }
420 : :
421 : : return true;
422 : 232 : }
423 : :
424 : 218 : bool BlockFilterIndex::LookupFilterHashRange(int start_height, const CBlockIndex* stop_index,
425 : : std::vector<uint256>& hashes_out) const
426 : :
427 : : {
428 : 218 : std::vector<DBVal> entries;
429 [ + - + + ]: 218 : if (!LookupRange(*m_db, m_name, start_height, stop_index, entries)) {
430 : : return false;
431 : : }
432 : :
433 [ - + ]: 117 : hashes_out.clear();
434 [ - + + - ]: 117 : hashes_out.reserve(entries.size());
435 [ + + ]: 2336 : for (const auto& entry : entries) {
436 [ + - ]: 2219 : hashes_out.push_back(entry.hash);
437 : : }
438 : : return true;
439 : 218 : }
|