Branch data Line data Source code
1 : : // Copyright (c) 2015-present The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <zmq/zmqpublishnotifier.h>
6 : :
7 : : #include <chain.h>
8 : : #include <crypto/common.h>
9 : : #include <logging.h>
10 : : #include <netaddress.h>
11 : : #include <netbase.h>
12 : : #include <primitives/transaction.h>
13 : : #include <serialize.h>
14 : : #include <streams.h>
15 : : #include <uint256.h>
16 : : #include <util/check.h>
17 : : #include <zmq/zmqutil.h>
18 : :
19 : : #include <zmq.h>
20 : :
21 : : #include <cstdarg>
22 : : #include <cstddef>
23 : : #include <cstdint>
24 : : #include <cstring>
25 : : #include <map>
26 : : #include <optional>
27 : : #include <span>
28 : : #include <string>
29 : : #include <utility>
30 : : #include <vector>
31 : :
32 : : static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
33 : :
34 : : static const char *MSG_HASHBLOCK = "hashblock";
35 : : static const char *MSG_HASHTX = "hashtx";
36 : : static const char *MSG_RAWBLOCK = "rawblock";
37 : : static const char *MSG_RAWTX = "rawtx";
38 : : static const char *MSG_SEQUENCE = "sequence";
39 : :
40 : : // Internal function to send multipart message
41 : 129 : static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
42 : : {
43 : 129 : va_list args;
44 : 129 : va_start(args, size);
45 : :
46 : 645 : while (1)
47 : : {
48 : 387 : zmq_msg_t msg;
49 : :
50 : 387 : int rc = zmq_msg_init_size(&msg, size);
51 [ - + ]: 387 : if (rc != 0)
52 : : {
53 [ # # ]: 0 : zmqError("Unable to initialize ZMQ msg");
54 : 0 : va_end(args);
55 : 0 : return -1;
56 : : }
57 : :
58 : 387 : void *buf = zmq_msg_data(&msg);
59 : 387 : memcpy(buf, data, size);
60 : :
61 : 387 : data = va_arg(args, const void*);
62 : :
63 [ + + ]: 516 : rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
64 [ - + ]: 387 : if (rc == -1)
65 : : {
66 [ # # ]: 0 : zmqError("Unable to send ZMQ msg");
67 : 0 : zmq_msg_close(&msg);
68 : 0 : va_end(args);
69 : 0 : return -1;
70 : : }
71 : :
72 : 387 : zmq_msg_close(&msg);
73 : :
74 [ + + ]: 387 : if (!data)
75 : : break;
76 : :
77 : 258 : size = va_arg(args, size_t);
78 : 258 : }
79 : 129 : va_end(args);
80 : 129 : return 0;
81 : : }
82 : :
83 : 9 : static bool IsZMQAddressIPV6(const std::string &zmq_address)
84 : : {
85 : 9 : const std::string tcp_prefix = "tcp://";
86 [ - + ]: 9 : const size_t tcp_index = zmq_address.rfind(tcp_prefix);
87 : 9 : const size_t colon_index = zmq_address.rfind(':');
88 [ + + ]: 9 : if (tcp_index == 0 && colon_index != std::string::npos) {
89 [ + - ]: 6 : const std::string ip = zmq_address.substr(tcp_prefix.length(), colon_index - tcp_prefix.length());
90 [ + - + - ]: 6 : const std::optional<CNetAddr> addr{LookupHost(ip, false)};
91 [ + - - + ]: 6 : if (addr.has_value() && addr.value().IsIPv6()) return true;
92 : 6 : }
93 : : return false;
94 : 9 : }
95 : :
96 : 16 : bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
97 : : {
98 [ - + ]: 16 : assert(!psocket);
99 : :
100 : : // check if address is being used by other publish notifier
101 : 16 : std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
102 : :
103 [ + + ]: 16 : if (i==mapPublishNotifiers.end())
104 : : {
105 : 9 : psocket = zmq_socket(pcontext, ZMQ_PUB);
106 [ - + ]: 9 : if (!psocket)
107 : : {
108 [ # # ]: 0 : zmqError("Failed to create socket");
109 : 0 : return false;
110 : : }
111 : :
112 [ + - ]: 9 : LogDebug(BCLog::ZMQ, "Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
113 : :
114 : 9 : int rc = zmq_setsockopt(psocket, ZMQ_SNDHWM, &outbound_message_high_water_mark, sizeof(outbound_message_high_water_mark));
115 [ - + ]: 9 : if (rc != 0)
116 : : {
117 [ # # ]: 0 : zmqError("Failed to set outbound message high water mark");
118 : 0 : zmq_close(psocket);
119 : 0 : return false;
120 : : }
121 : :
122 : 9 : const int so_keepalive_option {1};
123 : 9 : rc = zmq_setsockopt(psocket, ZMQ_TCP_KEEPALIVE, &so_keepalive_option, sizeof(so_keepalive_option));
124 [ - + ]: 9 : if (rc != 0) {
125 [ # # ]: 0 : zmqError("Failed to set SO_KEEPALIVE");
126 : 0 : zmq_close(psocket);
127 : 0 : return false;
128 : : }
129 : :
130 : : // On some systems (e.g. OpenBSD) the ZMQ_IPV6 must not be enabled, if the address to bind isn't IPv6
131 [ + - ]: 9 : const int enable_ipv6 { IsZMQAddressIPV6(address) ? 1 : 0};
132 : 9 : rc = zmq_setsockopt(psocket, ZMQ_IPV6, &enable_ipv6, sizeof(enable_ipv6));
133 [ - + ]: 9 : if (rc != 0) {
134 [ # # ]: 0 : zmqError("Failed to set ZMQ_IPV6");
135 : 0 : zmq_close(psocket);
136 : 0 : return false;
137 : : }
138 : :
139 : 9 : rc = zmq_bind(psocket, address.c_str());
140 [ + + ]: 9 : if (rc != 0)
141 : : {
142 [ + - ]: 2 : zmqError("Failed to bind address");
143 : 2 : zmq_close(psocket);
144 : 2 : return false;
145 : : }
146 : :
147 : : // register this notifier for the address, so it can be reused for other publish notifier
148 [ - + + - ]: 14 : mapPublishNotifiers.insert(std::make_pair(address, this));
149 : 7 : return true;
150 : : }
151 : : else
152 : : {
153 [ + - ]: 7 : LogDebug(BCLog::ZMQ, "Reusing socket for address %s\n", address);
154 [ + - ]: 7 : LogDebug(BCLog::ZMQ, "Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
155 : :
156 [ - + ]: 7 : psocket = i->second->psocket;
157 [ - + + - ]: 14 : mapPublishNotifiers.insert(std::make_pair(address, this));
158 : :
159 : 7 : return true;
160 : : }
161 : : }
162 : :
163 : 18 : void CZMQAbstractPublishNotifier::Shutdown()
164 : : {
165 : : // Early return if Initialize was not called
166 [ + + ]: 18 : if (!psocket) return;
167 : :
168 : 16 : int count = mapPublishNotifiers.count(address);
169 : :
170 : : // remove this notifier from the list of publishers using this address
171 : 16 : typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
172 : 16 : std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
173 : :
174 [ + + ]: 16 : for (iterator it = iterpair.first; it != iterpair.second; ++it)
175 : : {
176 [ + - ]: 14 : if (it->second==this)
177 : : {
178 : 14 : mapPublishNotifiers.erase(it);
179 : 14 : break;
180 : : }
181 : : }
182 : :
183 [ + + ]: 16 : if (count == 1)
184 : : {
185 [ + - ]: 7 : LogDebug(BCLog::ZMQ, "Close socket at address %s\n", address);
186 : 7 : int linger = 0;
187 : 7 : zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
188 : 7 : zmq_close(psocket);
189 : : }
190 : :
191 : 16 : psocket = nullptr;
192 : : }
193 : :
194 : 129 : bool CZMQAbstractPublishNotifier::SendZmqMessage(const char *command, const void* data, size_t size)
195 : : {
196 [ - + ]: 129 : assert(psocket);
197 : :
198 : : /* send three parts, command & data & a LE 4byte sequence number */
199 : 129 : unsigned char msgseq[sizeof(uint32_t)];
200 : 129 : WriteLE32(msgseq, nSequence);
201 : 129 : int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
202 [ + - ]: 129 : if (rc == -1)
203 : : return false;
204 : :
205 : : /* increment memory only sequence number after sending */
206 : 129 : nSequence++;
207 : :
208 : 129 : return true;
209 : : }
210 : :
211 : 23 : bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
212 : : {
213 : 23 : uint256 hash = pindex->GetBlockHash();
214 [ + - + - ]: 46 : LogDebug(BCLog::ZMQ, "Publish hashblock %s to %s\n", hash.GetHex(), this->address);
215 : : uint8_t data[32];
216 [ + + ]: 759 : for (unsigned int i = 0; i < 32; i++) {
217 : 736 : data[31 - i] = hash.begin()[i];
218 : : }
219 : 23 : return SendZmqMessage(MSG_HASHBLOCK, data, 32);
220 : : }
221 : :
222 : 32 : bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
223 : : {
224 : 32 : uint256 hash = transaction.GetHash().ToUint256();
225 [ + - + - ]: 64 : LogDebug(BCLog::ZMQ, "Publish hashtx %s to %s\n", hash.GetHex(), this->address);
226 : : uint8_t data[32];
227 [ + + ]: 1056 : for (unsigned int i = 0; i < 32; i++) {
228 : 1024 : data[31 - i] = hash.begin()[i];
229 : : }
230 : 32 : return SendZmqMessage(MSG_HASHTX, data, 32);
231 : : }
232 : :
233 : 14 : bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
234 : : {
235 [ + - + - ]: 28 : LogDebug(BCLog::ZMQ, "Publish rawblock %s to %s\n", pindex->GetBlockHash().GetHex(), this->address);
236 : :
237 : 14 : std::vector<std::byte> block{};
238 [ + - - + ]: 14 : if (!m_get_block_by_index(block, *pindex)) {
239 [ # # # # ]: 0 : zmqError("Can't read block from disk");
240 : 0 : return false;
241 : : }
242 : :
243 [ - + + - ]: 14 : return SendZmqMessage(MSG_RAWBLOCK, block.data(), block.size());
244 : 14 : }
245 : :
246 : 18 : bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
247 : : {
248 : 18 : uint256 hash = transaction.GetHash().ToUint256();
249 [ + - + - ]: 36 : LogDebug(BCLog::ZMQ, "Publish rawtx %s to %s\n", hash.GetHex(), this->address);
250 : 18 : DataStream ss;
251 [ + - ]: 18 : ss << TX_WITH_WITNESS(transaction);
252 [ - + + - ]: 18 : return SendZmqMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
253 : 18 : }
254 : :
255 : : // Helper function to send a 'sequence' topic message with the following structure:
256 : : // <32-byte hash> | <1-byte label> | <8-byte LE sequence> (optional)
257 : 42 : static bool SendSequenceMsg(CZMQAbstractPublishNotifier& notifier, uint256 hash, char label, std::optional<uint64_t> sequence = {})
258 : : {
259 : 42 : unsigned char data[sizeof(hash) + sizeof(label) + sizeof(uint64_t)];
260 [ + + ]: 1386 : for (unsigned int i = 0; i < sizeof(hash); ++i) {
261 : 1344 : data[sizeof(hash) - 1 - i] = hash.begin()[i];
262 : : }
263 : 42 : data[sizeof(hash)] = label;
264 [ + + ]: 42 : if (sequence) WriteLE64(data + sizeof(hash) + sizeof(label), *sequence);
265 [ + + ]: 56 : return notifier.SendZmqMessage(MSG_SEQUENCE, data, sequence ? sizeof(data) : sizeof(hash) + sizeof(label));
266 : : }
267 : :
268 : 12 : bool CZMQPublishSequenceNotifier::NotifyBlockConnect(const CBlockIndex *pindex)
269 : : {
270 : 12 : uint256 hash = pindex->GetBlockHash();
271 [ + - + - ]: 24 : LogDebug(BCLog::ZMQ, "Publish sequence block connect %s to %s\n", hash.GetHex(), this->address);
272 : 12 : return SendSequenceMsg(*this, hash, /* Block (C)onnect */ 'C');
273 : : }
274 : :
275 : 2 : bool CZMQPublishSequenceNotifier::NotifyBlockDisconnect(const CBlockIndex *pindex)
276 : : {
277 : 2 : uint256 hash = pindex->GetBlockHash();
278 [ + - + - ]: 4 : LogDebug(BCLog::ZMQ, "Publish sequence block disconnect %s to %s\n", hash.GetHex(), this->address);
279 : 2 : return SendSequenceMsg(*this, hash, /* Block (D)isconnect */ 'D');
280 : : }
281 : :
282 : 24 : bool CZMQPublishSequenceNotifier::NotifyTransactionAcceptance(const CTransaction &transaction, uint64_t mempool_sequence)
283 : : {
284 : 24 : uint256 hash = transaction.GetHash().ToUint256();
285 [ + - + - ]: 48 : LogDebug(BCLog::ZMQ, "Publish hashtx mempool acceptance %s to %s\n", hash.GetHex(), this->address);
286 : 24 : return SendSequenceMsg(*this, hash, /* Mempool (A)cceptance */ 'A', mempool_sequence);
287 : : }
288 : :
289 : 4 : bool CZMQPublishSequenceNotifier::NotifyTransactionRemoval(const CTransaction &transaction, uint64_t mempool_sequence)
290 : : {
291 : 4 : uint256 hash = transaction.GetHash().ToUint256();
292 [ + - + - ]: 8 : LogDebug(BCLog::ZMQ, "Publish hashtx mempool removal %s to %s\n", hash.GetHex(), this->address);
293 : 4 : return SendSequenceMsg(*this, hash, /* Mempool (R)emoval */ 'R', mempool_sequence);
294 : : }
|