Bitcoin ABC 0.33.11
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
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
113 m_internals->m_task_runner->flush();
114}
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
146 m_internals->Clear();
147}
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, ...) LogPrint(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 const CTransactionRef &tx,
200 std::shared_ptr<const std::vector<Coin>> spent_coins,
201 uint64_t mempool_sequence) {
202 auto event = [tx, spent_coins, mempool_sequence, this] {
203 m_internals->Iterate([&](CValidationInterface &callbacks) {
204 callbacks.TransactionAddedToMempool(tx, spent_coins,
205 mempool_sequence);
206 });
207 };
208 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
209 tx->GetHash().ToString());
210}
211
213 const CTransactionRef &tx, MemPoolRemovalReason reason,
214 uint64_t mempool_sequence) {
215 auto event = [tx, reason, mempool_sequence, this] {
216 m_internals->Iterate([&](CValidationInterface &callbacks) {
217 callbacks.TransactionRemovedFromMempool(tx, reason,
218 mempool_sequence);
219 });
220 };
221 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s reason=%s", __func__,
222 tx->GetHash().ToString(),
223 RemovalReasonToString(reason));
224}
225
227 ChainstateRole role, const std::shared_ptr<const CBlock> &pblock,
228 const CBlockIndex *pindex) {
229 auto event = [role, pblock, pindex, this] {
230 m_internals->Iterate([&](CValidationInterface &callbacks) {
231 callbacks.BlockConnected(role, pblock, pindex);
232 });
233 };
234 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
235 pblock->GetHash().ToString(), pindex->nHeight);
236}
237
239 const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
240 auto event = [pblock, pindex, this] {
241 m_internals->Iterate([&](CValidationInterface &callbacks) {
242 callbacks.BlockDisconnected(pblock, pindex);
243 });
244 };
245 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
246 pblock->GetHash().ToString());
247}
248
250 const CBlockLocator &locator) {
251 auto event = [role, locator, this] {
252 m_internals->Iterate([&](CValidationInterface &callbacks) {
253 callbacks.ChainStateFlushed(role, locator);
254 });
255 };
256 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
257 locator.IsNull() ? "null"
258 : locator.vHave.front().ToString());
259}
260
262 const BlockValidationState &state) {
263 LOG_EVENT("%s: block hash=%s state=%s", __func__,
264 block.GetHash().ToString(), state.ToString());
265 m_internals->Iterate([&](CValidationInterface &callbacks) {
266 callbacks.BlockChecked(block, state);
267 });
268}
269
271 const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
272 LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
273 m_internals->Iterate([&](CValidationInterface &callbacks) {
274 callbacks.NewPoWValidBlock(pindex, block);
275 });
276}
277
279 auto event = [pindex, this] {
280 m_internals->Iterate([&](CValidationInterface &callbacks) {
281 callbacks.BlockFinalized(pindex);
282 });
283 };
284 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
285 pindex ? pindex->GetBlockHash().ToString() : "null");
286}
287
289 const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
290 auto event = [pindex, block, this] {
291 m_internals->Iterate([&](CValidationInterface &callbacks) {
292 callbacks.BlockInvalidated(pindex, block);
293 });
294 };
295 ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
296 block ? block->GetHash().ToString() : "null");
297}
298
300 auto event = [tx, this] {
301 m_internals->Iterate([&](CValidationInterface &callbacks) {
302 callbacks.TransactionFinalized(tx);
303 });
304 };
305 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
306 tx->GetId().ToString());
307}
308
310 const CTransactionRef &tx,
311 std::shared_ptr<const std::vector<Coin>> spent_coins) {
312 auto event = [tx, spent_coins, this] {
313 m_internals->Iterate([&](CValidationInterface &callbacks) {
314 callbacks.TransactionInvalidated(tx, spent_coins);
315 });
316 };
317 ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s", __func__,
318 tx->GetId().ToString());
319}
#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:130
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 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 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:80
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
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: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:317
#define AssertLockNotHeld(cs)
Definition: sync.h:163
#define LOCK(cs)
Definition: sync.h:306
#define REVERSE_LOCK(g)
Definition: sync.h:265
This header provides an interface and simple implementation for a task runner.
#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:159
#define LOG_EVENT(fmt,...)
std::string RemovalReasonToString(const MemPoolRemovalReason &r) noexcept
Definition: txmempool.cpp:1031
#define ENQUEUE_AND_LOG_EVENT(event, fmt, name,...)