Bitcoin Core  24.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-2020 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 <attributes.h>
9 #include <chain.h>
10 #include <consensus/validation.h>
11 #include <logging.h>
12 #include <primitives/block.h>
13 #include <primitives/transaction.h>
14 #include <scheduler.h>
15 
16 #include <future>
17 #include <unordered_map>
18 #include <utility>
19 
29 {
30 private:
36  struct ListEntry { std::shared_ptr<CValidationInterface> callbacks; int count = 1; };
37  std::list<ListEntry> m_list GUARDED_BY(m_mutex);
38  std::unordered_map<CValidationInterface*, std::list<ListEntry>::iterator> m_map GUARDED_BY(m_mutex);
39 
40 public:
41  // We are not allowed to assume the scheduler only runs in one thread,
42  // but must ensure all callbacks happen in-order, so we end up creating
43  // our own queue here :(
45 
46  explicit MainSignalsImpl(CScheduler& scheduler LIFETIMEBOUND) : m_schedulerClient(scheduler) {}
47 
48  void Register(std::shared_ptr<CValidationInterface> callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
49  {
50  LOCK(m_mutex);
51  auto inserted = m_map.emplace(callbacks.get(), m_list.end());
52  if (inserted.second) inserted.first->second = m_list.emplace(m_list.end());
53  inserted.first->second->callbacks = std::move(callbacks);
54  }
55 
57  {
58  LOCK(m_mutex);
59  auto it = m_map.find(callbacks);
60  if (it != m_map.end()) {
61  if (!--it->second->count) m_list.erase(it->second);
62  m_map.erase(it);
63  }
64  }
65 
71  {
72  LOCK(m_mutex);
73  for (const auto& entry : m_map) {
74  if (!--entry.second->count) m_list.erase(entry.second);
75  }
76  m_map.clear();
77  }
78 
79  template<typename F> void Iterate(F&& f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
80  {
81  WAIT_LOCK(m_mutex, lock);
82  for (auto it = m_list.begin(); it != m_list.end();) {
83  ++it->count;
84  {
85  REVERSE_LOCK(lock);
86  f(*it->callbacks);
87  }
88  it = --it->count ? std::next(it) : m_list.erase(it);
89  }
90  }
91 };
92 
94 
96 {
98  m_internals = std::make_unique<MainSignalsImpl>(scheduler);
99 }
100 
102 {
103  m_internals.reset(nullptr);
104 }
105 
107 {
108  if (m_internals) {
109  m_internals->m_schedulerClient.EmptyQueue();
110  }
111 }
112 
114 {
115  if (!m_internals) return 0;
116  return m_internals->m_schedulerClient.CallbacksPending();
117 }
118 
120 {
121  return g_signals;
122 }
123 
124 void RegisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks)
125 {
126  // Each connection captures the shared_ptr to ensure that each callback is
127  // executed before the subscriber is destroyed. For more details see #18338.
128  g_signals.m_internals->Register(std::move(callbacks));
129 }
130 
132 {
133  // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle
134  // is managed by the caller.
136 }
137 
138 void UnregisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks)
139 {
140  UnregisterValidationInterface(callbacks.get());
141 }
142 
144 {
145  if (g_signals.m_internals) {
146  g_signals.m_internals->Unregister(callbacks);
147  }
148 }
149 
151 {
152  if (!g_signals.m_internals) {
153  return;
154  }
155  g_signals.m_internals->Clear();
156 }
157 
158 void CallFunctionInValidationInterfaceQueue(std::function<void()> func)
159 {
160  g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func));
161 }
162 
164 {
166  // Block until the validation queue drains
167  std::promise<void> promise;
169  promise.set_value();
170  });
171  promise.get_future().wait();
172 }
173 
174 // Use a macro instead of a function for conditional logging to prevent
175 // evaluating arguments when logging is not enabled.
176 //
177 // NOTE: The lambda captures all local variables by value.
178 #define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \
179  do { \
180  auto local_name = (name); \
181  LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \
182  m_internals->m_schedulerClient.AddToProcessQueue([=] { \
183  LOG_EVENT(fmt, local_name, __VA_ARGS__); \
184  event(); \
185  }); \
186  } while (0)
187 
188 #define LOG_EVENT(fmt, ...) \
189  LogPrint(BCLog::VALIDATION, fmt "\n", __VA_ARGS__)
190 
191 void CMainSignals::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
192  // Dependencies exist that require UpdatedBlockTip events to be delivered in the order in which
193  // the chain actually updates. One way to ensure this is for the caller to invoke this signal
194  // in the same critical section where the chain is updated
195 
196  auto event = [pindexNew, pindexFork, fInitialDownload, this] {
197  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload); });
198  };
199  ENQUEUE_AND_LOG_EVENT(event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__,
200  pindexNew->GetBlockHash().ToString(),
201  pindexFork ? pindexFork->GetBlockHash().ToString() : "null",
202  fInitialDownload);
203 }
204 
205 void CMainSignals::TransactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {
206  auto event = [tx, mempool_sequence, this] {
207  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionAddedToMempool(tx, mempool_sequence); });
208  };
209  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s", __func__,
210  tx->GetHash().ToString(),
211  tx->GetWitnessHash().ToString());
212 }
213 
214 void CMainSignals::TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {
215  auto event = [tx, reason, mempool_sequence, this] {
216  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionRemovedFromMempool(tx, reason, mempool_sequence); });
217  };
218  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s", __func__,
219  tx->GetHash().ToString(),
220  tx->GetWitnessHash().ToString());
221 }
222 
223 void CMainSignals::BlockConnected(const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
224  auto event = [pblock, pindex, this] {
225  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockConnected(pblock, pindex); });
226  };
227  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
228  pblock->GetHash().ToString(),
229  pindex->nHeight);
230 }
231 
232 void CMainSignals::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
233 {
234  auto event = [pblock, pindex, this] {
235  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockDisconnected(pblock, pindex); });
236  };
237  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
238  pblock->GetHash().ToString(),
239  pindex->nHeight);
240 }
241 
243  auto event = [locator, this] {
244  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.ChainStateFlushed(locator); });
245  };
246  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
247  locator.IsNull() ? "null" : locator.vHave.front().ToString());
248 }
249 
250 void CMainSignals::BlockChecked(const CBlock& block, const BlockValidationState& state) {
251  LOG_EVENT("%s: block hash=%s state=%s", __func__,
252  block.GetHash().ToString(), state.ToString());
253  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockChecked(block, state); });
254 }
255 
256 void CMainSignals::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
257  LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
258  m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.NewPoWValidBlock(pindex, block); });
259 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:414
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
Class used by CScheduler clients which may schedule multiple jobs which are required to be run serial...
Definition: scheduler.h:123
virtual void ChainStateFlushed(const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
std::unique_ptr< MainSignalsImpl > m_internals
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
assert(!tx.IsCoinBase())
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:120
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
Definition: block.h:68
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...
std::list< ListEntry > m_list GUARDED_BY(m_mutex)
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
Definition: txmempool.h:349
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
bool IsNull() const
Definition: block.h:141
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
#define REVERSE_LOCK(g)
Definition: sync.h:242
int count
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
MainSignalsImpl(CScheduler &scheduler LIFETIMEBOUND)
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
Implement this to subscribe to events generated in validation.
void TransactionAddedToMempool(const CTransactionRef &, uint64_t mempool_sequence)
void Iterate(F &&f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
uint256 GetBlockHash() const
Definition: chain.h:264
#define LIFETIMEBOUND
Definition: attributes.h:16
static CMainSignals g_signals
void Unregister(CValidationInterface *callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
#define LOG_EVENT(fmt,...)
#define LOCK(cs)
Definition: sync.h:261
std::string ToString() const
Definition: validation.h:127
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Clear unregisters every previously registered callback, erasing every map entry.
CMainSignals & GetMainSignals()
#define WAIT_LOCK(cs, name)
Definition: sync.h:266
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
std::string ToString() const
Definition: uint256.cpp:64
std::vector< uint256 > vHave
Definition: block.h:122
void ChainStateFlushed(const CBlockLocator &)
std::shared_ptr< CValidationInterface > callbacks
uint256 GetHash() const
Definition: block.cpp:11
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define ENQUEUE_AND_LOG_EVENT(event, fmt, name,...)
void Register(std::shared_ptr< CValidationInterface > callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
SingleThreadedSchedulerClient m_schedulerClient
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:151
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: validation.cpp:121
#define AssertLockNotHeld(cs)
Definition: sync.h:148
virtual void TransactionAddedToMempool(const CTransactionRef &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
MainSignalsImpl manages a list of shared_ptr<CValidationInterface> callbacks.
Simple class for background tasks that should be run periodically or once "after a while"...
Definition: scheduler.h:38
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void BlockChecked(const CBlock &, const BlockValidationState &)
void BlockConnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
List entries consist of a callback pointer and reference count.
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)