Bitcoin ABC  0.26.3
P2P Digital Currency
validationinterface.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 <tuple>
18 #include <unordered_map>
19 #include <utility>
20 
31 private:
37  struct ListEntry {
38  std::shared_ptr<CValidationInterface> callbacks;
39  int count = 1;
40  };
41  std::list<ListEntry> m_list GUARDED_BY(m_mutex);
42  std::unordered_map<CValidationInterface *, std::list<ListEntry>::iterator>
44 
45 public:
46  // We are not allowed to assume the scheduler only runs in one thread,
47  // but must ensure all callbacks happen in-order, so we end up creating
48  // our own queue here :(
50 
52  : m_schedulerClient(scheduler) {}
53 
54  void Register(std::shared_ptr<CValidationInterface> callbacks)
56  LOCK(m_mutex);
57  auto inserted = m_map.emplace(callbacks.get(), m_list.end());
58  if (inserted.second) {
59  inserted.first->second = m_list.emplace(m_list.end());
60  }
61  inserted.first->second->callbacks = std::move(callbacks);
62  }
63 
66  LOCK(m_mutex);
67  auto it = m_map.find(callbacks);
68  if (it != m_map.end()) {
69  if (!--it->second->count) {
70  m_list.erase(it->second);
71  }
72  m_map.erase(it);
73  }
74  }
75 
81  LOCK(m_mutex);
82  for (const auto &entry : m_map) {
83  if (!--entry.second->count) {
84  m_list.erase(entry.second);
85  }
86  }
87  m_map.clear();
88  }
89 
90  template <typename F>
92  WAIT_LOCK(m_mutex, lock);
93  for (auto it = m_list.begin(); it != m_list.end();) {
94  ++it->count;
95  {
96  REVERSE_LOCK(lock);
97  f(*it->callbacks);
98  }
99  it = --it->count ? std::next(it) : m_list.erase(it);
100  }
101  }
102 };
103 
105 
108  m_internals = std::make_unique<MainSignalsImpl>(scheduler);
109 }
110 
112  m_internals.reset(nullptr);
113 }
114 
116  if (m_internals) {
117  m_internals->m_schedulerClient.EmptyQueue();
118  }
119 }
120 
122  if (!m_internals) {
123  return 0;
124  }
125  return m_internals->m_schedulerClient.CallbacksPending();
126 }
127 
129  return g_signals;
130 }
131 
133  std::shared_ptr<CValidationInterface> callbacks) {
134  // Each connection captures the shared_ptr to ensure that each callback is
135  // executed before the subscriber is destroyed. For more details see #18338.
136  g_signals.m_internals->Register(std::move(callbacks));
137 }
138 
140  // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle
141  // is managed by the caller.
143  {callbacks, [](CValidationInterface *) {}});
144 }
145 
147  std::shared_ptr<CValidationInterface> callbacks) {
148  UnregisterValidationInterface(callbacks.get());
149 }
150 
152  if (g_signals.m_internals) {
153  g_signals.m_internals->Unregister(callbacks);
154  }
155 }
156 
158  if (!g_signals.m_internals) {
159  return;
160  }
161  g_signals.m_internals->Clear();
162 }
163 
164 void CallFunctionInValidationInterfaceQueue(std::function<void()> func) {
165  g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func));
166 }
167 
170  // Block until the validation queue drains
171  std::promise<void> promise;
172  CallFunctionInValidationInterfaceQueue([&promise] { promise.set_value(); });
173  promise.get_future().wait();
174 }
175 
176 // Use a macro instead of a function for conditional logging to prevent
177 // evaluating arguments when logging is not enabled.
178 //
179 // NOTE: The lambda captures all local variables by value.
180 #define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \
181  do { \
182  auto local_name = (name); \
183  LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \
184  m_internals->m_schedulerClient.AddToProcessQueue([=] { \
185  LOG_EVENT(fmt, local_name, __VA_ARGS__); \
186  event(); \
187  }); \
188  } while (0)
189 
190 #define LOG_EVENT(fmt, ...) LogPrint(BCLog::VALIDATION, fmt "\n", __VA_ARGS__)
191 
193  const CBlockIndex *pindexFork,
194  bool fInitialDownload) {
195  // Dependencies exist that require UpdatedBlockTip events to be delivered in
196  // the order in which the chain actually updates. One way to ensure this is
197  // for the caller to invoke this signal in the same critical section where
198  // the chain is updated
199 
200  auto event = [pindexNew, pindexFork, fInitialDownload, this] {
201  m_internals->Iterate([&](CValidationInterface &callbacks) {
202  callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload);
203  });
204  };
206  event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__,
207  pindexNew->GetBlockHash().ToString(),
208  pindexFork ? pindexFork->GetBlockHash().ToString() : "null",
209  fInitialDownload);
210 }
211 
213  const CTransactionRef &tx,
214  std::shared_ptr<const std::vector<Coin>> spent_coins,
215  uint64_t mempool_sequence) {
216  auto event = [tx, spent_coins, mempool_sequence, this] {
217  m_internals->Iterate([&](CValidationInterface &callbacks) {
218  callbacks.TransactionAddedToMempool(tx, spent_coins,
219  mempool_sequence);
220  });
221  };
222  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
223  tx->GetHash().ToString());
224 }
225 
227  MemPoolRemovalReason reason,
228  uint64_t mempool_sequence) {
229  auto event = [tx, reason, mempool_sequence, this] {
230  m_internals->Iterate([&](CValidationInterface &callbacks) {
231  callbacks.TransactionRemovedFromMempool(tx, reason,
232  mempool_sequence);
233  });
234  };
235  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
236  tx->GetHash().ToString());
237 }
238 
239 void CMainSignals::BlockConnected(const std::shared_ptr<const CBlock> &pblock,
240  const CBlockIndex *pindex) {
241  auto event = [pblock, pindex, this] {
242  m_internals->Iterate([&](CValidationInterface &callbacks) {
243  callbacks.BlockConnected(pblock, pindex);
244  });
245  };
246  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
247  pblock->GetHash().ToString(), pindex->nHeight);
248 }
249 
251  const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
252  auto event = [pblock, pindex, this] {
253  m_internals->Iterate([&](CValidationInterface &callbacks) {
254  callbacks.BlockDisconnected(pblock, pindex);
255  });
256  };
257  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
258  pblock->GetHash().ToString());
259 }
260 
262  auto event = [locator, this] {
263  m_internals->Iterate([&](CValidationInterface &callbacks) {
264  callbacks.ChainStateFlushed(locator);
265  });
266  };
267  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
268  locator.IsNull() ? "null"
269  : locator.vHave.front().ToString());
270 }
271 
273  const BlockValidationState &state) {
274  LOG_EVENT("%s: block hash=%s state=%s", __func__,
275  block.GetHash().ToString(), state.ToString());
276  m_internals->Iterate([&](CValidationInterface &callbacks) {
277  callbacks.BlockChecked(block, state);
278  });
279 }
280 
282  const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
283  LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
284  m_internals->Iterate([&](CValidationInterface &callbacks) {
285  callbacks.NewPoWValidBlock(pindex, block);
286  });
287 }
288 
290  auto event = [pindex, this] {
291  m_internals->Iterate([&](CValidationInterface &callbacks) {
292  callbacks.BlockFinalized(pindex);
293  });
294  };
295  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
296  pindex ? pindex->GetBlockHash().ToString() : "null");
297 }
#define LIFETIMEBOUND
Definition: attributes.h:16
BlockHash GetHash() const
Definition: block.cpp:11
Definition: block.h:60
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:26
BlockHash GetBlockHash() const
Definition: blockindex.h:147
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:39
void BlockConnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void BlockChecked(const CBlock &, const BlockValidationState &)
std::unique_ptr< MainSignalsImpl > m_internals
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
void BlockFinalized(const CBlockIndex *)
void TransactionAddedToMempool(const CTransactionRef &, std::shared_ptr< const std::vector< Coin >>, uint64_t mempool_sequence)
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once)
void ChainStateFlushed(const CBlockLocator &)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
Simple class for background tasks that should be run periodically or once "after a while".
Definition: scheduler.h:41
Implement this to subscribe to events generated in validation.
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 ChainStateFlushed(const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
virtual void TransactionAddedToMempool(const CTransactionRef &tx, std::shared_ptr< const std::vector< Coin >> spent_coins, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
virtual void BlockFinalized(const CBlockIndex *pindex)
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
MainSignalsImpl manages a list of shared_ptr<CValidationInterface> callbacks.
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Clear unregisters every previously registered callback, erasing every map entry.
std::list< ListEntry > m_list GUARDED_BY(m_mutex)
void Iterate(F &&f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
void Unregister(CValidationInterface *callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
std::unordered_map< CValidationInterface *, std::list< ListEntry >::iterator > m_map GUARDED_BY(m_mutex)
void Register(std::shared_ptr< CValidationInterface > callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
SingleThreadedSchedulerClient m_schedulerClient
MainSignalsImpl(CScheduler &scheduler LIFETIMEBOUND)
Class used by CScheduler clients which may schedule multiple jobs which are required to be run serial...
Definition: scheduler.h:143
std::string ToString() const
Definition: validation.h:118
std::string ToString() const
Definition: uint256.h:80
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition: block.h:105
std::vector< BlockHash > vHave
Definition: block.h:106
bool IsNull() const
Definition: block.h:123
List entries consist of a callback pointer and reference count.
int count
std::shared_ptr< CValidationInterface > callbacks
#define WAIT_LOCK(cs, name)
Definition: sync.h:317
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define REVERSE_LOCK(g)
Definition: sync.h:265
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: txmempool.h:148
assert(!tx.IsCoinBase())
CMainSignals & GetMainSignals()
#define LOG_EVENT(fmt,...)
static CMainSignals g_signals
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
#define ENQUEUE_AND_LOG_EVENT(event, fmt, name,...)
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.