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