/tmp/bitcoin/src/index/txindex.cpp
Line | Count | Source |
1 | | // Copyright (c) 2017-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/txindex.h> |
6 | | |
7 | | #include <chain.h> |
8 | | #include <common/args.h> |
9 | | #include <crypto/siphash.h> |
10 | | #include <dbwrapper.h> |
11 | | #include <flatfile.h> |
12 | | #include <index/base.h> |
13 | | #include <index/disktxpos.h> |
14 | | #include <index/txindex_key.h> |
15 | | #include <interfaces/chain.h> |
16 | | #include <node/blockstorage.h> |
17 | | #include <primitives/block.h> |
18 | | #include <primitives/transaction.h> |
19 | | #include <random.h> |
20 | | #include <serialize.h> |
21 | | #include <streams.h> |
22 | | #include <sync.h> |
23 | | #include <tinyformat.h> |
24 | | #include <uint256.h> |
25 | | #include <util/fs.h> |
26 | | #include <util/log.h> |
27 | | #include <util/string.h> |
28 | | #include <validation.h> |
29 | | |
30 | | #include <algorithm> |
31 | | #include <array> |
32 | | #include <cassert> |
33 | | #include <cstdint> |
34 | | #include <cstdio> |
35 | | #include <exception> |
36 | | #include <functional> |
37 | | #include <memory> |
38 | | #include <optional> |
39 | | #include <stdexcept> |
40 | | #include <string> |
41 | | #include <utility> |
42 | | #include <vector> |
43 | | |
44 | | std::unique_ptr<TxIndex> g_txindex; |
45 | | |
46 | | namespace { |
47 | | SipHasher13UJ ReadOrCreateTxidHasher(CDBWrapper& db) |
48 | 48 | { |
49 | 48 | std::pair<uint64_t, uint64_t> salt; |
50 | 48 | if (!db.Read(txindex::DB_TXID_HASH_SALT, salt)) { |
51 | 24 | FastRandomContext rng{}; |
52 | 24 | salt = {rng.rand64(), rng.rand64()}; |
53 | 24 | db.Write(txindex::DB_TXID_HASH_SALT, salt, /*fSync=*/true); |
54 | 24 | } |
55 | 48 | return SipHasher13UJ{salt.first, salt.second}; |
56 | 48 | } |
57 | | } // namespace |
58 | | |
59 | | /** Access to the txindex database (indexes/txindex/) */ |
60 | | class TxIndex::DB : public BaseIndex::DB |
61 | | { |
62 | | public: |
63 | | explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false); |
64 | | |
65 | | /// Write a block of transaction positions to the DB. |
66 | | void WriteTxs(const interfaces::BlockInfo& block); |
67 | | |
68 | | /// Used to hash the txid to compute the prefix. |
69 | | const SipHasher13UJ m_hasher; |
70 | | |
71 | | /// Whether the database contains any legacy ('t' + txid) entries. |
72 | | const bool m_has_legacy; |
73 | | |
74 | | CBlockLocator ReadBestBlock() const override; |
75 | | void WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) override; |
76 | | |
77 | | private: |
78 | | DB(size_t n_cache_size, bool f_memory, bool f_wipe, bool has_legacy); |
79 | | }; |
80 | | |
81 | 96 | static fs::path TxIndexDBPath() { return gArgs.GetDataDirNet() / "indexes" / "txindex"; } |
82 | | |
83 | | TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) : |
84 | | // Bloom filters are built for every key but only consulted by point reads, |
85 | | // which iterators bypass: the per-tx hashed ('x') lookups seek with an |
86 | | // iterator, and the 's'/'h' point reads are at most one per block against a |
87 | | // tiny keyspace. Only the legacy entries' per-tx point lookups benefit, so |
88 | | // enable the filters only for databases still containing them. |
89 | 51 | DB(n_cache_size, f_memory, f_wipe, |
90 | 51 | /*has_legacy=*/!f_memory && !f_wipe && CDBWrapper::HasKeyStartingWith(TxIndexDBPath(), txindex::DB_TXINDEX)) |
91 | 51 | {} |
92 | | |
93 | | TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe, bool has_legacy) : |
94 | 48 | BaseIndex::DB(TxIndexDBPath(), n_cache_size, f_memory, f_wipe, /*f_obfuscate=*/false, /*f_bloom=*/has_legacy), |
95 | 48 | m_hasher{ReadOrCreateTxidHasher(*this)}, |
96 | 48 | m_has_legacy{has_legacy} |
97 | 48 | {} |
98 | | |
99 | | CBlockLocator TxIndex::DB::ReadBestBlock() const |
100 | 54 | { |
101 | 54 | CBlockLocator locator; |
102 | 54 | if (Read(txindex::DB_BEST_BLOCK_V2, locator)) { |
103 | 26 | return locator; |
104 | 26 | } |
105 | | // If we don't have a locator yet, start from the legacy best block. |
106 | 28 | return BaseIndex::DB::ReadBestBlock(); |
107 | 54 | } |
108 | | |
109 | | void TxIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) |
110 | 59 | { |
111 | 59 | batch.Write(txindex::DB_BEST_BLOCK_V2, locator); |
112 | 59 | } |
113 | | |
114 | | void TxIndex::DB::WriteTxs(const interfaces::BlockInfo& block) |
115 | 4.80k | { |
116 | | // A block may be submitted again after it was already indexed, e.g. when it |
117 | | // reconnects after a reorg or is re-processed after an unclean shutdown. It |
118 | | // keeps its original sequence number, so skip it to avoid duplicate entries. |
119 | 4.80k | if (Exists(txindex::BlockHashKey{block.hash})) return; |
120 | | |
121 | 4.30k | uint32_t block_seq{0}; |
122 | 4.30k | Read(txindex::DB_NEXT_BLOCK_SEQ, block_seq); |
123 | | |
124 | 4.30k | CDBBatch batch(*this); |
125 | 4.30k | batch.Write(txindex::BlockHashKey{block.hash}, block_seq); |
126 | 4.30k | batch.Write(txindex::BlockSeqKey{block_seq}, block.hash); |
127 | 4.30k | batch.Write(txindex::DB_NEXT_BLOCK_SEQ, block_seq + 1); |
128 | 4.30k | uint32_t tx_offset_in_block{txindex::BLOCK_HEADER_SIZE + GetSizeOfCompactSize(block.data->vtx.size())}; |
129 | 4.45k | for (const auto& tx : block.data->vtx) { |
130 | 4.45k | const txindex::DBKey key{txindex::CreateKeyPrefix(m_hasher, tx->GetHash()), |
131 | 4.45k | txindex::BlockTxPosition{block_seq, tx_offset_in_block}}; |
132 | 4.45k | batch.Write(key, txindex::EMPTY_VALUE); |
133 | 4.45k | tx_offset_in_block += tx->ComputeTotalSize(); |
134 | 4.45k | } |
135 | 4.30k | WriteBatch(batch); |
136 | 4.30k | } |
137 | | |
138 | | TxIndex::TxIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory, bool f_wipe) |
139 | 51 | : BaseIndex(std::move(chain), "txindex", "txidx"), m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe)) |
140 | 51 | { |
141 | 51 | if (m_db->m_has_legacy) { |
142 | 2 | LogInfo("txindex contains entries in the legacy format, which uses excessive disk space. " |
143 | 2 | "To reclaim disk space, stop the node, delete %s and restart to rebuild the index.", |
144 | 2 | fs::PathToString(TxIndexDBPath())); |
145 | 2 | } |
146 | 51 | } |
147 | | |
148 | 48 | TxIndex::~TxIndex() = default; |
149 | | |
150 | | bool TxIndex::CustomAppend(const interfaces::BlockInfo& block) |
151 | 4.82k | { |
152 | | // Exclude genesis block transaction because outputs are not spendable. |
153 | 4.82k | if (block.height == 0) return true; |
154 | | |
155 | 4.82k | assert(block.data); |
156 | 4.80k | m_db->WriteTxs(block); |
157 | 4.80k | return true; |
158 | 4.80k | } |
159 | | |
160 | 233 | BaseIndex::DB& TxIndex::GetDB() const { return *m_db; } |
161 | | |
162 | | template <typename... Args> |
163 | | [[noreturn]] static void WarnAndThrowErr(util::ConstevalFormatString<sizeof...(Args)> fmt, const Args&... args) |
164 | 4 | { |
165 | 4 | const std::string err{tfm::format(fmt, args...)}; |
166 | 4 | LogWarning("%s", err); |
167 | 4 | throw std::runtime_error{err}; |
168 | 4 | } Unexecuted instantiation: txindex.cpp:void WarnAndThrowErr<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, unsigned int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, unsigned int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, unsigned int const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) Unexecuted instantiation: txindex.cpp:void WarnAndThrowErr<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) txindex.cpp:void WarnAndThrowErr<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) Line | Count | Source | 164 | 4 | { | 165 | 4 | const std::string err{tfm::format(fmt, args...)}; | 166 | 4 | LogWarning("%s", err); | 167 | 4 | throw std::runtime_error{err}; | 168 | 4 | } |
Unexecuted instantiation: txindex.cpp:void WarnAndThrowErr<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, char const* const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) Unexecuted instantiation: txindex.cpp:void WarnAndThrowErr<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>>(util::ConstevalFormatString<sizeof...(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, char const*, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)>, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, char const* const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&) |
169 | | |
170 | | std::optional<TxIndexResult> TxIndex::FindTx(const Txid& tx_hash) const |
171 | 266 | { |
172 | 266 | struct Candidate { |
173 | 266 | FlatFilePos tx_position; |
174 | 266 | uint256 block_hash; |
175 | 266 | uint32_t block_seq; |
176 | | //! Whether this candidate's block is currently in the active chain. |
177 | | //! Active chain candidates are attempted first, so duplicate entries |
178 | | //! in both active and stale blocks will always return the active block hash. |
179 | 266 | bool in_active_chain; |
180 | 266 | }; |
181 | 266 | std::vector<Candidate> candidates; |
182 | 266 | { |
183 | 266 | std::unique_ptr<CDBIterator> it{m_db->NewIterator()}; |
184 | 266 | const txindex::TxHashKeyPrefix prefix{txindex::CreateKeyPrefix(m_db->m_hasher, tx_hash)}; |
185 | 266 | txindex::DBKey key{prefix, {}}; |
186 | 426 | for (it->Seek(key); it->Valid() && it->GetKey(key) && key.hash_prefix == prefix; it->Next()) { |
187 | 160 | uint256 candidate_block_hash; |
188 | 160 | if (!m_db->Read(txindex::BlockSeqKey{key.pos.block_seq}, candidate_block_hash)) { |
189 | | // Read may throw dbwrapper_error. |
190 | | // Read returns false for internal deserialize errors or a |
191 | | // missing key. A missing key can only happen after corruption. |
192 | 0 | WarnAndThrowErr("%s: Corrupt index: block sequence %u not found for txid %s", |
193 | 0 | GetName(), key.pos.block_seq, tx_hash.ToString()); |
194 | 0 | } |
195 | 160 | LOCK(cs_main); |
196 | 160 | const CBlockIndex* block_index{m_chainstate->m_blockman.LookupBlockIndex(candidate_block_hash)}; |
197 | | // Stale entries can remain after an unclean shutdown. Unknown blocks |
198 | | // cannot be in the active chain, so skip them. |
199 | 160 | if (!block_index) continue; |
200 | 160 | const bool in_active_chain{m_chainstate->m_chain.Contains(*block_index)}; |
201 | 160 | if (!(block_index->nStatus & BLOCK_HAVE_DATA)) { |
202 | | // A stale entry may also refer to a known block without data. |
203 | | // Skip it if it is not in the active chain. |
204 | 0 | if (!in_active_chain) continue; |
205 | 0 | WarnAndThrowErr("%s: Block data %s unexpectedly unavailable for txid %s. Caused by data corruption?", |
206 | 0 | GetName(), candidate_block_hash.ToString(), tx_hash.ToString()); |
207 | 0 | } |
208 | 160 | const FlatFilePos tx_position{block_index->nFile, block_index->nDataPos + key.pos.tx_offset_in_block}; |
209 | 160 | candidates.emplace_back(tx_position, candidate_block_hash, key.pos.block_seq, in_active_chain); |
210 | 160 | } |
211 | 266 | } |
212 | | |
213 | | // Prefer active-chain matches, then later-connected blocks. |
214 | 266 | std::ranges::sort(candidates, std::greater{}, [](const Candidate& c) { return std::pair{c.in_active_chain, c.block_seq}; }); |
215 | | |
216 | 266 | for (const auto& candidate : candidates) { |
217 | 158 | AutoFile file{m_chainstate->m_blockman.OpenBlockFile(candidate.tx_position, /*fReadOnly=*/true)}; |
218 | 158 | if (file.IsNull()) { |
219 | 4 | WarnAndThrowErr("%s: Failed to open block file for txid %s at %s in block %s", |
220 | 4 | GetName(), tx_hash.ToString(), candidate.tx_position.ToString(), candidate.block_hash.ToString()); |
221 | 4 | } |
222 | 158 | CTransactionRef tx; |
223 | 158 | try { |
224 | 158 | file >> TX_WITH_WITNESS(tx); |
225 | 158 | } catch (const std::exception& e) { |
226 | 0 | WarnAndThrowErr("%s: Deserialize or I/O error (%s). txid %s at %s in block %s", |
227 | 0 | GetName(), e.what(), tx_hash.ToString(), candidate.tx_position.ToString(), candidate.block_hash.ToString()); |
228 | 0 | } |
229 | 158 | if (tx->GetHash() == tx_hash) { |
230 | 153 | return TxIndexResult{candidate.block_hash, std::move(tx)}; |
231 | 153 | } |
232 | 154 | } |
233 | | // Fall back to legacy if no hashed entry matched. This makes misses pay an |
234 | | // extra lookup, but keeps existing full-txid entries readable after upgrade. |
235 | 109 | return m_db->m_has_legacy ? FindLegacyTx(tx_hash) : std::nullopt; |
236 | 266 | } |
237 | | |
238 | | std::optional<TxIndexResult> TxIndex::FindLegacyTx(const Txid& tx_hash) const |
239 | 3 | { |
240 | 3 | CDiskTxPos postx; |
241 | 3 | const auto read{m_db->TryRead(txindex::LegacyTxKey(tx_hash), postx)}; |
242 | 3 | if (!read) { |
243 | 0 | WarnAndThrowErr("%s: Failed to read legacy entry for txid %s: %s", |
244 | 0 | GetName(), tx_hash.ToString(), read.error().err_msg); |
245 | 0 | } |
246 | 3 | if (!read.value()) { |
247 | 0 | return std::nullopt; |
248 | 0 | } |
249 | | |
250 | 3 | AutoFile file{m_chainstate->m_blockman.OpenBlockFile(postx, /*fReadOnly=*/true)}; |
251 | 3 | if (file.IsNull()) { |
252 | 0 | WarnAndThrowErr("%s: Failed to open block file for txid %s at %s", |
253 | 0 | GetName(), tx_hash.ToString(), postx.ToString()); |
254 | 0 | } |
255 | 3 | CBlockHeader header; |
256 | 3 | CTransactionRef tx; |
257 | 3 | try { |
258 | 3 | file >> header; |
259 | 3 | file.seek(postx.nTxOffset, SEEK_CUR); |
260 | 3 | file >> TX_WITH_WITNESS(tx); |
261 | 3 | } catch (const std::exception& e) { |
262 | 0 | WarnAndThrowErr("%s: Deserialize or I/O error (%s). txid %s at %s", |
263 | 0 | GetName(), e.what(), tx_hash.ToString(), postx.ToString()); |
264 | 0 | } |
265 | 3 | if (tx->GetHash() != tx_hash) { |
266 | 0 | WarnAndThrowErr("%s: txid mismatch in legacy index. txid %s at %s", |
267 | 0 | GetName(), tx_hash.ToString(), postx.ToString()); |
268 | 0 | } |
269 | 3 | return TxIndexResult{header.GetHash(), std::move(tx)}; |
270 | 3 | } |