Debian Codegraph @

src/rpc/zmq_pub.cpp

raw symbols SCIP
1 // Copyright (c) 2020-2022, The Monero Project
2
3 //
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without modification, are
7 // permitted provided that the following conditions are met:
8 //
9 // 1. Redistributions of source code must retain the above copyright notice, this list of
10 // conditions and the following disclaimer.
11 //
12 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
13 // of conditions and the following disclaimer in the documentation and/or other
14 // materials provided with the distribution.
15 //
16 // 3. Neither the name of the copyright holder nor the names of its contributors may be
17 // used to endorse or promote products derived from this software without specific
18 // prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
21 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
23 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
28 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 #include "zmq_pub.h"
31
32 #include <algorithm>
33 #include <boost/range/adaptor/filtered.hpp>
34 #include <boost/range/adaptor/transformed.hpp>
35 #include <boost/thread/locks.hpp>
36 #include <cassert>
37 #include <cstdint>
38 #include <cstring>
39 #include <rapidjson/document.h>
40 #include <rapidjson/stringbuffer.h>
41 #include <rapidjson/writer.h>
42 #include <stdexcept>
43 #include <string>
44 #include <utility>
45
46 #include "common/expect.h"
47 #include "crypto/crypto.h"
48 #include "cryptonote_basic/cryptonote_format_utils.h"
49 #include "cryptonote_basic/events.h"
50 #include "misc_log_ex.h"
51 #include "serialization/json_object.h"
52 #include "ringct/rctTypes.h"
53 #include "cryptonote_core/cryptonote_tx_utils.h"
54
55 #undef MONERO_DEFAULT_LOG_CATEGORY
56 #define MONERO_DEFAULT_LOG_CATEGORY "net.zmq"
57
58 namespace
59 {
60 constexpr const char txpool_signal[] = "tx_signal";
61
62 using chain_writer = void(epee::byte_stream&, std::uint64_t, epee::span<const cryptonote::block>);
63 using miner_writer = void(epee::byte_stream&, uint8_t, uint64_t, const crypto::hash&, const crypto::hash&, cryptonote::difficulty_type, uint64_t, uint64_t, const std::vector<cryptonote::tx_block_template_backlog_entry>&);
64 using txpool_writer = void(epee::byte_stream&, epee::span<const cryptonote::txpool_event>);
65
66 template<typename F>
67 struct context
68 {
69 char const* const name;
70 F* generate_pub;
71 };
72
73 template<typename T>
74 bool operator<(const context<T>& lhs, const context<T>& rhs) noexcept
75 {
76 return std::strcmp(lhs.name, rhs.name) < 0;
77 }
78
79 template<typename T>
80 bool operator<(const context<T>& lhs, const boost::string_ref rhs) noexcept
81 {
82 return lhs.name < rhs;
83 }
84
85 struct is_valid
86 {
87 bool operator()(const cryptonote::txpool_event& event) const noexcept
88 {
89 return event.res;
90 }
91 };
92
93 template<typename T, std::size_t N>
94 void verify_sorted(const std::array<context<T>, N>& elems, const char* name)
95 {
96 auto unsorted = std::is_sorted_until(elems.begin(), elems.end());
97 if (unsorted != elems.end())
98 throw std::logic_error{name + std::string{" array is not properly sorted, see: "} + unsorted->name};
99 }
100
101 void write_header(epee::byte_stream& buf, const boost::string_ref name)
102 {
103 buf.write(name.data(), name.size());
104 buf.put(':');
105 }
106
107 //! \return `name:...` where `...` is JSON and `name` is directly copied (no quotes - not JSON).
108 template<typename T>
109 void json_pub(epee::byte_stream& buf, const T value)
110 {
111 rapidjson::Writer<epee::byte_stream> dest{buf};
112 using cryptonote::json::toJsonValue;
113 toJsonValue(dest, value);
114 }
115
116 //! Object for "minimal" block serialization
117 struct minimal_chain
118 {
119 const std::uint64_t height;
120 const epee::span<const cryptonote::block> blocks;
121 };
122
123 //! Object for miner data serialization
124 struct miner_data
125 {
126 uint8_t major_version;
127 uint64_t height;
128 const crypto::hash& prev_id;
129 const crypto::hash& seed_hash;
130 cryptonote::difficulty_type diff;
131 uint64_t median_weight;
132 uint64_t already_generated_coins;
133 const std::vector<cryptonote::tx_block_template_backlog_entry>& tx_backlog;
134 };
135
136 //! Object for "minimal" tx serialization
137 struct minimal_txpool
138 {
139 const cryptonote::transaction& tx;
140 crypto::hash hash;
141 uint64_t blob_size;
142 uint64_t weight;
143 uint64_t fee;
144 };
145
146 void toJsonValue(rapidjson::Writer<epee::byte_stream>& dest, const minimal_chain& self)
147 {
148 namespace adapt = boost::adaptors;
149
150 const auto to_block_id = [](const cryptonote::block& bl)
151 {
152 crypto::hash id;
153 if (!get_block_hash(bl, id))
154 MERROR("ZMQ/Pub failure: get_block_hash");
155 return id;
156 };
157
158 assert(!self.blocks.empty()); // checked in zmq_pub::send_chain_main
159
160 dest.StartObject();
161 INSERT_INTO_JSON_OBJECT(dest, first_height, self.height);
162 INSERT_INTO_JSON_OBJECT(dest, first_prev_id, self.blocks[0].prev_id);
163 INSERT_INTO_JSON_OBJECT(dest, ids, (self.blocks | adapt::transformed(to_block_id)));
164 dest.EndObject();
165 }
166
167 void toJsonValue(rapidjson::Writer<epee::byte_stream>& dest, const miner_data& self)
168 {
169 dest.StartObject();
170 INSERT_INTO_JSON_OBJECT(dest, major_version, self.major_version);
171 INSERT_INTO_JSON_OBJECT(dest, height, self.height);
172 INSERT_INTO_JSON_OBJECT(dest, prev_id, self.prev_id);
173 INSERT_INTO_JSON_OBJECT(dest, seed_hash, self.seed_hash);
174 INSERT_INTO_JSON_OBJECT(dest, difficulty, cryptonote::hex(self.diff));
175 INSERT_INTO_JSON_OBJECT(dest, median_weight, self.median_weight);
176 INSERT_INTO_JSON_OBJECT(dest, already_generated_coins, self.already_generated_coins);
177 INSERT_INTO_JSON_OBJECT(dest, tx_backlog, self.tx_backlog);
178 dest.EndObject();
179 }
180
181 void toJsonValue(rapidjson::Writer<epee::byte_stream>& dest, const minimal_txpool& self)
182 {
183 dest.StartObject();
184 INSERT_INTO_JSON_OBJECT(dest, id, self.hash);
185 INSERT_INTO_JSON_OBJECT(dest, blob_size, self.blob_size);
186 INSERT_INTO_JSON_OBJECT(dest, weight, self.weight);
187 INSERT_INTO_JSON_OBJECT(dest, fee, self.fee);
188 dest.EndObject();
189 }
190
191 void json_full_chain(epee::byte_stream& buf, const std::uint64_t height, const epee::span<const cryptonote::block> blocks)
192 {
193 json_pub(buf, blocks);
194 }
195
196 void json_minimal_chain(epee::byte_stream& buf, const std::uint64_t height, const epee::span<const cryptonote::block> blocks)
197 {
198 json_pub(buf, minimal_chain{height, blocks});
199 }
200
201 void json_miner_data(epee::byte_stream& buf, uint8_t major_version, uint64_t height, const crypto::hash& prev_id, const crypto::hash& seed_hash, cryptonote::difficulty_type diff, uint64_t median_weight, uint64_t already_generated_coins, const std::vector<cryptonote::tx_block_template_backlog_entry>& tx_backlog)
202 {
203 json_pub(buf, miner_data{major_version, height, prev_id, seed_hash, diff, median_weight, already_generated_coins, tx_backlog});
204 }
205
206 // boost::adaptors are in place "views" - no copy/move takes place
207 // moving transactions (via sort, etc.), is expensive!
208
209 void json_full_txpool(epee::byte_stream& buf, epee::span<const cryptonote::txpool_event> txes)
210 {
211 namespace adapt = boost::adaptors;
212 const auto to_full_tx = [](const cryptonote::txpool_event& event)
213 {
214 return event.tx;
215 };
216 json_pub(buf, (txes | adapt::filtered(is_valid{}) | adapt::transformed(to_full_tx)));
217 }
218
219 void json_minimal_txpool(epee::byte_stream& buf, epee::span<const cryptonote::txpool_event> txes)
220 {
221 namespace adapt = boost::adaptors;
222 const auto to_minimal_tx = [](const cryptonote::txpool_event& event)
223 {
224 return minimal_txpool{event.tx, event.hash, event.blob_size, event.weight, cryptonote::get_tx_fee(event.tx)};
225 };
226 json_pub(buf, (txes | adapt::filtered(is_valid{}) | adapt::transformed(to_minimal_tx)));
227 }
228
229 constexpr const std::array<context<chain_writer>, 2> chain_contexts =
230 {{
231 {u8"json-full-chain_main", json_full_chain},
232 {u8"json-minimal-chain_main", json_minimal_chain}
233 }};
234
235 constexpr const std::array<context<miner_writer>, 1> miner_contexts =
236 {{
237 {u8"json-full-miner_data", json_miner_data},
238 }};
239
240 constexpr const std::array<context<txpool_writer>, 2> txpool_contexts =
241 {{
242 {u8"json-full-txpool_add", json_full_txpool},
243 {u8"json-minimal-txpool_add", json_minimal_txpool}
244 }};
245
246 template<typename T, std::size_t N>
247 epee::span<const context<T>> get_range(const std::array<context<T>, N>& contexts, const boost::string_ref value)
248 {
249 const auto not_prefix = [](const boost::string_ref lhs, const context<T>& rhs)
250 {
251 return !(boost::string_ref{rhs.name}.starts_with(lhs));
252 };
253
254 const auto lower = std::lower_bound(contexts.begin(), contexts.end(), value);
255 const auto upper = std::upper_bound(lower, contexts.end(), value, not_prefix);
256 return {lower, std::size_t(upper - lower)};
257 }
258
259 template<std::size_t N, typename T>
260 void add_subscriptions(std::array<std::size_t, N>& subs, const epee::span<const context<T>> range, context<T> const* const first)
261 {
262 assert(range.size() <= N);
263 assert((unsigned long)(range.begin() - first) <= N - range.size());
264
265 for (const auto& ctx : range)
266 {
267 const std::size_t i = std::addressof(ctx) - first;
268 subs[i] = std::min(std::numeric_limits<std::size_t>::max() - 1, subs[i]) + 1;
269 }
270 }
271
272 template<std::size_t N, typename T>
273 void remove_subscriptions(std::array<std::size_t, N>& subs, const epee::span<const context<T>> range, context<T> const* const first)
274 {
275 assert(range.size() <= N);
276 assert((unsigned long)(range.begin() - first) <= N - range.size());
277
278 for (const auto& ctx : range)
279 {
280 const std::size_t i = std::addressof(ctx) - first;
281 subs[i] = std::max(std::size_t(1), subs[i]) - 1;
282 }
283 }
284
285 template<std::size_t N, typename T, typename... U>
286 std::array<epee::byte_slice, N> make_pubs(const std::array<std::size_t, N>& subs, const std::array<context<T>, N>& contexts, U&&... args)
287 {
288 epee::byte_stream buf{};
289
290 std::size_t last_offset = 0;
291 std::array<std::size_t, N> offsets{{}};
292 for (std::size_t i = 0; i < N; ++i)
293 {
294 if (subs[i])
295 {
296 write_header(buf, contexts[i].name);
297 contexts[i].generate_pub(buf, std::forward<U>(args)...);
298 offsets[i] = buf.size() - last_offset;
299 last_offset = buf.size();
300 }
301 }
302
303 epee::byte_slice bytes{std::move(buf)};
304 std::array<epee::byte_slice, N> out;
305 for (std::size_t i = 0; i < N; ++i)
306 out[i] = bytes.take_slice(offsets[i]);
307
308 return out;
309 }
310
311 template<std::size_t N>
312 std::size_t send_messages(void* const socket, std::array<epee::byte_slice, N>& messages)
313 {
314 std::size_t count = 0;
315 for (epee::byte_slice& message : messages)
316 {
317 if (!message.empty())
318 {
319 const expect<void> sent = net::zmq::send(std::move(message), socket, ZMQ_DONTWAIT);
320 if (!sent)
321 MERROR("Failed to send ZMQ/Pub message: " << sent.error().message());
322 else
323 ++count;
324 }
325 }
326 return count;
327 }
328
329 expect<bool> relay_block_pub(void* const relay, void* const pub) noexcept
330 {
331 zmq_msg_t msg;
332 zmq_msg_init(std::addressof(msg));
333 MONERO_CHECK(net::zmq::retry_op(zmq_msg_recv, std::addressof(msg), relay, ZMQ_DONTWAIT));
334
335 const boost::string_ref payload{
336 reinterpret_cast<const char*>(zmq_msg_data(std::addressof(msg))),
337 zmq_msg_size(std::addressof(msg))
338 };
339
340 if (payload == txpool_signal)
341 {
342 zmq_msg_close(std::addressof(msg));
343 return false;
344 }
345
346 // forward block messages (serialized on P2P thread for now)
347 const expect<void> sent = net::zmq::retry_op(zmq_msg_send, std::addressof(msg), pub, ZMQ_DONTWAIT);
348 if (!sent)
349 {
350 zmq_msg_close(std::addressof(msg));
351 return sent.error();
352 }
353 return true;
354 }
355 } // anonymous
356
357 namespace cryptonote { namespace listener
358 {
359
360 zmq_pub::zmq_pub(void* context)
361 : relay_(),
362 chain_subs_{{0}},
363 miner_subs_{{0}},
364 txpool_subs_{{0}},
365 sync_()
366 {
367 if (!context)
368 throw std::logic_error{"ZMQ context cannot be NULL"};
369
370 verify_sorted(chain_contexts, "chain_contexts");
371 verify_sorted(miner_contexts, "miner_contexts");
372 verify_sorted(txpool_contexts, "txpool_contexts");
373
374 relay_.reset(zmq_socket(context, ZMQ_PAIR));
375 if (!relay_)
376 MONERO_ZMQ_THROW("Failed to create relay socket");
377 if (zmq_connect(relay_.get(), relay_endpoint()) != 0)
378 MONERO_ZMQ_THROW("Failed to connect relay socket");
379 }
380
381 zmq_pub::~zmq_pub()
382 {}
383
384 bool zmq_pub::sub_request(boost::string_ref message)
385 {
386 if (!message.empty())
387 {
388 const char tag = message[0];
389 message.remove_prefix(1);
390
391 const auto chain_range = get_range(chain_contexts, message);
392 const auto miner_range = get_range(miner_contexts, message);
393 const auto txpool_range = get_range(txpool_contexts, message);
394
395 if (!chain_range.empty() || !miner_range.empty() || !txpool_range.empty())
396 {
397 MDEBUG("Client " << (tag ? "subscribed" : "unsubscribed") << " to " <<
398 chain_range.size() << " chain topic(s), " << miner_range.size() << " miner topic(s) and " << txpool_range.size() << " txpool topic(s)");
399
400 const boost::lock_guard<boost::mutex> lock{sync_};
401 switch (tag)
402 {
403 case 0:
404 remove_subscriptions(chain_subs_, chain_range, chain_contexts.begin());
405 remove_subscriptions(miner_subs_, miner_range, miner_contexts.begin());
406 remove_subscriptions(txpool_subs_, txpool_range, txpool_contexts.begin());
407 return true;
408 case 1:
409 add_subscriptions(chain_subs_, chain_range, chain_contexts.begin());
410 add_subscriptions(miner_subs_, miner_range, miner_contexts.begin());
411 add_subscriptions(txpool_subs_, txpool_range, txpool_contexts.begin());
412 return true;
413 default:
414 break;
415 }
416 }
417 }
418 MERROR("Invalid ZMQ/Sub message");
419 return false;
420 }
421
422 bool zmq_pub::relay_to_pub(void* const relay, void* const pub)
423 {
424 const expect<bool> relayed = relay_block_pub(relay, pub);
425 if (!relayed)
426 {
427 MERROR("Error relaying ZMQ/Pub: " << relayed.error().message());
428 return false;
429 }
430
431 if (!*relayed)
432 {
433 std::array<std::size_t, 2> subs;
434 std::vector<cryptonote::txpool_event> events;
435 {
436 const boost::lock_guard<boost::mutex> lock{sync_};
437 if (txes_.empty())
438 return false;
439
440 subs = txpool_subs_;
441 events = std::move(txes_.front());
442 txes_.pop_front();
443 }
444 auto messages = make_pubs(subs, txpool_contexts, epee::to_span(events));
445 send_messages(pub, messages);
446 MDEBUG("Sent txpool ZMQ/Pub");
447 }
448 else
449 MDEBUG("Sent chain_main ZMQ/Pub");
450
451 return true;
452 }
453
454 std::size_t zmq_pub::send_chain_main(const std::uint64_t height, const epee::span<const cryptonote::block> blocks)
455 {
456 if (blocks.empty())
457 return 0;
458
459 /* Block format only sends one block at a time - multiple block notifications
460 are less common and only occur on rollbacks. */
461
462 boost::unique_lock<boost::mutex> guard{sync_};
463
464 const auto subs_copy = chain_subs_;
465 guard.unlock();
466
467 for (const std::size_t sub : subs_copy)
468 {
469 if (sub)
470 {
471 /* cryptonote_core/blockchain.cpp cannot "give" us the block like core
472 does for txpool events. Since copying the block is expensive anyway,
473 serialization is done right here on the p2p thread (for now). */
474
475 auto messages = make_pubs(subs_copy, chain_contexts, height, blocks);
476 guard.lock();
477 return send_messages(relay_.get(), messages);
478 }
479 }
480 return 0;
481 }
482
483 std::size_t zmq_pub::send_miner_data(uint8_t major_version, uint64_t height, const crypto::hash& prev_id, const crypto::hash& seed_hash, difficulty_type diff, uint64_t median_weight, uint64_t already_generated_coins, const std::vector<tx_block_template_backlog_entry>& tx_backlog)
484 {
485 boost::unique_lock<boost::mutex> guard{sync_};
486
487 const auto subs_copy = miner_subs_;
488 guard.unlock();
489
490 for (const std::size_t sub : subs_copy)
491 {
492 if (sub)
493 {
494 auto messages = make_pubs(subs_copy, miner_contexts, major_version, height, prev_id, seed_hash, diff, median_weight, already_generated_coins, tx_backlog);
495 guard.lock();
496 return send_messages(relay_.get(), messages);
497 }
498 }
499 return 0;
500 }
501
502 std::size_t zmq_pub::send_txpool_add(std::vector<txpool_event> txes)
503 {
504 if (txes.empty())
505 return 0;
506
507 const boost::lock_guard<boost::mutex> lock{sync_};
508 for (const std::size_t sub : txpool_subs_)
509 {
510 if (sub)
511 {
512 const expect<void> sent = net::zmq::retry_op(zmq_send_const, relay_.get(), txpool_signal, sizeof(txpool_signal) - 1, ZMQ_DONTWAIT);
513 if (sent)
514 txes_.emplace_back(std::move(txes));
515 else
516 MERROR("ZMQ/Pub failure, relay queue error: " << sent.error().message());
517 return bool(sent);
518 }
519 }
520 return 0;
521 }
522
523 void zmq_pub::chain_main::operator()(const std::uint64_t height, epee::span<const cryptonote::block> blocks) const
524 {
525 const std::shared_ptr<zmq_pub> self = self_.lock();
526 if (self)
527 self->send_chain_main(height, blocks);
528 else
529 MERROR("Unable to send ZMQ/Pub - ZMQ server destroyed");
530 }
531
532 void zmq_pub::miner_data::operator()(uint8_t major_version, uint64_t height, const crypto::hash& prev_id, const crypto::hash& seed_hash, difficulty_type diff, uint64_t median_weight, uint64_t already_generated_coins, const std::vector<tx_block_template_backlog_entry>& tx_backlog) const
533 {
534 const std::shared_ptr<zmq_pub> self = self_.lock();
535 if (self)
536 self->send_miner_data(major_version, height, prev_id, seed_hash, diff, median_weight, already_generated_coins, tx_backlog);
537 else
538 MERROR("Unable to send ZMQ/Pub - ZMQ server destroyed");
539 }
540
541 void zmq_pub::txpool_add::operator()(std::vector<cryptonote::txpool_event> txes) const
542 {
543 const std::shared_ptr<zmq_pub> self = self_.lock();
544 if (self)
545 self->send_txpool_add(std::move(txes));
546 else
547 MERROR("Unable to send ZMQ/Pub - ZMQ server destroyed");
548 }
549
550 }}