Bitcoin Core  22.99.0
P2P Digital Currency
txindex.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2021 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(size_t n_cache_size, bool f_memory, bool f_wipe)
52  : m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe))
53 {}
54 
56 
57 bool TxIndex::WriteBlock(const CBlock& block, const CBlockIndex* pindex)
58 {
59  // Exclude genesis block transaction because outputs are not spendable.
60  if (pindex->nHeight == 0) return true;
61 
62  CDiskTxPos pos{
63  WITH_LOCK(::cs_main, return pindex->GetBlockPos()),
64  GetSizeOfCompactSize(block.vtx.size())};
65  std::vector<std::pair<uint256, CDiskTxPos>> vPos;
66  vPos.reserve(block.vtx.size());
67  for (const auto& tx : block.vtx) {
68  vPos.emplace_back(tx->GetHash(), pos);
69  pos.nTxOffset += ::GetSerializeSize(*tx, CLIENT_VERSION);
70  }
71  return m_db->WriteTxs(vPos);
72 }
73 
74 BaseIndex::DB& TxIndex::GetDB() const { return *m_db; }
75 
76 bool TxIndex::FindTx(const uint256& tx_hash, uint256& block_hash, CTransactionRef& tx) const
77 {
78  CDiskTxPos postx;
79  if (!m_db->ReadTxPos(tx_hash, postx)) {
80  return false;
81  }
82 
83  CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
84  if (file.IsNull()) {
85  return error("%s: OpenBlockFile failed", __func__);
86  }
87  CBlockHeader header;
88  try {
89  file >> header;
90  if (fseek(file.Get(), postx.nTxOffset, SEEK_CUR)) {
91  return error("%s: fseek(...) failed", __func__);
92  }
93  file >> tx;
94  } catch (const std::exception& e) {
95  return error("%s: Deserialize or I/O error - %s", __func__, e.what());
96  }
97  if (tx->GetHash() != tx_hash) {
98  return error("%s: txid mismatch", __func__);
99  }
100  block_hash = header.GetHash();
101  return true;
102 }
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1086
TxIndex::DB
Access to the txindex database (indexes/txindex/)
Definition: txindex.cpp:20
SER_DISK
@ SER_DISK
Definition: serialize.h:132
g_txindex
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:16
TxIndex::WriteBlock
bool WriteBlock(const CBlock &block, const CBlockIndex *pindex) override
Write update index entries for a newly connected block.
Definition: txindex.cpp:57
CBlockHeader
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:20
CDBBatch
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:47
CAutoFile::Get
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:519
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:164
CBlockIndex::GetBlockPos
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: chain.h:229
TxIndex::m_db
const std::unique_ptr< DB > m_db
Definition: txindex.h:18
WITH_LOCK
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:270
CDiskTxPos
Definition: disktxpos.h:11
CDiskTxPos::nTxOffset
unsigned int nTxOffset
Definition: disktxpos.h:13
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:406
BaseIndex
Base class for indices of blockchain data.
Definition: base.h:27
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:11
disktxpos.h
txindex.h
CDBBatch::Write
void Write(const K &key, const V &value)
Definition: dbwrapper.h:73
CAutoFile
Non-refcounted RAII wrapper for FILE*.
Definition: streams.h:478
TxIndex::~TxIndex
virtual ~TxIndex() override
Definition: txindex.cpp:55
TxIndex::DB::ReadTxPos
bool ReadTxPos(const uint256 &txid, CDiskTxPos &pos) const
Read the disk location of the transaction data with the given hash.
Definition: txindex.cpp:37
DB_TXINDEX
constexpr uint8_t DB_TXINDEX
Definition: txindex.cpp:14
GetSizeOfCompactSize
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
CAutoFile::IsNull
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:523
node::OpenBlockFile
FILE * OpenBlockFile(const FlatFilePos &pos, bool fReadOnly)
Open a block file (blk?????.dat)
Definition: blockstorage.cpp:599
uint256
256-bit opaque blob.
Definition: uint256.h:126
gArgs
ArgsManager gArgs
Definition: system.cpp:87
TxIndex::GetDB
BaseIndex::DB & GetDB() const override
Definition: txindex.cpp:74
system.h
CBlock
Definition: block.h:62
TxIndex::DB::WriteTxs
bool WriteTxs(const std::vector< std::pair< uint256, CDiskTxPos >> &v_pos)
Write a batch of transaction positions to the DB.
Definition: txindex.cpp:42
CBlock::vtx
std::vector< CTransactionRef > vtx
Definition: block.h:66
TxIndex::DB::DB
DB(size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
Definition: txindex.cpp:33
blockstorage.h
TxIndex::FindTx
bool FindTx(const uint256 &tx_hash, uint256 &block_hash, CTransactionRef &tx) const
Look up a transaction by hash.
Definition: txindex.cpp:76
std
Definition: setup_common.h:33
CLIENT_VERSION
static const int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:33
TxIndex
TxIndex is used to look up transactions included in the blockchain by hash.
Definition: txindex.h:15
BaseIndex::DB
The database stores a block locator of the chain the database is synced to so that the index can effi...
Definition: base.h:37
error
bool error(const char *fmt, const Args &... args)
Definition: system.h:49
cs_main
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: validation.cpp:138
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:151
TxIndex::TxIndex
TxIndex(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