| 1 | // Copyright (c) 2019-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | |
| 29 | #include "levin_notify.h" |
| 30 | |
| 31 | #include <boost/asio/dispatch.hpp> |
| 32 | #include <boost/asio/post.hpp> |
| 33 | #include <boost/asio/steady_timer.hpp> |
| 34 | #include <boost/system/system_error.hpp> |
| 35 | #include <boost/uuid/uuid_io.hpp> |
| 36 | #include <chrono> |
| 37 | #include <deque> |
| 38 | #include <stdexcept> |
| 39 | #include <utility> |
| 40 | |
| 41 | #include "byte_slice.h" |
| 42 | #include "common/expect.h" |
| 43 | #include "common/varint.h" |
| 44 | #include "cryptonote_config.h" |
| 45 | #include "crypto/crypto.h" |
| 46 | #include "crypto/duration.h" |
| 47 | #include "cryptonote_basic/connection_context.h" |
| 48 | #include "cryptonote_core/i_core_events.h" |
| 49 | #include "cryptonote_protocol/cryptonote_protocol_defs.h" |
| 50 | #include "net/dandelionpp.h" |
| 51 | #include "p2p/net_node.h" |
| 52 | |
| 53 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 54 | #define MONERO_DEFAULT_LOG_CATEGORY "net.p2p.tx" |
| 55 | |
| 56 | namespace cryptonote |
| 57 | { |
| 58 | namespace levin |
| 59 | { |
| 60 | namespace |
| 61 | { |
| 62 | constexpr const std::size_t connection_id_reserve_size = 100; |
| 63 | |
| 64 | constexpr const std::chrono::minutes noise_min_epoch{CRYPTONOTE_NOISE_MIN_EPOCH}; |
| 65 | constexpr const std::chrono::seconds noise_epoch_range{CRYPTONOTE_NOISE_EPOCH_RANGE}; |
| 66 | |
| 67 | constexpr const std::chrono::minutes dandelionpp_min_epoch{CRYPTONOTE_DANDELIONPP_MIN_EPOCH}; |
| 68 | constexpr const std::chrono::seconds dandelionpp_epoch_range{CRYPTONOTE_DANDELIONPP_EPOCH_RANGE}; |
| 69 | |
| 70 | constexpr const std::chrono::seconds noise_min_delay{CRYPTONOTE_NOISE_MIN_DELAY}; |
| 71 | constexpr const std::chrono::seconds noise_delay_range{CRYPTONOTE_NOISE_DELAY_RANGE}; |
| 72 | |
| 73 | /* A custom duration is used for the poisson distribution because of the |
| 74 | variance. If 5 seconds is given to `std::poisson_distribution`, 95% of |
| 75 | the values fall between 1-9s in 1s increments (not granular enough). If |
| 76 | 5000 milliseconds is given, 95% of the values fall between 4859ms-5141ms |
| 77 | in 1ms increments (not enough time variance). Providing 20 quarter |
| 78 | seconds yields 95% of the values between 3s-7.25s in 1/4s increments. */ |
| 79 | using fluff_stepsize = std::chrono::duration<std::chrono::milliseconds::rep, std::ratio<1, 4>>; |
| 80 | constexpr const std::chrono::seconds fluff_average_in{CRYPTONOTE_DANDELIONPP_FLUSH_AVERAGE}; |
| 81 | |
| 82 | /*! Bitcoin Core is using 1/2 average seconds for outgoing connections |
| 83 | compared to incoming. The thinking is that the user controls outgoing |
| 84 | connections (Dandelion++ makes similar assumptions in its stem |
| 85 | algorithm). The randomization yields 95% values between 1s-4s in |
| 86 | 1/4s increments. */ |
| 87 | using fluff_duration = crypto::random_poisson_subseconds::result_type; |
| 88 | constexpr const fluff_duration fluff_average_out{fluff_duration{fluff_average_in} / 2}; |
| 89 | |
| 90 | /*! Select a randomized duration from 0 to `range`. The precision will be to |
| 91 | the systems `steady_clock`. As an example, supplying 3 seconds to this |
| 92 | function will select a duration from [0, 3] seconds, and the increments |
| 93 | for the selection will be determined by the `steady_clock` precision |
| 94 | (typically nanoseconds). |
| 95 | |
| 96 | \return A randomized duration from 0 to `range`. */ |
| 97 | std::chrono::steady_clock::duration random_duration(std::chrono::steady_clock::duration range) |
| 98 | { |
| 99 | using rep = std::chrono::steady_clock::rep; |
| 100 | return std::chrono::steady_clock::duration{crypto::rand_range(rep(0), range.count())}; |
| 101 | } |
| 102 | |
| 103 | uint64_t get_median_remote_height(connections& p2p) |
| 104 | { |
| 105 | std::vector<uint64_t> remote_heights; |
| 106 | remote_heights.reserve(connection_id_reserve_size); |
| 107 | p2p.foreach_connection([&remote_heights] (detail::p2p_context& context) { |
| 108 | if (!context.m_is_income) |
| 109 | { |
| 110 | remote_heights.emplace_back(context.m_remote_blockchain_height); |
| 111 | } |
| 112 | return true; |
| 113 | }); |
| 114 | |
| 115 | if (remote_heights.empty()) |
| 116 | { |
| 117 | return 0; |
| 118 | } |
| 119 | |
| 120 | const size_t n = remote_heights.size() / 2; |
| 121 | std::sort(remote_heights.begin(), remote_heights.end()); |
| 122 | if (remote_heights.size() % 2 != 0) |
| 123 | { |
| 124 | return remote_heights[n]; |
| 125 | } |
| 126 | return remote_heights[n-1]; |
| 127 | } |
| 128 | |
| 129 | uint64_t get_blockchain_height(connections& p2p, const i_core_events* core) |
| 130 | { |
| 131 | const uint64_t local_blockchain_height = core->get_current_blockchain_height(); |
| 132 | if (core->is_synchronized()) |
| 133 | { |
| 134 | return local_blockchain_height; |
| 135 | } |
| 136 | return std::max(local_blockchain_height, get_median_remote_height(p2p)); |
| 137 | } |
| 138 | |
| 139 | //! \return Outgoing connections supporting fragments in `connections` filtered by blockchain height. |
| 140 | std::vector<boost::uuids::uuid> get_out_connections(connections& p2p, uint64_t blockchain_height) |
| 141 | { |
| 142 | std::vector<boost::uuids::uuid> outs; |
| 143 | outs.reserve(connection_id_reserve_size); |
| 144 | |
| 145 | /* The foreach call is serialized with a lock, but should be quick due to |
| 146 | the reserve call so a strand is not used. Investigate if there is lots |
| 147 | of waiting in here. */ |
| 148 | |
| 149 | p2p.foreach_connection([&outs, blockchain_height] (detail::p2p_context& context) { |
| 150 | if (!context.m_is_income && context.m_remote_blockchain_height >= blockchain_height) |
| 151 | outs.emplace_back(context.m_connection_id); |
| 152 | return true; |
| 153 | }); |
| 154 | |
| 155 | MDEBUG("Found " << outs.size() << " out connections having height >= " << blockchain_height); |
| 156 | return outs; |
| 157 | } |
| 158 | |
| 159 | std::vector<boost::uuids::uuid> get_out_connections(connections& p2p, const i_core_events* core) |
| 160 | { |
| 161 | return get_out_connections(p2p, get_blockchain_height(p2p, core)); |
| 162 | } |
| 163 | |
| 164 | epee::levin::message_writer make_tx_message(std::vector<blobdata>&& txs, const bool pad, const bool fluff) |
| 165 | { |
| 166 | NOTIFY_NEW_TRANSACTIONS::request request{}; |
| 167 | request.txs = std::move(txs); |
| 168 | request.dandelionpp_fluff = fluff; |
| 169 | |
| 170 | if (pad) |
| 171 | { |
| 172 | size_t bytes = 9 /* header */ + 4 /* 1 + 'txs' */ + tools::get_varint_data(request.txs.size()).size(); |
| 173 | for(auto tx_blob_it = request.txs.begin(); tx_blob_it!=request.txs.end(); ++tx_blob_it) |
| 174 | bytes += tools::get_varint_data(tx_blob_it->size()).size() + tx_blob_it->size(); |
| 175 | |
| 176 | // stuff some dummy bytes in to stay safe from traffic volume analysis |
| 177 | static constexpr const size_t granularity = 1024; |
| 178 | size_t padding = granularity - bytes % granularity; |
| 179 | const size_t overhead = 2 /* 1 + '_' */ + tools::get_varint_data(padding).size(); |
| 180 | if (overhead > padding) |
| 181 | padding = 0; |
| 182 | else |
| 183 | padding -= overhead; |
| 184 | request._ = std::string(padding, ' '); |
| 185 | |
| 186 | epee::byte_slice arg_buff; |
| 187 | epee::serialization::store_t_to_binary(request, arg_buff); |
| 188 | |
| 189 | // we probably lowballed the payload size a bit, so added a but too much. Fix this now. |
| 190 | size_t remove = arg_buff.size() % granularity; |
| 191 | if (remove > request._.size()) |
| 192 | request._.clear(); |
| 193 | else |
| 194 | request._.resize(request._.size() - remove); |
| 195 | // if the size of _ moved enough, we might lose byte in size encoding, we don't care |
| 196 | } |
| 197 | |
| 198 | epee::levin::message_writer out; |
| 199 | if (!epee::serialization::store_t_to_binary(request, out.buffer)) |
| 200 | throw std::runtime_error{"Failed to serialize to epee binary format"}; |
| 201 | |
| 202 | return out; |
| 203 | } |
| 204 | |
| 205 | bool make_payload_send_txs(connections& p2p, std::vector<blobdata>&& txs, const boost::uuids::uuid& destination, const bool pad, const bool fluff) |
| 206 | { |
| 207 | epee::byte_slice blob = make_tx_message(std::move(txs), pad, fluff).finalize_notify(NOTIFY_NEW_TRANSACTIONS::ID); |
| 208 | return p2p.send(std::move(blob), destination); |
| 209 | } |
| 210 | |
| 211 | /* The current design uses `asio::strand`s. The documentation isn't as clear |
| 212 | as it should be - a `strand` has an internal `mutex` and `bool`. The |
| 213 | `mutex` synchronizes thread access and the `bool` is set when a thread is |
| 214 | executing something "in the strand". Therefore, if a callback has lots of |
| 215 | work to do in a `strand`, asio can switch to some other task instead of |
| 216 | blocking 1+ threads to wait for the original thread to complete the task |
| 217 | (as is the case when client code has a `mutex` inside the callback). The |
| 218 | downside is that asio _always_ allocates for the callback, even if it can |
| 219 | be immediately executed. So if all work in a strand is minimal, a lock |
| 220 | may be better. |
| 221 | |
| 222 | This code uses a strand per "zone" and a strand per "channel in a zone". |
| 223 | `dispatch` is used heavily, which means "execute immediately in _this_ |
| 224 | thread if the strand is not in use, otherwise queue the callback to be |
| 225 | executed immediately after the strand completes its current task". |
| 226 | `post` is used where deferred execution to an `asio::io_context::run` |
| 227 | thread is preferred. |
| 228 | |
| 229 | The strand per "zone" is useful because the levin |
| 230 | `foreach_connection` is blocked with a mutex anyway. So this primarily |
| 231 | helps with reducing blocking of a thread attempting a "flood" |
| 232 | notification. Updating/merging the outgoing connections in the |
| 233 | Dandelion++ map is also somewhat expensive. |
| 234 | |
| 235 | The strand per "channel" may need a re-visit. The most "expensive" code |
| 236 | is figuring out the noise/notification to send. If levin code is |
| 237 | optimized further, it might be better to just use standard locks per |
| 238 | channel. */ |
| 239 | |
| 240 | //! A queue of levin messages for a noise i2p/tor link |
| 241 | struct noise_channel |
| 242 | { |
| 243 | explicit noise_channel(boost::asio::io_context& io_service) |
| 244 | : active(nullptr), |
| 245 | queue(), |
| 246 | strand(io_service), |
| 247 | next_noise(io_service), |
| 248 | connection(boost::uuids::nil_uuid()) |
| 249 | {} |
| 250 | |
| 251 | // `asio::io_context::strand` cannot be copied or moved |
| 252 | noise_channel(const noise_channel&) = delete; |
| 253 | noise_channel& operator=(const noise_channel&) = delete; |
| 254 | |
| 255 | // Only read/write these values "inside the strand" |
| 256 | |
| 257 | epee::byte_slice active; |
| 258 | std::deque<epee::byte_slice> queue; |
| 259 | boost::asio::io_context::strand strand; |
| 260 | boost::asio::steady_timer next_noise; |
| 261 | boost::uuids::uuid connection; |
| 262 | }; |
| 263 | } // anonymous |
| 264 | |
| 265 | namespace detail |
| 266 | { |
| 267 | struct zone |
| 268 | { |
| 269 | explicit zone(boost::asio::io_context& io_service, std::shared_ptr<connections> p2p, epee::byte_slice noise_in, epee::net_utils::zone zone, bool pad_txs) |
| 270 | : p2p(std::move(p2p)), |
| 271 | noise(std::move(noise_in)), |
| 272 | next_epoch(io_service), |
| 273 | flush_txs(io_service), |
| 274 | strand(io_service), |
| 275 | map(), |
| 276 | channels(), |
| 277 | connection_count(0), |
| 278 | flush_callbacks(0), |
| 279 | nzone(zone), |
| 280 | pad_txs(pad_txs), |
| 281 | fluffing(false) |
| 282 | { |
| 283 | for (std::size_t count = 0; !noise.empty() && count < CRYPTONOTE_NOISE_CHANNELS; ++count) |
| 284 | channels.emplace_back(io_service); |
| 285 | } |
| 286 | |
| 287 | const std::shared_ptr<connections> p2p; |
| 288 | const epee::byte_slice noise; //!< `!empty()` means zone is using noise channels |
| 289 | boost::asio::steady_timer next_epoch; |
| 290 | boost::asio::steady_timer flush_txs; |
| 291 | boost::asio::io_context::strand strand; |
| 292 | struct context_t { |
| 293 | std::vector<cryptonote::blobdata> fluff_txs; |
| 294 | std::chrono::steady_clock::time_point flush_time; |
| 295 | bool m_is_income; |
| 296 | }; |
| 297 | boost::unordered_map<boost::uuids::uuid, context_t> contexts; |
| 298 | net::dandelionpp::connection_map map;//!< Tracks outgoing uuid's for noise channels or Dandelion++ stems |
| 299 | std::deque<noise_channel> channels; //!< Never touch after init; only update elements on `noise_channel.strand` |
| 300 | std::atomic<std::size_t> connection_count; //!< Only update in strand, can be read at any time |
| 301 | std::uint32_t flush_callbacks; //!< Number of active fluff flush callbacks queued |
| 302 | const epee::net_utils::zone nzone; //!< Zone is public ipv4/ipv6 connections, or i2p or tor |
| 303 | const bool pad_txs; //!< Pad txs to the next boundary for privacy |
| 304 | bool fluffing; //!< Zone is in Dandelion++ fluff epoch |
| 305 | }; |
| 306 | } // detail |
| 307 | |
| 308 | namespace |
| 309 | { |
| 310 | //! Adds a message to the sending queue of the channel. |
| 311 | class queue_covert_notify |
| 312 | { |
| 313 | std::shared_ptr<detail::zone> zone_; |
| 314 | epee::byte_slice message_; // Requires manual copy constructor |
| 315 | const std::size_t destination_; |
| 316 | |
| 317 | public: |
| 318 | queue_covert_notify(std::shared_ptr<detail::zone> zone, epee::byte_slice message, std::size_t destination) |
| 319 | : zone_(std::move(zone)), message_(std::move(message)), destination_(destination) |
| 320 | {} |
| 321 | |
| 322 | queue_covert_notify(queue_covert_notify&&) = default; |
| 323 | queue_covert_notify(const queue_covert_notify& source) |
| 324 | : zone_(source.zone_), message_(source.message_.clone()), destination_(source.destination_) |
| 325 | {} |
| 326 | |
| 327 | //! \pre Called within `zone_->channels[destionation_].strand`. |
| 328 | void operator()() |
| 329 | { |
| 330 | if (!zone_) |
| 331 | return; |
| 332 | |
| 333 | noise_channel& channel = zone_->channels.at(destination_); |
| 334 | assert(channel.strand.running_in_this_thread()); |
| 335 | |
| 336 | if (!channel.connection.is_nil()) |
| 337 | channel.queue.push_back(std::move(message_)); |
| 338 | else if (destination_ == 0 && zone_->connection_count == 0) |
| 339 | MWARNING("Unable to send transaction(s) to " << epee::net_utils::zone_to_string(zone_->nzone) << |
| 340 | " - no available outbound connections"); |
| 341 | } |
| 342 | }; |
| 343 | |
| 344 | //! Sends txs on connections with expired timers, and queues callback for next timer expiration (if any). |
| 345 | struct fluff_flush |
| 346 | { |
| 347 | std::shared_ptr<detail::zone> zone_; |
| 348 | |
| 349 | static void queue(std::shared_ptr<detail::zone> zone, const std::chrono::steady_clock::time_point flush_time) |
| 350 | { |
| 351 | assert(zone != nullptr); |
| 352 | assert(zone->strand.running_in_this_thread()); |
| 353 | |
| 354 | detail::zone& this_zone = *zone; |
| 355 | ++this_zone.flush_callbacks; |
| 356 | this_zone.flush_txs.expires_at(flush_time); |
| 357 | this_zone.flush_txs.async_wait(this_zone.strand.wrap(fluff_flush{std::move(zone)})); |
| 358 | } |
| 359 | |
| 360 | void operator()(const boost::system::error_code error) |
| 361 | { |
| 362 | if (!zone_ || !zone_->flush_callbacks || --zone_->flush_callbacks || !zone_->p2p) |
| 363 | return; |
| 364 | |
| 365 | assert(zone_->strand.running_in_this_thread()); |
| 366 | |
| 367 | const bool timer_error = bool(error); |
| 368 | if (timer_error && error != boost::system::errc::operation_canceled) |
| 369 | throw boost::system::system_error{error, "fluff_flush timer failed"}; |
| 370 | |
| 371 | const auto now = std::chrono::steady_clock::now(); |
| 372 | auto next_flush = std::chrono::steady_clock::time_point::max(); |
| 373 | std::vector<std::pair<std::vector<blobdata>, boost::uuids::uuid>> connections{}; |
| 374 | for (auto &e: zone_->contexts) |
| 375 | { |
| 376 | auto &id = e.first; |
| 377 | auto &context = e.second; |
| 378 | if (!context.fluff_txs.empty()) |
| 379 | { |
| 380 | if (context.flush_time <= now || timer_error) // flush on canceled timer |
| 381 | { |
| 382 | context.flush_time = std::chrono::steady_clock::time_point::max(); |
| 383 | connections.emplace_back(std::move(context.fluff_txs), id); |
| 384 | context.fluff_txs.clear(); |
| 385 | } |
| 386 | else // not flushing yet |
| 387 | next_flush = std::min(next_flush, context.flush_time); |
| 388 | } |
| 389 | else // nothing to flush |
| 390 | context.flush_time = std::chrono::steady_clock::time_point::max(); |
| 391 | } |
| 392 | |
| 393 | /* Always send with `fluff` flag, even over i2p/tor. The hidden service |
| 394 | will disable the forwarding delay and immediately fluff. The i2p/tor |
| 395 | network is therefore replacing the sybil protection of Dandelion++. |
| 396 | Dandelion++ stem phase over i2p/tor is also worth investigating |
| 397 | (with/without "noise"?). */ |
| 398 | for (auto& connection : connections) |
| 399 | { |
| 400 | std::sort(connection.first.begin(), connection.first.end()); // don't leak receive order |
| 401 | connection.first.erase(std::unique(connection.first.begin(), connection.first.end()), |
| 402 | connection.first.end()); |
| 403 | make_payload_send_txs(*zone_->p2p, std::move(connection.first), connection.second, zone_->pad_txs, true); |
| 404 | } |
| 405 | |
| 406 | if (next_flush != std::chrono::steady_clock::time_point::max()) |
| 407 | fluff_flush::queue(std::move(zone_), next_flush); |
| 408 | } |
| 409 | }; |
| 410 | |
| 411 | /*! The "fluff" portion of the Dandelion++ algorithm. Every tx is queued |
| 412 | per-connection and flushed with a randomized poisson timer. This |
| 413 | implementation only has one system timer per-zone, and instead tracks |
| 414 | the lowest flush time. */ |
| 415 | struct fluff_notify |
| 416 | { |
| 417 | std::shared_ptr<detail::zone> zone_; |
| 418 | std::vector<blobdata> txs_; |
| 419 | boost::uuids::uuid source_; |
| 420 | |
| 421 | void operator()() |
| 422 | { |
| 423 | run(std::move(zone_), epee::to_span(txs_), source_); |
| 424 | } |
| 425 | |
| 426 | static void run(std::shared_ptr<detail::zone> zone, epee::span<const blobdata> txs, const boost::uuids::uuid& source) |
| 427 | { |
| 428 | if (!zone || !zone->p2p || txs.empty()) |
| 429 | return; |
| 430 | |
| 431 | assert(zone->strand.running_in_this_thread()); |
| 432 | |
| 433 | const auto now = std::chrono::steady_clock::now(); |
| 434 | auto next_flush = std::chrono::steady_clock::time_point::max(); |
| 435 | |
| 436 | crypto::random_poisson_subseconds in_duration(fluff_average_in); |
| 437 | crypto::random_poisson_subseconds out_duration(fluff_average_out); |
| 438 | |
| 439 | |
| 440 | MDEBUG("Queueing " << txs.size() << " transaction(s) for Dandelion++ fluffing"); |
| 441 | for (auto &e: zone->contexts) |
| 442 | { |
| 443 | auto &id = e.first; |
| 444 | auto &context = e.second; |
| 445 | // When i2p/tor, only fluff to outbound connections |
| 446 | if (source != id && (zone->nzone == epee::net_utils::zone::public_ || !context.m_is_income)) |
| 447 | { |
| 448 | if (context.fluff_txs.empty()) |
| 449 | context.flush_time = now + (context.m_is_income ? in_duration() : out_duration()); |
| 450 | |
| 451 | next_flush = std::min(next_flush, context.flush_time); |
| 452 | context.fluff_txs.reserve(context.fluff_txs.size() + txs.size()); |
| 453 | context.fluff_txs.insert(context.fluff_txs.end(), txs.begin(), txs.end()); |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | if (next_flush == std::chrono::steady_clock::time_point::max()) |
| 458 | MWARNING("Unable to send transaction(s), no available connections"); |
| 459 | else if (!zone->flush_callbacks || next_flush < zone->flush_txs.expiry()) |
| 460 | fluff_flush::queue(std::move(zone), next_flush); |
| 461 | } |
| 462 | }; |
| 463 | |
| 464 | //! Updates the connection for a channel. |
| 465 | struct update_channel |
| 466 | { |
| 467 | std::shared_ptr<detail::zone> zone_; |
| 468 | const std::size_t channel_; |
| 469 | const boost::uuids::uuid connection_; |
| 470 | |
| 471 | //! \pre Called within `stem_.strand`. |
| 472 | void operator()() const |
| 473 | { |
| 474 | if (!zone_) |
| 475 | return; |
| 476 | |
| 477 | noise_channel& channel = zone_->channels.at(channel_); |
| 478 | assert(channel.strand.running_in_this_thread()); |
| 479 | static_assert( |
| 480 | CRYPTONOTE_MAX_FRAGMENTS <= (noise_min_epoch / (noise_min_delay + noise_delay_range)), |
| 481 | "Max fragments more than the max that can be sent in an epoch" |
| 482 | ); |
| 483 | |
| 484 | /* This clears the active message so that a message "in-flight" is |
| 485 | restarted. DO NOT try to send the remainder of the fragments, this |
| 486 | additional send time can leak that this node was sending out a real |
| 487 | notify (tx) instead of dummy noise. */ |
| 488 | |
| 489 | channel.connection = connection_; |
| 490 | channel.active = nullptr; |
| 491 | |
| 492 | if (connection_.is_nil()) |
| 493 | channel.queue.clear(); |
| 494 | } |
| 495 | }; |
| 496 | |
| 497 | //! Merges `out_connections_` into the existing `zone_->map`. |
| 498 | struct update_channels |
| 499 | { |
| 500 | std::shared_ptr<detail::zone> zone_; |
| 501 | std::vector<boost::uuids::uuid> out_connections_; |
| 502 | |
| 503 | //! \pre Called within `zone->strand`. |
| 504 | static void post(std::shared_ptr<detail::zone> zone) |
| 505 | { |
| 506 | if (!zone) |
| 507 | return; |
| 508 | |
| 509 | assert(zone->strand.running_in_this_thread()); |
| 510 | |
| 511 | zone->connection_count = zone->map.size(); |
| 512 | |
| 513 | // only noise uses the "noise channels", only update when enabled |
| 514 | if (zone->noise.empty()) |
| 515 | return; |
| 516 | |
| 517 | for (auto id = zone->map.begin(); id != zone->map.end(); ++id) |
| 518 | { |
| 519 | const std::size_t i = id - zone->map.begin(); |
| 520 | boost::asio::post(zone->channels[i].strand, update_channel{zone, i, *id}); |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | //! \pre Called within `zone_->strand`. |
| 525 | static void run(std::shared_ptr<detail::zone> zone, std::vector<boost::uuids::uuid> out_connections) |
| 526 | { |
| 527 | if (!zone) |
| 528 | return; |
| 529 | |
| 530 | assert(zone->strand.running_in_this_thread()); |
| 531 | if (zone->map.update(std::move(out_connections))) |
| 532 | post(std::move(zone)); |
| 533 | } |
| 534 | |
| 535 | //! \pre Called within `zone_->strand`. |
| 536 | void operator()() |
| 537 | { |
| 538 | run(std::move(zone_), std::move(out_connections_)); |
| 539 | } |
| 540 | }; |
| 541 | |
| 542 | //! Checks fluff status for this node, and then does stem or fluff for txes |
| 543 | struct dandelionpp_notify |
| 544 | { |
| 545 | std::shared_ptr<detail::zone> zone_; |
| 546 | i_core_events* core_; |
| 547 | std::vector<blobdata> txs_; |
| 548 | boost::uuids::uuid source_; |
| 549 | relay_method tx_relay; |
| 550 | |
| 551 | //! \pre Called in `zone_->strand` |
| 552 | void operator()() |
| 553 | { |
| 554 | if (!zone_ || !core_ || txs_.empty()) |
| 555 | return; |
| 556 | |
| 557 | if (!zone_->fluffing || tx_relay == relay_method::local) |
| 558 | { |
| 559 | core_->on_transactions_relayed(epee::to_span(txs_), relay_method::stem); |
| 560 | for (int tries = 2; 0 < tries; tries--) |
| 561 | { |
| 562 | const boost::uuids::uuid destination = zone_->map.get_stem(source_); |
| 563 | if (!destination.is_nil() && make_payload_send_txs(*zone_->p2p, std::vector<blobdata>{txs_}, destination, zone_->pad_txs, false)) |
| 564 | { |
| 565 | /* Source is intentionally omitted in debug log for privacy - a |
| 566 | nil uuid indicates source is that node. */ |
| 567 | MDEBUG("Sent " << txs_.size() << " transaction(s) to " << destination << " using Dandelion++ stem"); |
| 568 | return; |
| 569 | } |
| 570 | |
| 571 | // connection list may be outdated, try again |
| 572 | update_channels::run(zone_, get_out_connections(*zone_->p2p, core_)); |
| 573 | } |
| 574 | |
| 575 | MERROR("Unable to send transaction(s) via Dandelion++ stem"); |
| 576 | } |
| 577 | |
| 578 | core_->on_transactions_relayed(epee::to_span(txs_), relay_method::fluff); |
| 579 | fluff_notify::run(std::move(zone_), epee::to_span(txs_), source_); |
| 580 | } |
| 581 | }; |
| 582 | |
| 583 | //! Swaps out noise/dandelionpp channels entirely; new epoch start. |
| 584 | class change_channels |
| 585 | { |
| 586 | std::shared_ptr<detail::zone> zone_; |
| 587 | net::dandelionpp::connection_map map_; // Requires manual copy constructor |
| 588 | bool fluffing_; |
| 589 | |
| 590 | public: |
| 591 | explicit change_channels(std::shared_ptr<detail::zone> zone, net::dandelionpp::connection_map map, const bool fluffing) |
| 592 | : zone_(std::move(zone)), map_(std::move(map)), fluffing_(fluffing) |
| 593 | {} |
| 594 | |
| 595 | change_channels(change_channels&&) = default; |
| 596 | change_channels(const change_channels& source) |
| 597 | : zone_(source.zone_), map_(source.map_.clone()), fluffing_(source.fluffing_) |
| 598 | {} |
| 599 | |
| 600 | //! \pre Called within `zone_->strand`. |
| 601 | void operator()() |
| 602 | { |
| 603 | if (!zone_) |
| 604 | return; |
| 605 | |
| 606 | assert(zone_->strand.running_in_this_thread()); |
| 607 | |
| 608 | if (zone_->nzone == epee::net_utils::zone::public_) |
| 609 | MDEBUG("Starting new Dandelion++ epoch: " << (fluffing_ ? "fluff" : "stem")); |
| 610 | |
| 611 | zone_->map = std::move(map_); |
| 612 | zone_->fluffing = fluffing_; |
| 613 | update_channels::post(std::move(zone_)); |
| 614 | } |
| 615 | }; |
| 616 | |
| 617 | //! Sends a noise packet or real notification and sets timer for next call. |
| 618 | struct send_noise |
| 619 | { |
| 620 | std::shared_ptr<detail::zone> zone_; |
| 621 | const std::size_t channel_; |
| 622 | const i_core_events* core_; |
| 623 | |
| 624 | static void wait(const std::chrono::steady_clock::time_point start, std::shared_ptr<detail::zone> zone, const std::size_t index, const i_core_events* core) |
| 625 | { |
| 626 | if (!zone) |
| 627 | return; |
| 628 | |
| 629 | noise_channel& channel = zone->channels.at(index); |
| 630 | channel.next_noise.expires_at(start + noise_min_delay + random_duration(noise_delay_range)); |
| 631 | channel.next_noise.async_wait( |
| 632 | channel.strand.wrap(send_noise{std::move(zone), index, core}) |
| 633 | ); |
| 634 | } |
| 635 | |
| 636 | //! \pre Called within `zone_->channels[channel_].strand`. |
| 637 | void operator()(boost::system::error_code error) |
| 638 | { |
| 639 | if (!zone_ || !zone_->p2p || zone_->noise.empty()) |
| 640 | return; |
| 641 | |
| 642 | if (error && error != boost::system::errc::operation_canceled) |
| 643 | throw boost::system::system_error{error, "send_noise timer failed"}; |
| 644 | |
| 645 | assert(zone_->channels.at(channel_).strand.running_in_this_thread()); |
| 646 | |
| 647 | const auto start = std::chrono::steady_clock::now(); |
| 648 | noise_channel& channel = zone_->channels.at(channel_); |
| 649 | |
| 650 | if (!channel.connection.is_nil()) |
| 651 | { |
| 652 | epee::byte_slice message = nullptr; |
| 653 | if (!channel.active.empty()) |
| 654 | message = channel.active.take_slice(zone_->noise.size()); |
| 655 | else if (!channel.queue.empty()) |
| 656 | { |
| 657 | channel.active = channel.queue.front().clone(); |
| 658 | message = channel.active.take_slice(zone_->noise.size()); |
| 659 | } |
| 660 | else |
| 661 | message = zone_->noise.clone(); |
| 662 | |
| 663 | if (zone_->p2p->send(std::move(message), channel.connection)) |
| 664 | { |
| 665 | if (!channel.queue.empty() && channel.active.empty()) |
| 666 | channel.queue.pop_front(); |
| 667 | } |
| 668 | else |
| 669 | { |
| 670 | channel.active = nullptr; |
| 671 | channel.connection = boost::uuids::nil_uuid(); |
| 672 | auto height = get_blockchain_height(*zone_->p2p, core_); |
| 673 | |
| 674 | auto connections = get_out_connections(*zone_->p2p, height); |
| 675 | if (connections.empty()) |
| 676 | MWARNING("Unable to send transaction(s) to " << epee::net_utils::zone_to_string(zone_->nzone) << |
| 677 | " - no suitable outbound connections at height " << height); |
| 678 | |
| 679 | boost::asio::post(zone_->strand, update_channels{zone_, std::move(connections)}); |
| 680 | } |
| 681 | } |
| 682 | |
| 683 | wait(start, std::move(zone_), channel_, core_); |
| 684 | } |
| 685 | }; |
| 686 | |
| 687 | //! Prepares connections for new channel/dandelionpp epoch and sets timer for next epoch |
| 688 | struct start_epoch |
| 689 | { |
| 690 | // Variables allow for Dandelion++ extension |
| 691 | std::shared_ptr<detail::zone> zone_; |
| 692 | std::chrono::seconds min_epoch_; |
| 693 | std::chrono::seconds epoch_range_; |
| 694 | std::size_t count_; |
| 695 | const i_core_events* core_; |
| 696 | |
| 697 | //! \pre Should not be invoked within any strand to prevent blocking. |
| 698 | void operator()(const boost::system::error_code error = {}) |
| 699 | { |
| 700 | if (!zone_ || !zone_->p2p) |
| 701 | return; |
| 702 | |
| 703 | if (error && error != boost::system::errc::operation_canceled) |
| 704 | throw boost::system::system_error{error, "start_epoch timer failed"}; |
| 705 | |
| 706 | const bool fluffing = crypto::rand_idx(unsigned(100)) < CRYPTONOTE_DANDELIONPP_FLUFF_PROBABILITY; |
| 707 | const auto start = std::chrono::steady_clock::now(); |
| 708 | auto connections = get_out_connections(*(zone_->p2p), core_); |
| 709 | boost::asio::dispatch( |
| 710 | zone_->strand, |
| 711 | change_channels{zone_, net::dandelionpp::connection_map{std::move(connections), count_}, fluffing} |
| 712 | ); |
| 713 | |
| 714 | detail::zone& alias = *zone_; |
| 715 | alias.next_epoch.expires_at(start + min_epoch_ + random_duration(epoch_range_)); |
| 716 | alias.next_epoch.async_wait(start_epoch{std::move(*this)}); |
| 717 | } |
| 718 | }; |
| 719 | } // anonymous |
| 720 | |
| 721 | notify::notify(boost::asio::io_context& service, std::shared_ptr<connections> p2p, epee::byte_slice noise, epee::net_utils::zone zone, const bool pad_txs, i_core_events& core) |
| 722 | : zone_(std::make_shared<detail::zone>(service, std::move(p2p), std::move(noise), zone, pad_txs)) |
| 723 | , core_(std::addressof(core)) |
| 724 | { |
| 725 | if (!zone_->p2p) |
| 726 | throw std::logic_error{"cryptonote::levin::notify cannot have nullptr p2p argument"}; |
| 727 | |
| 728 | const bool noise_enabled = !zone_->noise.empty(); |
| 729 | if (noise_enabled || zone == epee::net_utils::zone::public_) |
| 730 | { |
| 731 | const auto now = std::chrono::steady_clock::now(); |
| 732 | const auto min_epoch = noise_enabled ? noise_min_epoch : dandelionpp_min_epoch; |
| 733 | const auto epoch_range = noise_enabled ? noise_epoch_range : dandelionpp_epoch_range; |
| 734 | const std::size_t out_count = noise_enabled ? CRYPTONOTE_NOISE_CHANNELS : CRYPTONOTE_DANDELIONPP_STEMS; |
| 735 | |
| 736 | start_epoch{zone_, min_epoch, epoch_range, out_count, core_}(); |
| 737 | |
| 738 | for (std::size_t channel = 0; channel < zone_->channels.size(); ++channel) |
| 739 | send_noise::wait(now, zone_, channel, core_); |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | notify::~notify() noexcept |
| 744 | {} |
| 745 | |
| 746 | notify::status notify::get_status() const noexcept |
| 747 | { |
| 748 | if (!zone_) |
| 749 | return {false, false, false}; |
| 750 | |
| 751 | // `connection_count` is only set when `!noise.empty()`. |
| 752 | const std::size_t connection_count = zone_->connection_count; |
| 753 | bool has_outgoing = connection_count; |
| 754 | if (zone_->noise.empty()) |
| 755 | has_outgoing = zone_->p2p->get_out_connections_count(); |
| 756 | return {!zone_->noise.empty(), CRYPTONOTE_NOISE_CHANNELS <= connection_count, has_outgoing}; |
| 757 | } |
| 758 | |
| 759 | void notify::new_out_connection() |
| 760 | { |
| 761 | if (!zone_ || zone_->noise.empty() || CRYPTONOTE_NOISE_CHANNELS <= zone_->connection_count) |
| 762 | return; |
| 763 | |
| 764 | boost::asio::dispatch( |
| 765 | zone_->strand, |
| 766 | update_channels{zone_, get_out_connections(*(zone_->p2p), core_)} |
| 767 | ); |
| 768 | } |
| 769 | |
| 770 | void notify::on_handshake_complete(const boost::uuids::uuid &id, bool is_income) |
| 771 | { |
| 772 | if (!zone_) |
| 773 | return; |
| 774 | |
| 775 | auto& zone = zone_; |
| 776 | boost::asio::dispatch(zone_->strand, [zone, id, is_income] { |
| 777 | zone->contexts[id] = { |
| 778 | .fluff_txs = {}, |
| 779 | .flush_time = std::chrono::steady_clock::time_point::max(), |
| 780 | .m_is_income = is_income, |
| 781 | }; |
| 782 | }); |
| 783 | } |
| 784 | |
| 785 | void notify::on_connection_close(const boost::uuids::uuid &id) |
| 786 | { |
| 787 | if (!zone_) |
| 788 | return; |
| 789 | |
| 790 | auto& zone = zone_; |
| 791 | boost::asio::dispatch(zone_->strand, [zone, id]{ |
| 792 | zone->contexts.erase(id); |
| 793 | }); |
| 794 | } |
| 795 | |
| 796 | void notify::run_epoch() |
| 797 | { |
| 798 | if (!zone_) |
| 799 | return; |
| 800 | zone_->next_epoch.cancel(); |
| 801 | } |
| 802 | |
| 803 | void notify::run_stems() |
| 804 | { |
| 805 | if (!zone_) |
| 806 | return; |
| 807 | |
| 808 | for (noise_channel& channel : zone_->channels) |
| 809 | channel.next_noise.cancel(); |
| 810 | } |
| 811 | |
| 812 | void notify::run_fluff() |
| 813 | { |
| 814 | if (!zone_) |
| 815 | return; |
| 816 | zone_->flush_txs.cancel(); |
| 817 | } |
| 818 | |
| 819 | bool notify::send_txs(std::vector<blobdata> txs, const boost::uuids::uuid& source, relay_method tx_relay) |
| 820 | { |
| 821 | if (txs.empty()) |
| 822 | return true; |
| 823 | |
| 824 | if (!zone_) |
| 825 | return false; |
| 826 | |
| 827 | /* If noise is enabled in a zone, it always takes precedence. The technique |
| 828 | provides good protection against ISP adversaries, but not sybil |
| 829 | adversaries. Noise is currently only enabled over I2P/Tor - those |
| 830 | networks provide protection against sybil attacks (we only send to |
| 831 | outgoing connections). |
| 832 | |
| 833 | If noise is disabled, Dandelion++ is used for public networks only. |
| 834 | Dandelion++ over I2P/Tor should be an interesting case to investigate, |
| 835 | but the mempool/stempool needs to know the zone a tx originated from to |
| 836 | work properly. */ |
| 837 | |
| 838 | if (!zone_->noise.empty() && !zone_->channels.empty()) |
| 839 | { |
| 840 | // covert send in "noise" channel |
| 841 | static_assert( |
| 842 | CRYPTONOTE_MAX_FRAGMENTS * CRYPTONOTE_NOISE_BYTES <= LEVIN_DEFAULT_MAX_PACKET_SIZE, "most nodes will reject this fragment setting" |
| 843 | ); |
| 844 | |
| 845 | if (tx_relay == relay_method::stem) |
| 846 | { |
| 847 | MWARNING("Dandelion++ stem not supported over noise networks"); |
| 848 | tx_relay = relay_method::local; // do not put into stempool embargo (hopefully not there already!). |
| 849 | } |
| 850 | |
| 851 | core_->on_transactions_relayed(epee::to_span(txs), tx_relay); |
| 852 | |
| 853 | // Padding is not useful when using noise mode. Send as stem so receiver |
| 854 | // forwards in Dandelion++ mode. |
| 855 | epee::byte_slice message = epee::levin::make_fragmented_notify( |
| 856 | zone_->noise.size(), NOTIFY_NEW_TRANSACTIONS::ID, make_tx_message(std::move(txs), false, false) |
| 857 | ); |
| 858 | if (CRYPTONOTE_MAX_FRAGMENTS * zone_->noise.size() < message.size()) |
| 859 | { |
| 860 | MERROR("notify::send_txs provided message exceeding covert fragment size"); |
| 861 | return false; |
| 862 | } |
| 863 | |
| 864 | for (std::size_t channel = 0; channel < zone_->channels.size(); ++channel) |
| 865 | { |
| 866 | boost::asio::dispatch( |
| 867 | zone_->channels[channel].strand, |
| 868 | queue_covert_notify{zone_, message.clone(), channel} |
| 869 | ); |
| 870 | } |
| 871 | } |
| 872 | else |
| 873 | { |
| 874 | switch (tx_relay) |
| 875 | { |
| 876 | default: |
| 877 | case relay_method::none: |
| 878 | case relay_method::block: |
| 879 | return false; |
| 880 | case relay_method::stem: |
| 881 | case relay_method::forward: |
| 882 | case relay_method::local: |
| 883 | if (zone_->nzone == epee::net_utils::zone::public_) |
| 884 | { |
| 885 | // this will change a local/forward tx to stem or fluff ... |
| 886 | boost::asio::dispatch( |
| 887 | zone_->strand, |
| 888 | dandelionpp_notify{zone_, core_, std::move(txs), source, tx_relay} |
| 889 | ); |
| 890 | break; |
| 891 | } |
| 892 | /* fallthrough */ |
| 893 | case relay_method::fluff: |
| 894 | /* If sending stem/forward/local txes over non public networks, |
| 895 | continue to claim that relay mode even though it used the "fluff" |
| 896 | routine. A "fluff" over i2p/tor is not the same as a "fluff" over |
| 897 | ipv4/6. Marking it as "fluff" here will make the tx immediately |
| 898 | visible externally from this node, which is not desired. */ |
| 899 | core_->on_transactions_relayed(epee::to_span(txs), tx_relay); |
| 900 | boost::asio::dispatch(zone_->strand, fluff_notify{zone_, std::move(txs), source}); |
| 901 | break; |
| 902 | } |
| 903 | } |
| 904 | return true; |
| 905 | } |
| 906 | } // levin |
| 907 | } // net |