Bitcoin ABC  0.22.12
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 <chain.h>
9 #include <consensus/validation.h>
10 #include <logging.h>
11 #include <primitives/block.h>
12 #include <primitives/transaction.h>
13 #include <scheduler.h>
14 
15 #include <future>
16 #include <tuple>
17 #include <unordered_map>
18 #include <utility>
19 
28 private:
34  struct ListEntry {
35  std::shared_ptr<CValidationInterface> callbacks;
36  int count = 1;
37  };
38  std::list<ListEntry> m_list GUARDED_BY(m_mutex);
39  std::unordered_map<CValidationInterface *, std::list<ListEntry>::iterator>
40  m_map GUARDED_BY(m_mutex);
41 
42 public:
43  // We are not allowed to assume the scheduler only runs in one thread,
44  // but must ensure all callbacks happen in-order, so we end up creating
45  // our own queue here :(
47 
48  explicit MainSignalsInstance(CScheduler *pscheduler)
49  : m_schedulerClient(pscheduler) {}
50 
51  void Register(std::shared_ptr<CValidationInterface> callbacks) {
52  LOCK(m_mutex);
53  auto inserted = m_map.emplace(callbacks.get(), m_list.end());
54  if (inserted.second) {
55  inserted.first->second = m_list.emplace(m_list.end());
56  }
57  inserted.first->second->callbacks = std::move(callbacks);
58  }
59 
61  LOCK(m_mutex);
62  auto it = m_map.find(callbacks);
63  if (it != m_map.end()) {
64  if (!--it->second->count) {
65  m_list.erase(it->second);
66  }
67  m_map.erase(it);
68  }
69  }
70 
75  void Clear() {
76  LOCK(m_mutex);
77  for (const auto &entry : m_map) {
78  if (!--entry.second->count) {
79  m_list.erase(entry.second);
80  }
81  }
82  m_map.clear();
83  }
84 
85  template <typename F> void Iterate(F &&f) {
86  WAIT_LOCK(m_mutex, lock);
87  for (auto it = m_list.begin(); it != m_list.end();) {
88  ++it->count;
89  {
90  REVERSE_LOCK(lock);
91  f(*it->callbacks);
92  }
93  it = --it->count ? std::next(it) : m_list.erase(it);
94  }
95  }
96 };
97 
99 
101  assert(!m_internals);
102  m_internals.reset(new MainSignalsInstance(&scheduler));
103 }
104 
106  m_internals.reset(nullptr);
107 }
108 
110  if (m_internals) {
111  m_internals->m_schedulerClient.EmptyQueue();
112  }
113 }
114 
116  if (!m_internals) {
117  return 0;
118  }
119  return m_internals->m_schedulerClient.CallbacksPending();
120 }
121 
123  return g_signals;
124 }
125 
127  std::shared_ptr<CValidationInterface> pwalletIn) {
128  // Each connection captures pwalletIn to ensure that each callback is
129  // executed before pwalletIn is destroyed. For more details see #18338.
130  g_signals.m_internals->Register(std::move(pwalletIn));
131 }
132 
134  // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle
135  // is managed by the caller.
137  {callbacks, [](CValidationInterface *) {}});
138 }
139 
141  std::shared_ptr<CValidationInterface> callbacks) {
142  UnregisterValidationInterface(callbacks.get());
143 }
144 
146  if (g_signals.m_internals) {
147  g_signals.m_internals->Unregister(pwalletIn);
148  }
149 }
150 
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  g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func));
160 }
161 
164  // Block until the validation queue drains
165  std::promise<void> promise;
166  CallFunctionInValidationInterfaceQueue([&promise] { promise.set_value(); });
167  promise.get_future().wait();
168 }
169 
170 // Use a macro instead of a function for conditional logging to prevent
171 // evaluating arguments when logging is not enabled.
172 //
173 // NOTE: The lambda captures all local variables by value.
174 #define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \
175  do { \
176  auto local_name = (name); \
177  LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \
178  m_internals->m_schedulerClient.AddToProcessQueue([=] { \
179  LOG_EVENT(fmt, local_name, __VA_ARGS__); \
180  event(); \
181  }); \
182  } while (0)
183 
184 #define LOG_EVENT(fmt, ...) LogPrint(BCLog::VALIDATION, fmt "\n", __VA_ARGS__)
185 
187  const CBlockIndex *pindexFork,
188  bool fInitialDownload) {
189  // Dependencies exist that require UpdatedBlockTip events to be delivered in
190  // the order in which the chain actually updates. One way to ensure this is
191  // for the caller to invoke this signal in the same critical section where
192  // the chain is updated
193 
194  auto event = [pindexNew, pindexFork, fInitialDownload, this] {
195  m_internals->Iterate([&](CValidationInterface &callbacks) {
196  callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload);
197  });
198  };
200  event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__,
201  pindexNew->GetBlockHash().ToString(),
202  pindexFork ? pindexFork->GetBlockHash().ToString() : "null",
203  fInitialDownload);
204 }
205 
207  auto event = [ptx, this] {
208  m_internals->Iterate([&](CValidationInterface &callbacks) {
209  callbacks.TransactionAddedToMempool(ptx);
210  });
211  };
212  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
213  ptx->GetHash().ToString());
214 }
215 
217  auto event = [ptx, this] {
218  m_internals->Iterate([&](CValidationInterface &callbacks) {
219  callbacks.TransactionRemovedFromMempool(ptx);
220  });
221  };
222  ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
223  ptx->GetHash().ToString());
224 }
225 
226 void CMainSignals::BlockConnected(const std::shared_ptr<const CBlock> &pblock,
227  const CBlockIndex *pindex) {
228  auto event = [pblock, pindex, this] {
229  m_internals->Iterate([&](CValidationInterface &callbacks) {
230  callbacks.BlockConnected(pblock, pindex);
231  });
232  };
233  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
234  pblock->GetHash().ToString(), pindex->nHeight);
235 }
236 
238  const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
239  auto event = [pblock, pindex, this] {
240  m_internals->Iterate([&](CValidationInterface &callbacks) {
241  callbacks.BlockDisconnected(pblock, pindex);
242  });
243  };
244  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
245  pblock->GetHash().ToString());
246 }
247 
249  auto event = [locator, this] {
250  m_internals->Iterate([&](CValidationInterface &callbacks) {
251  callbacks.ChainStateFlushed(locator);
252  });
253  };
254  ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
255  locator.IsNull() ? "null"
256  : locator.vHave.front().ToString());
257 }
258 
260  const BlockValidationState &state) {
261  LOG_EVENT("%s: block hash=%s state=%s", __func__,
262  block.GetHash().ToString(), state.ToString());
263  m_internals->Iterate([&](CValidationInterface &callbacks) {
264  callbacks.BlockChecked(block, state);
265  });
266 }
267 
269  const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
270  LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
271  m_internals->Iterate([&](CValidationInterface &callbacks) {
272  callbacks.NewPoWValidBlock(pindex, block);
273  });
274 }
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:338
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:115
std::unique_ptr< MainSignalsInstance > m_internals
virtual void ChainStateFlushed(const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
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:110
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
std::shared_ptr< CValidationInterface > callbacks
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
Definition: block.h:62
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > pwalletIn)
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...
void UnregisterBackgroundSignalScheduler()
Unregister a CScheduler to give callbacks which should run in the background - these callbacks will n...
std::vector< BlockHash > vHave
Definition: block.h:111
void TransactionRemovedFromMempool(const CTransactionRef &)
void UnregisterAllValidationInterfaces()
Unregister all wallets from core.
bool IsNull() const
Definition: block.h:131
std::list< ListEntry > m_list GUARDED_BY(m_mutex)
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
#define REVERSE_LOCK(g)
Definition: sync.h:222
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Implement this to subscribe to events generated in validation.
virtual void BlockConnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
int count
BlockHash GetBlockHash() const
Definition: blockindex.h:133
static CMainSignals g_signals
#define LOG_EVENT(fmt,...)
#define LOCK(cs)
Definition: sync.h:230
std::string ToString() const
Definition: validation.h:122
SingleThreadedSchedulerClient m_schedulerClient
MainSignalsInstance(CScheduler *pscheduler)
virtual void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload)
Notifies listeners when the block chain tip advances.
RecursiveMutex cs_main
Global state.
Definition: validation.cpp:90
CMainSignals & GetMainSignals()
#define WAIT_LOCK(cs, name)
Definition: sync.h:238
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.h:74
void ChainStateFlushed(const CBlockLocator &)
void Unregister(CValidationInterface *callbacks)
void Clear()
Clear unregisters every previously registered callback, erasing every map entry.
void RegisterBackgroundSignalScheduler(CScheduler &scheduler)
Register a CScheduler to give callbacks which should run in the background (may only be called once) ...
#define ENQUEUE_AND_LOG_EVENT(event, fmt, name,...)
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: blockindex.h:23
BlockHash GetHash() const
Definition: block.cpp:11
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
virtual void TransactionRemovedFromMempool(const CTransactionRef &ptx)
Notifies listeners of a transaction leaving mempool.
#define AssertLockNotHeld(cs)
Definition: sync.h:88
virtual void TransactionAddedToMempool(const CTransactionRef &ptxn)
Notifies listeners of a transaction having been added to mempool.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register a wallet to receive updates from core.
The MainSignalsInstance manages a list of shared_ptr<CValidationInterface> callbacks.
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)
void Register(std::shared_ptr< CValidationInterface > callbacks)
List entries consist of a callback pointer and reference count.
void TransactionAddedToMempool(const CTransactionRef &)