Bitcoin ABC 0.34.5
P2P Digital Currency
Loading...
Searching...
No Matches
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
7
8#include <chain.h>
10#include <kernel/chain.h>
11#include <logging.h>
12#include <primitives/block.h>
14#include <util/check.h>
15#include <util/task_runner.h>
16
17#include <future>
18#include <tuple>
19#include <unordered_map>
20#include <utility>
21
22std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept;
23
34private:
40 struct ListEntry {
41 std::shared_ptr<CValidationInterface> callbacks;
42 int count = 1;
43 };
44 std::list<ListEntry> m_list GUARDED_BY(m_mutex);
45 std::unordered_map<CValidationInterface *, std::list<ListEntry>::iterator>
47
48public:
49 std::unique_ptr<util::TaskRunnerInterface> m_task_runner;
50
52 std::unique_ptr<util::TaskRunnerInterface> task_runner)
53 : m_task_runner{std::move(Assert(task_runner))} {}
54
55 void Register(std::shared_ptr<CValidationInterface> callbacks)
58 auto inserted = m_map.emplace(callbacks.get(), m_list.end());
59 if (inserted.second) {
60 inserted.first->second = m_list.emplace(m_list.end());
61 }
62 inserted.first->second->callbacks = std::move(callbacks);
63 }
64
68 auto it = m_map.find(callbacks);
69 if (it != m_map.end()) {
70 if (!--it->second->count) {
71 m_list.erase(it->second);
72 }
73 m_map.erase(it);
74 }
75 }
76
83 for (const auto &entry : m_map) {
84 if (!--entry.second->count) {
85 m_list.erase(entry.second);
86 }
87 }
88 m_map.clear();
89 }
90
91 template <typename F>
93 WAIT_LOCK(m_mutex, lock);
94 for (auto it = m_list.begin(); it != m_list.end();) {
95 ++it->count;
96 {
97 REVERSE_LOCK(lock);
98 f(*it->callbacks);
99 }
100 it = --it->count ? std::next(it) : m_list.erase(it);
101 }
102 }
103};
104
106 std::unique_ptr<util::TaskRunnerInterface> task_runner)
107 : m_internals{
108 std::make_unique<ValidationSignalsImpl>(std::move(task_runner))} {}
109
111
115
117 return m_internals->m_task_runner->size();
118}
119
121 std::shared_ptr<CValidationInterface> callbacks) {
122 // Each connection captures the shared_ptr to ensure that each callback is
123 // executed before the subscriber is destroyed. For more details see #18338.
124 m_internals->Register(std::move(callbacks));
125}
126
128 CValidationInterface *callbacks) {
129 // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle
130 // is managed by the caller.
132 {callbacks, [](CValidationInterface *) {}});
133}
134
136 std::shared_ptr<CValidationInterface> callbacks) {
137 UnregisterValidationInterface(callbacks.get());
138}
139
141 CValidationInterface *callbacks) {
142 m_internals->Unregister(callbacks);
143}
144
148
150 std::function<void()> func) {
151 m_internals->m_task_runner->insert(std::move(func));
152}
153
156 // Block until the validation queue drains
157 std::promise<void> promise;
158 CallFunctionInValidationInterfaceQueue([&promise] { promise.set_value(); });
159 promise.get_future().wait();
160}
161
162// Use a macro instead of a function for conditional logging to prevent
163// evaluating arguments when logging is not enabled.
164//
165// NOTE: The lambda captures all local variables by value.
166#define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \
167 do { \
168 auto local_name = (name); \
169 LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \
170 m_internals->m_task_runner->insert([=] { \
171 LOG_EVENT(fmt, local_name, __VA_ARGS__); \
172 event(); \
173 }); \
174 } while (0)
175
176#define LOG_EVENT(fmt, ...) LogDebug(BCLog::VALIDATION, fmt "\n", __VA_ARGS__)
177
179 const CBlockIndex *pindexFork,
180 bool fInitialDownload) {
181 // Dependencies exist that require UpdatedBlockTip events to be delivered in
182 // the order in which the chain actually updates. One way to ensure this is
183 // for the caller to invoke this signal in the same critical section where
184 // the chain is updated
185
186 auto event = [pindexNew, pindexFork, fInitialDownload, this] {
187 m_internals->Iterate([&](CValidationInterface &callbacks) {
188 callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload);
189 });
190 };
192 event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__,
193 pindexNew->GetBlockHash().ToString(),
194 pindexFork ? pindexFork->GetBlockHash().ToString() : "null",
195 fInitialDownload);
196}
197
199 bool is_ibd) {
200 LOG_EVENT("%s: new block hash=%s block height=%d", __func__,
201 new_tip.GetBlockHash().ToString(), new_tip.nHeight);
202 m_internals->Iterate([&](CValidationInterface &callbacks) {
203 callbacks.ActiveTipChange(new_tip, is_ibd);
204 });
205}
206
208 const CTransactionRef &tx,
209 std::shared_ptr<const std::vector<Coin>> spent_coins,
210 uint64_t mempool_sequence) {
211 auto event = [tx, spent_coins, mempool_sequence, this] {
212 m_internals->Iterate([&](CValidationInterface &callbacks) {
213 callbacks.TransactionAddedToMempool(tx, spent_coins,
214 mempool_sequence);
215 });
216 };
217 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
218 tx->GetHash().ToString());
219}
220
222 const CTransactionRef &tx, MemPoolRemovalReason reason,
223 uint64_t mempool_sequence) {
224 auto event = [tx, reason, mempool_sequence, this] {
225 m_internals->Iterate([&](CValidationInterface &callbacks) {
226 callbacks.TransactionRemovedFromMempool(tx, reason,
227 mempool_sequence);
228 });
229 };
230 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s reason=%s", __func__,
231 tx->GetHash().ToString(),
232 RemovalReasonToString(reason));
233}
234
236 ChainstateRole role, const std::shared_ptr<const CBlock> &pblock,
237 const CBlockIndex *pindex) {
238 auto event = [role, pblock, pindex, this] {
239 m_internals->Iterate([&](CValidationInterface &callbacks) {
240 callbacks.BlockConnected(role, pblock, pindex);
241 });
242 };
243 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
244 pblock->GetHash().ToString(), pindex->nHeight);
245}
246
248 const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
249 auto event = [pblock, pindex, this] {
250 m_internals->Iterate([&](CValidationInterface &callbacks) {
251 callbacks.BlockDisconnected(pblock, pindex);
252 });
253 };
254 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
255 pblock->GetHash().ToString());
256}
257
259 const CBlockLocator &locator) {
260 auto event = [role, locator, this] {
261 m_internals->Iterate([&](CValidationInterface &callbacks) {
262 callbacks.ChainStateFlushed(role, locator);
263 });
264 };
265 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
266 locator.IsNull() ? "null"
267 : locator.vHave.front().ToString());
268}
269
271 const BlockValidationState &state) {
272 LOG_EVENT("%s: block hash=%s state=%s", __func__,
273 block.GetHash().ToString(), state.ToString());
274 m_internals->Iterate([&](CValidationInterface &callbacks) {
275 callbacks.BlockChecked(block, state);
276 });
277}
278
280 const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
281 LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
282 m_internals->Iterate([&](CValidationInterface &callbacks) {
283 callbacks.NewPoWValidBlock(pindex, block);
284 });
285}
286
288 auto event = [pindex, this] {
289 m_internals->Iterate([&](CValidationInterface &callbacks) {
290 callbacks.BlockFinalized(pindex);
291 });
292 };
293 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
294 pindex ? pindex->GetBlockHash().ToString() : "null");
295}
296
298 const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
299 auto event = [pindex, block, this] {
300 m_internals->Iterate([&](CValidationInterface &callbacks) {
301 callbacks.BlockInvalidated(pindex, block);
302 });
303 };
304 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
305 block ? block->GetHash().ToString() : "null");
306}
307
309 auto event = [tx, this] {
310 m_internals->Iterate([&](CValidationInterface &callbacks) {
311 callbacks.TransactionFinalized(tx);
312 });
313 };
314 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
315 tx->GetId().ToString());
316}
317
319 const CTransactionRef &tx,
320 std::shared_ptr<const std::vector<Coin>> spent_coins) {
321 auto event = [tx, spent_coins, this] {
322 m_internals->Iterate([&](CValidationInterface &callbacks) {
323 callbacks.TransactionInvalidated(tx, spent_coins);
324 });
325 };
326 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
327 tx->GetId().ToString());
328}
#define Assert(val)
Identity function.
Definition check.h:87
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:25
BlockHash GetBlockHash() const
Definition blockindex.h:129
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition blockindex.h:38
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 BlockInvalidated(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
virtual void ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator)
Notifies listeners of the new active block chain on-disk.
virtual void BlockConnected(ChainstateRole role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being connected.
virtual void BlockChecked(const CBlock &, const BlockValidationState &)
Notifies listeners of a block validation result.
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 TransactionInvalidated(const CTransactionRef &tx, std::shared_ptr< const std::vector< Coin > > spent_coins)
virtual void ActiveTipChange(const CBlockIndex &new_tip, bool is_ibd)
Notifies listeners any time the block chain tip changes, synchronously.
virtual void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex)
Notifies listeners of a block being disconnected.
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 TransactionFinalized(const CTransactionRef &tx)
void UnregisterValidationInterface(CValidationInterface *callbacks)
Unregister subscriber.
void BlockInvalidated(const CBlockIndex *pindex, const std::shared_ptr< const CBlock > &block)
void TransactionInvalidated(const CTransactionRef &tx, std::shared_ptr< const std::vector< Coin > > spent_coins)
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
void TransactionAddedToMempool(const CTransactionRef &, std::shared_ptr< const std::vector< Coin > >, uint64_t mempool_sequence)
void BlockFinalized(const CBlockIndex *pindex)
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
void TransactionFinalized(const CTransactionRef &tx)
ValidationSignals(std::unique_ptr< util::TaskRunnerInterface > task_runner)
void BlockDisconnected(const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void UnregisterAllValidationInterfaces()
Unregister all subscribers.
void RegisterValidationInterface(CValidationInterface *callbacks)
Register subscriber.
void NewPoWValidBlock(const CBlockIndex *, const std::shared_ptr< const CBlock > &)
void UpdatedBlockTip(const CBlockIndex *, const CBlockIndex *, bool fInitialDownload)
void ChainStateFlushed(ChainstateRole, const CBlockLocator &)
void ActiveTipChange(const CBlockIndex &, bool)
void SyncWithValidationInterfaceQueue() LOCKS_EXCLUDED(cs_main)
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
void BlockChecked(const CBlock &, const BlockValidationState &)
void TransactionRemovedFromMempool(const CTransactionRef &, MemPoolRemovalReason, uint64_t mempool_sequence)
void FlushBackgroundCallbacks()
Call any remaining callbacks on the calling thread.
std::unique_ptr< ValidationSignalsImpl > m_internals
void BlockConnected(ChainstateRole, const std::shared_ptr< const CBlock > &, const CBlockIndex *pindex)
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
ValidationSignalsImpl manages a list of shared_ptr<CValidationInterface> callbacks.
void Register(std::shared_ptr< CValidationInterface > callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
std::unique_ptr< util::TaskRunnerInterface > m_task_runner
void Unregister(CValidationInterface *callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
std::unordered_map< CValidationInterface *, std::list< ListEntry >::iterator > m_map GUARDED_BY(m_mutex)
std::list< ListEntry > m_list GUARDED_BY(m_mutex)
void Iterate(F &&f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
ValidationSignalsImpl(std::unique_ptr< util::TaskRunnerInterface > task_runner)
void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Clear unregisters every previously registered callback, erasing every map entry.
std::string ToString() const
Definition validation.h:125
std::string ToString() const
Definition uint256.h:117
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition cs_main.cpp:7
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition chain.h:14
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition rcu.h:259
std::shared_ptr< const CTransaction > CTransactionRef
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
Definition block.h:108
std::vector< BlockHash > vHave
Definition block.h:120
bool IsNull() const
Definition block.h:135
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:304
#define AssertLockNotHeld(cs)
Definition sync.h:163
#define LOCK(cs)
Definition sync.h:295
#define REVERSE_LOCK(g)
Definition sync.h:267
This header provides an interface and simple implementation for a task runner.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition txmempool.h:159
#define LOG_EVENT(fmt,...)
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
#define ENQUEUE_AND_LOG_EVENT(event, fmt, name,...)