Bitcoin ABC  0.29.4
P2P Digital Currency
txindex.cpp
Go to the documentation of this file.
1 // Copyright (c) 2017-2018 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 <index/disktxpos.h>
10 #include <logging.h>
11 #include <node/blockstorage.h>
12 #include <validation.h>
13 
14 constexpr uint8_t DB_TXINDEX{'t'};
15 
16 std::unique_ptr<TxIndex> g_txindex;
17 
19 class TxIndex::DB : public BaseIndex::DB {
20 public:
21  explicit DB(size_t n_cache_size, bool f_memory = false,
22  bool f_wipe = false);
23 
26  bool ReadTxPos(const TxId &txid, CDiskTxPos &pos) const;
27 
29  bool WriteTxs(const std::vector<std::pair<TxId, CDiskTxPos>> &v_pos);
30 };
31 
32 TxIndex::DB::DB(size_t n_cache_size, bool f_memory, bool f_wipe)
33  : BaseIndex::DB(gArgs.GetDataDirNet() / "indexes" / "txindex", n_cache_size,
34  f_memory, f_wipe) {}
35 
36 bool TxIndex::DB::ReadTxPos(const TxId &txid, CDiskTxPos &pos) const {
37  return Read(std::make_pair(DB_TXINDEX, txid), pos);
38 }
39 
41  const std::vector<std::pair<TxId, CDiskTxPos>> &v_pos) {
42  CDBBatch batch(*this);
43  for (const auto &tuple : v_pos) {
44  batch.Write(std::make_pair(DB_TXINDEX, tuple.first), tuple.second);
45  }
46  return WriteBatch(batch);
47 }
48 
49 TxIndex::TxIndex(size_t n_cache_size, bool f_memory, bool f_wipe)
50  : m_db(std::make_unique<TxIndex::DB>(n_cache_size, f_memory, f_wipe)) {}
51 
53 
54 bool TxIndex::WriteBlock(const CBlock &block, const CBlockIndex *pindex) {
55  // Exclude genesis block transaction because outputs are not spendable.
56  if (pindex->nHeight == 0) {
57  return true;
58  }
59 
60  CDiskTxPos pos(WITH_LOCK(::cs_main, return pindex->GetBlockPos()),
61  GetSizeOfCompactSize(block.vtx.size()));
62  std::vector<std::pair<TxId, CDiskTxPos>> vPos;
63  vPos.reserve(block.vtx.size());
64  for (const auto &tx : block.vtx) {
65  vPos.emplace_back(tx->GetId(), pos);
67  }
68  return m_db->WriteTxs(vPos);
69 }
70 
72  return *m_db;
73 }
74 
75 bool TxIndex::FindTx(const TxId &txid, BlockHash &block_hash,
76  CTransactionRef &tx) const {
77  CDiskTxPos postx;
78  if (!m_db->ReadTxPos(txid, postx)) {
79  return false;
80  }
81 
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->GetId() != txid) {
98  return error("%s: txid mismatch", __func__);
99  }
100  block_hash = header.GetHash();
101  return true;
102 }
ArgsManager gArgs
Definition: args.cpp:38
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:570
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:567
The database stores a block locator of the chain the database is synced to so that the TxIndex can ef...
Definition: base.h:36
Base class for indices of blockchain data.
Definition: base.h:27
Chainstate * m_chainstate
Definition: base.h:82
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
Definition: block.h:60
std::vector< CTransactionRef > vtx
Definition: block.h:63
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:113
Batch of changes queued to be written to a CDBWrapper.
Definition: dbwrapper.h:78
void Write(const K &key, const V &value)
Definition: dbwrapper.h:103
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Definition: validation.h:704
Access to the txindex database (indexes/txindex/)
Definition: txindex.cpp:19
bool WriteTxs(const std::vector< std::pair< TxId, CDiskTxPos >> &v_pos)
Write a batch of transaction positions to the DB.
Definition: txindex.cpp:40
DB(size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
Definition: txindex.cpp:32
bool ReadTxPos(const TxId &txid, CDiskTxPos &pos) const
Read the disk location of the transaction data with the given ID.
Definition: txindex.cpp:36
TxIndex is used to look up transactions included in the blockchain by ID.
Definition: txindex.h:22
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:49
bool FindTx(const TxId &txid, BlockHash &block_hash, CTransactionRef &tx) const
Look up a transaction by identifier.
Definition: txindex.cpp:75
BaseIndex::DB & GetDB() const override
Definition: txindex.cpp:71
virtual ~TxIndex() override
Definition: txindex.cpp:52
bool WriteBlock(const CBlock &block, const CBlockIndex *pindex) override
Write update index entries for a newly connected block.
Definition: txindex.cpp:54
const std::unique_ptr< DB > m_db
Definition: txindex.h:24
bool IsBlockPruned(const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(void UpdatePruneLock(const std::string &name, const PruneLockInfo &lock_info) EXCLUSIVE_LOCKS_REQUIRED(FILE OpenBlockFile)(const FlatFilePos &pos, bool fReadOnly=false) const
Check whether the block associated with this index entry is pruned or not.
Definition: blockstorage.h:274
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
bool error(const char *fmt, const Args &...args)
Definition: logging.h:225
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:257
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
uint32_t 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:373
@ SER_DISK
Definition: serialize.h:153
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1258
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
unsigned int nTxOffset
Definition: disktxpos.h:12
A TxId is the identifier of a transaction.
Definition: txid.h:14
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
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