Bitcoin Core  24.99.0
P2P Digital Currency
txindex.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2022 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 <index/disktxpos.h>
8 #include <node/blockstorage.h>
9 #include <util/system.h>
10 #include <validation.h>
11 
13 
14 constexpr uint8_t DB_TXINDEX{'t'};
15 
16 std::unique_ptr<TxIndex> g_txindex;
17 
18 
20 class TxIndex::DB : public BaseIndex::DB
21 {
22 public:
23  explicit DB(size_t n_cache_size, bool f_memory = false, bool f_wipe = false);
24 
27  bool ReadTxPos(const uint256& txid, CDiskTxPos& pos) const;
28 
30  bool WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos);
31 };
32 
33 TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe) :
34  BaseIndex::DB(gArgs.GetDataDirNet() / "indexes" / "txindex", n_cache_size, f_memory, f_wipe)
35 {}
36 
37 bool TxIndex::DB::ReadTxPos(const uint256 &txid, CDiskTxPos& pos) const
38 {
39  return Read(std::make_pair(DB_TXINDEX, txid), pos);
40 }
41 
42 bool TxIndex::DB::WriteTxs(const std::vector<std::pair<uint256, CDiskTxPos>>& v_pos)
43 {
44  CDBBatch batch(*this);
45  for (const auto& tuple : v_pos) {
46  batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second);
47  }
48  return WriteBatch(batch);
49 }
50 
51 TxIndex::TxIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory, bool f_wipe)
52  : BaseIndex(std::move(chain), "txindex"), m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe))
53 {}
54 
55 TxIndex::~TxIndex() = default;
56 
58 {
59  // Exclude genesis block transaction because outputs are not spendable.
60  if (block.height == 0) return true;
61 
62  assert(block.data);
63  CDiskTxPos pos({block.file_number, block.data_pos}, GetSizeOfCompactSize(block.data->vtx.size()));
64  std::vector<std::pair<uint256, CDiskTxPos>> vPos;
65  vPos.reserve(block.data->vtx.size());
66  for (const auto& tx : block.data->vtx) {
67  vPos.emplace_back(tx->GetHash(), pos);
69  }
70  return m_db->WriteTxs(vPos);
71 }
72 
73 BaseIndex::DB& TxIndex::GetDB() const { return *m_db; }
74 
75 bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const
76 {
77  CDiskTxPos postx;
78  if (!m_db->ReadTxPos(tx_hash, postx)) {
79  return false;
80  }
81 
82  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
83  if (file.IsNull()) {
84  return error("%s: OpenBlockFile failed", __func__);
85  }
86  CBlockHeader header;
87  try {
88  file >> header;
89  if (fseek(file.Get(), postx.nTxOffset, SEEK_CUR)) {
90  return error("%s: fseek(...) failed", __func__);
91  }
92  file >> tx;
93  } catch (const std::exception& e) {
94  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
95  }
96  if (tx->GetHash() != tx_hash) {
97  return error("%s: txid mismatch", __func__);
98  }
99  block_hash = header.GetHash();
100  return true;
101 }
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:536
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:532
The database stores a block locator of the chain the database is synced to so that the index can effi...
Definition: base.h:44
Base class for indices of blockchain data.
Definition: base.h:34
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:22
uint256 GetHash() const
Definition: block.cpp:11
std::vector< CTransactionRef > vtx
Definition: block.h:72
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:64
void Write(const K &key, const V &value)
Definition: dbwrapper.h:89
Access to the txindex database (indexes/txindex/)
Definition: txindex.cpp:21
bool WriteTxs(const std::vector< std::pair< uint256, CDiskTxPos >> &v_pos)
Write a batch of transaction positions to the DB.
Definition: txindex.cpp:42
DB(size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
Definition: txindex.cpp:33
bool ReadTxPos(const uint256 &txid, CDiskTxPos &pos) const
Read the disk location of the transaction data with the given hash.
Definition: txindex.cpp:37
TxIndex is used to look up transactions included in the blockchain by hash.
Definition: txindex.h:18
bool FindTx(const uint256 &tx_hash, uint256 &block_hash, CTransactionRef &tx) const
Look up a transaction by hash.
Definition: txindex.cpp:75
BaseIndex::DB & GetDB() const override
Definition: txindex.cpp:73
bool CustomAppend(const interfaces::BlockInfo &block) override
Write update index entries for a newly connected block.
Definition: txindex.cpp:57
TxIndex(std::unique_ptr< interfaces::Chain > chain, size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
Constructs the index, which becomes available to be queried.
Definition: txindex.cpp:51
virtual ~TxIndex() override
const std::unique_ptr< DB > m_db
Definition: txindex.h:20
256-bit opaque blob.
Definition: uint256.h:119
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
@ SER_DISK
Definition: serialize.h:132
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:233
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1109
unsigned int nTxOffset
Definition: disktxpos.h:13
Block data sent with blockConnected, blockDisconnected notifications.
Definition: chain.h:82
unsigned data_pos
Definition: chain.h:87
const CBlock * data
Definition: chain.h:88
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:16
constexpr uint8_t DB_TXINDEX
Definition: txindex.cpp:14
ArgsManager gArgs
Definition: system.cpp:73
assert(!tx.IsCoinBase())