Bitcoin Core  29.1.0
P2P Digital Currency
validationinterface.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <validationinterface.h>
7 
8 #include <chain.h>
9 #include <consensus/validation.h>
10 #include <kernel/chain.h>
11 #include <kernel/mempool_entry.h>
13 #include <logging.h>
14 #include <primitives/block.h>
15 #include <primitives/transaction.h>
16 #include <util/check.h>
17 #include <util/task_runner.h>
18 
19 #include <future>
20 #include <unordered_map>
21 #include <utility>
22 
32 {
33 private:
39  struct ListEntry { std::shared_ptr<CValidationInterface> callbacks; int count = 1; };
40  std::list<ListEntry> m_list GUARDED_BY(m_mutex);
41  std::unordered_map<CValidationInterface*, std::list<ListEntry>::iterator> m_map GUARDED_BY(m_mutex);
42 
43 public:
44  std::unique_ptr<util::TaskRunnerInterface> m_task_runner;
45 
46  explicit ValidationSignalsImpl(std::unique_ptr<util::TaskRunnerInterface> task_runner)
47  : m_task_runner{std::move(Assert(task_runner))} {}
48 
49  void Register(std::shared_ptr<CValidationInterface> callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
50  {
51  LOCK(m_mutex);
52  auto inserted = m_map.emplace(callbacks.get(), m_list.end());
53  if (inserted.second) inserted.first->second = m_list.emplace(m_list.end());
54  inserted.first->second->callbacks = std::move(callbacks);
55  }
56 
58  {
59  LOCK(m_mutex);
60  auto it = m_map.find(callbacks);
61  if (it != m_map.end()) {
62  if (!--it->second->count) m_list.erase(it->second);
63  m_map.erase(it);
64  }
65  }
66 
72  {
73  LOCK(m_mutex);
74  for (const auto& entry : m_map) {
75  if (!--entry.second->count) m_list.erase(entry.second);
76  }
77  m_map.clear();
78  }
79 
80  template<typename F> void Iterate(F&& f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
81  {
82  WAIT_LOCK(m_mutex, lock);
83  for (auto it = m_list.begin(); it != m_list.end();) {
84  ++it->count;
85  {
86  REVERSE_LOCK(lock);
87  f(*it->callbacks);
88  }
89  it = --it->count ? std::next(it) : m_list.erase(it);
90  }
91  }
92 };
93 
94 ValidationSignals::ValidationSignals(std::unique_ptr<util::TaskRunnerInterface> task_runner)
95  : m_internals{std::make_unique<ValidationSignalsImpl>(std::move(task_runner))} {}
96 
98 
100 {
101  m_internals->m_task_runner->flush();
102 }
103 
105 {
106  return m_internals->m_task_runner->size();
107 }
108 
109 void ValidationSignals::RegisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks)
110 {
111  // Each connection captures the shared_ptr to ensure that each callback is
112  // executed before the subscriber is destroyed. For more details see #18338.
113  m_internals->Register(std::move(callbacks));
114 }
115 
117 {
118  // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle
119  // is managed by the caller.
121 }
122 
123 void ValidationSignals::UnregisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks)
124 {
125  UnregisterValidationInterface(callbacks.get());
126 }
127 
129 {
130  m_internals->Unregister(callbacks);
131 }
132 
134 {
135  m_internals->Clear();
136 }
137 
139 {
140  m_internals->m_task_runner->insert(std::move(func));
141 }
142 
144 {
146  // Block until the validation queue drains
147  std::promise<void> promise;
149  promise.set_value();
150  });
151  promise.get_future().wait();
152 }
153 
154 // Use a macro instead of a function for conditional logging to prevent
155 // evaluating arguments when logging is not enabled.
156 //
157 // NOTE: The lambda captures all local variables by value.
158 #define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \
159  do { \
160  auto local_name = (name); \
161  LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \
162  m_internals->m_task_runner->insert([=] { \
163  LOG_EVENT(fmt, local_name, __VA_ARGS__); \
164  event(); \
165  }); \
166  } while (0)
167 
168 #define LOG_EVENT(fmt, ...) \
169  LogDebug(BCLog::VALIDATION, fmt "\n", __VA_ARGS__)
170 
171 void ValidationSignals::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
172  // Dependencies exist that require UpdatedBlockTip events to be delivered in the order in which
173  // the chain actually updates. One way to ensure this is for the caller to invoke this signal
174  // in the same critical section where the chain is updated
175 
176  auto event = [pindexNew, pindexFork, fInitialDownload, this] {
177  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload); });
178  };
179  ENQUEUE_AND_LOG_EVENT(event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__,
180  pindexNew->GetBlockHash().ToString(),
181  pindexFork ? pindexFork->GetBlockHash().ToString() : "null",
182  fInitialDownload);
183 }
184 
185 void ValidationSignals::ActiveTipChange(const CBlockIndex& new_tip, bool is_ibd)
186 {
187  LOG_EVENT("%s: new block hash=%s block height=%d", __func__, new_tip.GetBlockHash().ToString(), new_tip.nHeight);
188  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.ActiveTipChange(new_tip, is_ibd); });
189 }
190 
192 {
193  auto event = [tx, mempool_sequence, this] {
194  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionAddedToMempool(tx, mempool_sequence); });
195  };
196  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s", __func__,
197  tx.info.m_tx->GetHash().ToString(),
198  tx.info.m_tx->GetWitnessHash().ToString());
199 }
200 
202  auto event = [tx, reason, mempool_sequence, this] {
203  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionRemovedFromMempool(tx, reason, mempool_sequence); });
204  };
205  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s reason=%s", __func__,
206  tx->GetHash().ToString(),
207  tx->GetWitnessHash().ToString(),
208  RemovalReasonToString(reason));
209 }
210 
211 void ValidationSignals::BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
212  auto event = [role, pblock, pindex, this] {
213  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockConnected(role, pblock, pindex); });
214  };
215  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
216  pblock->GetHash().ToString(),
217  pindex->nHeight);
218 }
219 
220 void ValidationSignals::MempoolTransactionsRemovedForBlock(const std::vector<RemovedMempoolTransactionInfo>& txs_removed_for_block, unsigned int nBlockHeight)
221 {
222  auto event = [txs_removed_for_block, nBlockHeight, this] {
223  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight); });
224  };
225  ENQUEUE_AND_LOG_EVENT(event, "%s: block height=%s txs removed=%s", __func__,
226  nBlockHeight,
227  txs_removed_for_block.size());
228 }
229 
230 void ValidationSignals::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
231 {
232  auto event = [pblock, pindex, this] {
233  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockDisconnected(pblock, pindex); });
234  };
235  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
236  pblock->GetHash().ToString(),
237  pindex->nHeight);
238 }
239 
241  auto event = [role, locator, this] {
242  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.ChainStateFlushed(role, locator); });
243  };
244  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
245  locator.IsNull() ? "null" : locator.vHave.front().ToString());
246 }
247 
249  LOG_EVENT("%s: block hash=%s state=%s", __func__,
250  block.GetHash().ToString(), state.ToString());
251  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockChecked(block, state); });
252 }
253 
254 void ValidationSignals::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
255  LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
256  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.NewPoWValidBlock(pindex, block); });
257 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
std::unique_ptr< ValidationSignalsImpl > m_internals
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void BlockConnected(ChainstateRole, const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void TransactionAddedToMempool(const NewMempoolTransactionInfo &, uint64_t mempool_sequence)
std::unique_ptr< util::TaskRunnerInterface > m_task_runner
Describes a place in the block chain to another node such that if the other node doesn&#39;t have the sam...
Definition: block.h:123
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected Provides the block that was disconnected.
Definition: block.h:68
void Register(std::shared_ptr< CValidationInterface > callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
std::list< ListEntry > m_list GUARDED_BY(m_mutex)
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
virtual void NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
Notifies listeners that a block which builds directly on our current tip has been received and connec...
virtual void ActiveTipChange(const CBlockIndex &new_tip, bool is_ibd)
Notifies listeners any time the block chain tip changes, synchronously.
void Unregister(CValidationInterface *callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
ValidationSignalsImpl(std::unique_ptr< util::TaskRunnerInterface > task_runner)
#define REVERSE_LOCK(g)
Definition: sync.h:243
void ChainStateFlushed(ChainstateRole, const CBlockLocator &)
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Clear unregisters every previously registered callback, erasing every map entry.
virtual void TransactionAddedToMempool(const NewMempoolTransactionInfo &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
Implement this to subscribe to events generated in validation and mempool.
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
uint256 GetBlockHash() const
Definition: chain.h:243
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
#define LOG_EVENT(fmt,...)
#define LOCK(cs)
Definition: sync.h:257
std::string ToString() const
Definition: validation.h:112
void ActiveTipChange(const CBlockIndex &, bool)
List entries consist of a callback pointer and reference count.
int count
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void MempoolTransactionsRemovedForBlock(const std::vector< RemovedMempoolTransactionInfo > &txs_removed_for_block, unsigned int nBlockHeight)
ValidationSignals(std::unique_ptr< util::TaskRunnerInterface > task_runner)
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
std::shared_ptr< CValidationInterface > callbacks
#define WAIT_LOCK(cs, name)
Definition: sync.h:262
std::string ToString() const
Definition: uint256.cpp:47
This header provides an interface and simple implementation for a task runner.
uint256 GetHash() const
Definition: block.cpp:11
ValidationSignalsImpl manages a list of shared_ptr<CValidationInterface> callbacks.
void SyncWithValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main)
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define ENQUEUE_AND_LOG_EVENT(event, fmt, name,...)
void MempoolTransactionsRemovedForBlock(const std::vector< RemovedMempoolTransactionInfo > &, unsigned int nBlockHeight)
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:140
virtual void ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
const CTransactionRef m_tx
#define AssertLockNotHeld(cs)
Definition: sync.h:147
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
virtual void BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:153
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void Iterate(F &&f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
#define Assert(val)
Identity function.
Definition: check.h:85
void BlockChecked(const CBlock &, const BlockValidationState &)
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)