Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 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 <kernel/chain.h>
12 : : #include <logging.h>
13 : : #include <primitives/block.h>
14 : : #include <primitives/transaction.h>
15 : : #include <scheduler.h>
16 : :
17 : : #include <future>
18 : : #include <unordered_map>
19 : : #include <utility>
20 : :
21 : : std::string RemovalReasonToString(const MemPoolRemovalReason& r) noexcept;
22 : :
23 : : /**
24 : : * MainSignalsImpl manages a list of shared_ptr<CValidationInterface> callbacks.
25 : : *
26 : : * A std::unordered_map is used to track what callbacks are currently
27 : : * registered, and a std::list is used to store the callbacks that are
28 : : * currently registered as well as any callbacks that are just unregistered
29 : : * and about to be deleted when they are done executing.
30 : : */
31 : 0 : class MainSignalsImpl
32 : : {
33 : : private:
34 : : Mutex m_mutex;
35 : : //! List entries consist of a callback pointer and reference count. The
36 : : //! count is equal to the number of current executions of that entry, plus 1
37 : : //! if it's registered. It cannot be 0 because that would imply it is
38 : : //! unregistered and also not being executed (so shouldn't exist).
39 : 0 : struct ListEntry { std::shared_ptr<CValidationInterface> callbacks; int count = 1; };
40 : : std::list<ListEntry> m_list GUARDED_BY(m_mutex);
41 : : std::unordered_map<CValidationInterface*, std::list<ListEntry>::iterator> m_map GUARDED_BY(m_mutex);
42 : :
43 : : public:
44 : : // We are not allowed to assume the scheduler only runs in one thread,
45 : : // but must ensure all callbacks happen in-order, so we end up creating
46 : : // our own queue here :(
47 : : SingleThreadedSchedulerClient m_schedulerClient;
48 : :
49 [ + - ]: 1 : explicit MainSignalsImpl(CScheduler& scheduler LIFETIMEBOUND) : m_schedulerClient(scheduler) {}
50 : :
51 : 200 : void Register(std::shared_ptr<CValidationInterface> callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
52 : : {
53 : 200 : LOCK(m_mutex);
54 [ + - ]: 200 : auto inserted = m_map.emplace(callbacks.get(), m_list.end());
55 [ + - ][ + - ]: 200 : if (inserted.second) inserted.first->second = m_list.emplace(m_list.end());
56 : 200 : inserted.first->second->callbacks = std::move(callbacks);
57 : 200 : }
58 : :
59 : 200 : void Unregister(CValidationInterface* callbacks) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
60 : : {
61 : 200 : LOCK(m_mutex);
62 [ + - ]: 200 : auto it = m_map.find(callbacks);
63 [ + - ]: 200 : if (it != m_map.end()) {
64 [ + + ]: 200 : if (!--it->second->count) m_list.erase(it->second);
65 [ + - ]: 200 : m_map.erase(it);
66 : 200 : }
67 : 200 : }
68 : :
69 : : //! Clear unregisters every previously registered callback, erasing every
70 : : //! map entry. After this call, the list may still contain callbacks that
71 : : //! are currently executing, but it will be cleared when they are done
72 : : //! executing.
73 : 0 : void Clear() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
74 : : {
75 : 0 : LOCK(m_mutex);
76 [ # # ]: 0 : for (const auto& entry : m_map) {
77 [ # # ]: 0 : if (!--entry.second->count) m_list.erase(entry.second);
78 : : }
79 : 0 : m_map.clear();
80 : 0 : }
81 : :
82 : 603 : template<typename F> void Iterate(F&& f) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
83 : : {
84 : 603 : WAIT_LOCK(m_mutex, lock);
85 [ + + ][ # # ]: 1146 : for (auto it = m_list.begin(); it != m_list.end();) {
[ + + ][ # # ]
[ # # ][ + + ]
[ # # ][ # # ]
86 : 543 : ++it->count;
87 : : {
88 [ + - ][ # # ]: 543 : REVERSE_LOCK(lock);
[ + - ][ # # ]
[ # # ][ + - ]
[ # # ][ # # ]
89 [ - + ][ # # ]: 543 : f(*it->callbacks);
[ - + ][ # # ]
[ # # ][ - + ]
[ # # ][ # # ]
90 : 543 : }
91 [ + - ][ + - ]: 543 : it = --it->count ? std::next(it) : m_list.erase(it);
[ # # ][ # # ]
[ + - ][ + - ]
[ # # ][ # # ]
[ # # ][ # # ]
[ + + ][ + - ]
[ # # ][ # # ]
[ # # ][ # # ]
92 : : }
93 : 603 : }
94 : : };
95 : :
96 : : static CMainSignals g_signals;
97 : :
98 : 1 : void CMainSignals::RegisterBackgroundSignalScheduler(CScheduler& scheduler)
99 : : {
100 [ + - ]: 1 : assert(!m_internals);
101 : 1 : m_internals = std::make_unique<MainSignalsImpl>(scheduler);
102 : 1 : }
103 : :
104 : 1 : void CMainSignals::UnregisterBackgroundSignalScheduler()
105 : : {
106 : 1 : m_internals.reset(nullptr);
107 : 1 : }
108 : :
109 : 1 : void CMainSignals::FlushBackgroundCallbacks()
110 : : {
111 [ - + ]: 1 : if (m_internals) {
112 : 1 : m_internals->m_schedulerClient.EmptyQueue();
113 : 1 : }
114 : 1 : }
115 : :
116 : 201 : size_t CMainSignals::CallbacksPending()
117 : : {
118 [ - + ]: 201 : if (!m_internals) return 0;
119 : 201 : return m_internals->m_schedulerClient.CallbacksPending();
120 : 201 : }
121 : :
122 : 807 : CMainSignals& GetMainSignals()
123 : : {
124 : 807 : return g_signals;
125 : : }
126 : :
127 : 200 : void RegisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks)
128 : : {
129 : : // Each connection captures the shared_ptr to ensure that each callback is
130 : : // executed before the subscriber is destroyed. For more details see #18338.
131 [ + - ]: 200 : g_signals.m_internals->Register(std::move(callbacks));
132 : 200 : }
133 : :
134 : 200 : void RegisterValidationInterface(CValidationInterface* callbacks)
135 : : {
136 : : // Create a shared_ptr with a no-op deleter - CValidationInterface lifecycle
137 : : // is managed by the caller.
138 [ + - ]: 400 : RegisterSharedValidationInterface({callbacks, [](CValidationInterface*){}});
139 : 200 : }
140 : :
141 : 0 : void UnregisterSharedValidationInterface(std::shared_ptr<CValidationInterface> callbacks)
142 : : {
143 : 0 : UnregisterValidationInterface(callbacks.get());
144 : 0 : }
145 : :
146 : 200 : void UnregisterValidationInterface(CValidationInterface* callbacks)
147 : : {
148 [ - + ]: 200 : if (g_signals.m_internals) {
149 : 200 : g_signals.m_internals->Unregister(callbacks);
150 : 200 : }
151 : 200 : }
152 : :
153 : 0 : void UnregisterAllValidationInterfaces()
154 : : {
155 [ # # ]: 0 : if (!g_signals.m_internals) {
156 : 0 : return;
157 : : }
158 : 0 : g_signals.m_internals->Clear();
159 : 0 : }
160 : :
161 : 343 : void CallFunctionInValidationInterfaceQueue(std::function<void()> func)
162 : : {
163 [ + - ]: 343 : g_signals.m_internals->m_schedulerClient.AddToProcessQueue(std::move(func));
164 : 343 : }
165 : :
166 : 343 : void SyncWithValidationInterfaceQueue()
167 : : {
168 : 343 : AssertLockNotHeld(cs_main);
169 : : // Block until the validation queue drains
170 : 343 : std::promise<void> promise;
171 [ + - ]: 686 : CallFunctionInValidationInterfaceQueue([&promise] {
172 : 343 : promise.set_value();
173 : 343 : });
174 [ + - ][ - + ]: 343 : promise.get_future().wait();
175 : 343 : }
176 : :
177 : : // Use a macro instead of a function for conditional logging to prevent
178 : : // evaluating arguments when logging is not enabled.
179 : : //
180 : : // NOTE: The lambda captures all local variables by value.
181 : : #define ENQUEUE_AND_LOG_EVENT(event, fmt, name, ...) \
182 : : do { \
183 : : auto local_name = (name); \
184 : : LOG_EVENT("Enqueuing " fmt, local_name, __VA_ARGS__); \
185 : : m_internals->m_schedulerClient.AddToProcessQueue([=] { \
186 : : LOG_EVENT(fmt, local_name, __VA_ARGS__); \
187 : : event(); \
188 : : }); \
189 : : } while (0)
190 : :
191 : : #define LOG_EVENT(fmt, ...) \
192 : : LogPrint(BCLog::VALIDATION, fmt "\n", __VA_ARGS__)
193 : :
194 : 201 : void CMainSignals::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
195 : : // Dependencies exist that require UpdatedBlockTip events to be delivered in the order in which
196 : : // the chain actually updates. One way to ensure this is for the caller to invoke this signal
197 : : // in the same critical section where the chain is updated
198 : :
199 : 402 : auto event = [pindexNew, pindexFork, fInitialDownload, this] {
200 : 368 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.UpdatedBlockTip(pindexNew, pindexFork, fInitialDownload); });
201 : 201 : };
202 [ + - ][ # # ]: 402 : ENQUEUE_AND_LOG_EVENT(event, "%s: new block hash=%s fork block hash=%s (in IBD=%s)", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ + - ][ + - ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ]
203 : : pindexNew->GetBlockHash().ToString(),
204 : : pindexFork ? pindexFork->GetBlockHash().ToString() : "null",
205 : : fInitialDownload);
206 : 201 : }
207 : :
208 : 0 : void CMainSignals::TransactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) {
209 : 0 : auto event = [tx, mempool_sequence, this] {
210 : 0 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionAddedToMempool(tx, mempool_sequence); });
211 : 0 : };
212 [ # # ][ # # ]: 0 : ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ]
213 : : tx->GetHash().ToString(),
214 : : tx->GetWitnessHash().ToString());
215 : 0 : }
216 : :
217 : 0 : void CMainSignals::TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) {
218 : 0 : auto event = [tx, reason, mempool_sequence, this] {
219 : 0 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.TransactionRemovedFromMempool(tx, reason, mempool_sequence); });
220 : 0 : };
221 [ # # ][ # # ]: 0 : ENQUEUE_AND_LOG_EVENT(event, "%s: txid=%s wtxid=%s reason=%s", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ]
222 : : tx->GetHash().ToString(),
223 : : tx->GetWitnessHash().ToString(),
224 : : RemovalReasonToString(reason));
225 : 0 : }
226 : :
227 : 201 : void CMainSignals::BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock> &pblock, const CBlockIndex *pindex) {
228 : 402 : auto event = [role, pblock, pindex, this] {
229 : 377 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockConnected(role, pblock, pindex); });
230 : 201 : };
231 [ + - ][ + - ]: 402 : ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ + - ]
[ + - ][ + - ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ]
232 : : pblock->GetHash().ToString(),
233 : : pindex->nHeight);
234 : 201 : }
235 : :
236 : 0 : void CMainSignals::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex)
237 : : {
238 : 0 : auto event = [pblock, pindex, this] {
239 : 0 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockDisconnected(pblock, pindex); });
240 : 0 : };
241 [ # # ][ # # ]: 0 : ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s block height=%d", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ]
242 : : pblock->GetHash().ToString(),
243 : : pindex->nHeight);
244 : 0 : }
245 : :
246 : 0 : void CMainSignals::ChainStateFlushed(ChainstateRole role, const CBlockLocator &locator) {
247 : 0 : auto event = [role, locator, this] {
248 : 0 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.ChainStateFlushed(role, locator); });
249 : 0 : };
250 [ # # ][ # # ]: 0 : ENQUEUE_AND_LOG_EVENT(event, "%s: block hash=%s", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ][ # # ]
251 : : locator.IsNull() ? "null" : locator.vHave.front().ToString());
252 : 0 : }
253 : :
254 : 201 : void CMainSignals::BlockChecked(const CBlock& block, const BlockValidationState& state) {
255 [ + - ][ # # ]: 201 : LOG_EVENT("%s: block hash=%s state=%s", __func__,
[ # # ][ # # ]
[ # # ][ # # ]
[ # # ]
256 : : block.GetHash().ToString(), state.ToString());
257 : 401 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.BlockChecked(block, state); });
258 : 201 : }
259 : :
260 : 0 : void CMainSignals::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock> &block) {
261 [ # # ][ # # ]: 0 : LOG_EVENT("%s: block hash=%s", __func__, block->GetHash().ToString());
[ # # ][ # # ]
[ # # ][ # # ]
262 : 0 : m_internals->Iterate([&](CValidationInterface& callbacks) { callbacks.NewPoWValidBlock(pindex, block); });
263 : 0 : }
|