Debian Codegraph @

monero/src/cryptonote_protocol/cryptonote_protocol_handler.inl

raw
1 /// @file
2 /// @author rfree (current maintainer/user in monero.cc project - most of code is from CryptoNote)
3 /// @brief This is the original cryptonote protocol network-events handler, modified by us
4
5 // Copyright (c) 2014-2022, The Monero Project
6 //
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without modification, are
10 // permitted provided that the following conditions are met:
11 //
12 // 1. Redistributions of source code must retain the above copyright notice, this list of
13 // conditions and the following disclaimer.
14 //
15 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
16 // of conditions and the following disclaimer in the documentation and/or other
17 // materials provided with the distribution.
18 //
19 // 3. Neither the name of the copyright holder nor the names of its contributors may be
20 // used to endorse or promote products derived from this software without specific
21 // prior written permission.
22 //
23 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
24 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
25 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
26 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
31 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
34
35 // (may contain code and/or modifications by other developers)
36 // developer rfree: this code is caller of our new network code, and is modded; e.g. for rate limiting
37
38 #include <boost/optional/optional.hpp>
39 #include <list>
40 #include <ctime>
41
42 #include "cryptonote_basic/cryptonote_format_utils.h"
43 #include "profile_tools.h"
44 #include "net/network_throttle-detail.hpp"
45 #include "common/pruning.h"
46 #include "common/util.h"
47
48 #undef MONERO_DEFAULT_LOG_CATEGORY
49 #define MONERO_DEFAULT_LOG_CATEGORY "net.cn"
50
51 #define MLOG_P2P_MESSAGE(x) MCINFO("net.p2p.msg", context << x)
52 #define MLOGIF_P2P_MESSAGE(init, test, x) \
53 do { \
54 const auto level = el::Level::Info; \
55 const char *cat = "net.p2p.msg"; \
56 if (ELPP->vRegistry()->allowed(level, cat)) { \
57 init; \
58 if (test) \
59 el::base::Writer(level, el::Color::Default, __FILE__, __LINE__, ELPP_FUNC, el::base::DispatchAction::NormalLog).construct(cat) << x; \
60 } \
61 } while(0)
62
63 #define MLOG_PEER_STATE(x) \
64 MCINFO(MONERO_DEFAULT_LOG_CATEGORY, context << "[" << epee::string_tools::to_string_hex(context.m_pruning_seed) << "] state: " << x << " in state " << cryptonote::get_protocol_state_string(context.m_state))
65
66 #define BLOCK_QUEUE_NSPANS_THRESHOLD 10 // chunks of N blocks
67 #define BLOCK_QUEUE_SIZE_THRESHOLD (100*1024*1024) // MB
68 #define BLOCK_QUEUE_FORCE_DOWNLOAD_NEAR_BLOCKS 1000
69 #define REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY (5 * 1000000) // microseconds
70 #define REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD (30 * 1000000) // microseconds
71 #define IDLE_PEER_KICK_TIME (240 * 1000000) // microseconds
72 #define NON_RESPONSIVE_PEER_KICK_TIME (20 * 1000000) // microseconds
73 #define PASSIVE_PEER_KICK_TIME (60 * 1000000) // microseconds
74 #define DROP_ON_SYNC_WEDGE_THRESHOLD (30 * 1000000000ull) // nanoseconds
75 #define LAST_ACTIVITY_STALL_THRESHOLD (2.0f) // seconds
76 #define DROP_PEERS_ON_SCORE -2
77
78 namespace cryptonote
79 {
80 template <class CryptoHashContainer>
81 inline bool make_pool_supplement_from_block_entry(
82 const std::vector<cryptonote::tx_blob_entry>& tx_entries,
83 const CryptoHashContainer& blk_tx_hashes,
84 const bool allow_pruned,
85 cryptonote::pool_supplement& pool_supplement)
86 {
87 pool_supplement.nic_verified_hf_version = 0;
88
89 if (tx_entries.size() > blk_tx_hashes.size())
90 {
91 MERROR("Failed to make pool supplement: Too many transaction blobs!");
92 return false;
93 }
94
95 for (const cryptonote::tx_blob_entry& tx_entry: tx_entries)
96 {
97 if (tx_entry.blob.size() > get_max_tx_size())
98 {
99 MERROR("Transaction blob of length " << tx_entry.blob.size() << " is too large to unpack!");
100 return false;
101 }
102
103 const bool is_pruned = tx_entry.prunable_hash != crypto::null_hash;
104 if (is_pruned && !allow_pruned)
105 {
106 MERROR("Pruned transaction not allowed here");
107 return false;
108 }
109
110 cryptonote::transaction tx;
111 crypto::hash tx_hash;
112 bool parse_success = false;
113 if (is_pruned)
114 {
115 if ((parse_success = cryptonote::parse_and_validate_tx_base_from_blob(tx_entry.blob, tx)))
116 tx_hash = cryptonote::get_pruned_transaction_hash(tx, tx_entry.prunable_hash);
117 }
118 else
119 {
120 parse_success = cryptonote::parse_and_validate_tx_from_blob(tx_entry.blob, tx, tx_hash);
121 }
122
123 if (!parse_success)
124 {
125 MERROR("failed to parse and/or validate transaction: "
126 << epee::string_tools::buff_to_hex_nodelimer(tx_entry.blob)
127 );
128 return false;
129 }
130 else if (!blk_tx_hashes.count(tx_hash))
131 {
132 MERROR("transaction " << tx_hash << " not in block");
133 return false;
134 }
135
136 pool_supplement.txs_by_txid.emplace(tx_hash, std::make_pair(std::move(tx), tx_entry.blob));
137 }
138
139 return true;
140 }
141
142 inline bool make_full_pool_supplement_from_block_entry(
143 const cryptonote::block_complete_entry& blk_entry,
144 cryptonote::pool_supplement& pool_supplement)
145 {
146 cryptonote::block blk;
147 if (!cryptonote::parse_and_validate_block_from_blob(blk_entry.block, blk))
148 {
149 MERROR("sent bad block: failed to parse and/or validate block: "
150 << epee::string_tools::buff_to_hex_nodelimer(blk_entry.block)
151 );
152 return false;
153 }
154
155 const std::unordered_set<crypto::hash> blk_tx_hashes(blk.tx_hashes.cbegin(), blk.tx_hashes.cend());
156
157 if (blk_tx_hashes.size() != blk_entry.txs.size())
158 {
159 MERROR("sent bad block entry: number of hashes is not equal number of tx blobs: "
160 << epee::string_tools::buff_to_hex_nodelimer(blk_entry.block)
161 );
162 return false;
163 }
164 else if (blk_tx_hashes.size() != blk.tx_hashes.size())
165 {
166 MERROR("sent bad block entry: there are duplicate tx hashes in parsed block: "
167 << epee::string_tools::buff_to_hex_nodelimer(blk_entry.block));
168 return false;
169 }
170
171 // We set `allow_pruned` equal to whether this block entry is pruned since the pruned flag
172 // should be checked anyways by the time we deserialize transactions
173 return make_pool_supplement_from_block_entry(blk_entry.txs, blk_tx_hashes, blk_entry.pruned, pool_supplement);
174 }
175
176
177 //-----------------------------------------------------------------------------------------------------------------------
178 template<class t_core>
179 t_cryptonote_protocol_handler<t_core>::t_cryptonote_protocol_handler(t_core& rcore, nodetool::i_p2p_endpoint<connection_context>* p_net_layout, bool offline):m_core(rcore),
180 m_p2p(p_net_layout),
181 m_syncronized_connections_count(0),
182 m_synchronized(offline),
183 m_ask_for_txpool_complement(true),
184 m_stopping(false),
185 m_no_sync(false)
186
187 {
188 if(!m_p2p)
189 m_p2p = &m_p2p_stub;
190 }
191 //-----------------------------------------------------------------------------------------------------------------------
192 template<class t_core>
193 bool t_cryptonote_protocol_handler<t_core>::init(const boost::program_options::variables_map& vm)
194 {
195 m_sync_timer.pause();
196 m_sync_timer.reset();
197 m_add_timer.pause();
198 m_add_timer.reset();
199 m_last_add_end_time = 0;
200 m_sync_spans_downloaded = 0;
201 m_sync_old_spans_downloaded = 0;
202 m_sync_bad_spans_downloaded = 0;
203 m_sync_download_chain_size = 0;
204 m_sync_download_objects_size = 0;
205
206 m_block_download_max_size = command_line::get_arg(vm, cryptonote::arg_block_download_max_size);
207 m_sync_pruned_blocks = command_line::get_arg(vm, cryptonote::arg_sync_pruned_blocks);
208
209 return true;
210 }
211 //------------------------------------------------------------------------------------------------------------------------
212 template<class t_core>
213 bool t_cryptonote_protocol_handler<t_core>::deinit()
214 {
215 return true;
216 }
217 //------------------------------------------------------------------------------------------------------------------------
218 template<class t_core>
219 void t_cryptonote_protocol_handler<t_core>::set_p2p_endpoint(nodetool::i_p2p_endpoint<connection_context>* p2p)
220 {
221 if(p2p)
222 m_p2p = p2p;
223 else
224 m_p2p = &m_p2p_stub;
225 }
226 //------------------------------------------------------------------------------------------------------------------------
227 template<class t_core>
228 bool t_cryptonote_protocol_handler<t_core>::on_callback(cryptonote_connection_context& context)
229 {
230 LOG_PRINT_CCONTEXT_L2("callback fired");
231 CHECK_AND_ASSERT_MES_CC( context.m_callback_request_count > 0, false, "false callback fired, but context.m_callback_request_count=" << context.m_callback_request_count);
232 --context.m_callback_request_count;
233
234 uint32_t notified = true;
235 if (context.m_idle_peer_notification.compare_exchange_strong(notified, not notified))
236 {
237 if (context.m_state == cryptonote_connection_context::state_synchronizing && context.m_last_request_time != boost::date_time::not_a_date_time)
238 {
239 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
240 const boost::posix_time::time_duration dt = now - context.m_last_request_time;
241 const auto ms = dt.total_microseconds();
242 if (ms > IDLE_PEER_KICK_TIME || (context.m_expect_response && ms > NON_RESPONSIVE_PEER_KICK_TIME))
243 {
244 if (context.m_score-- >= 0)
245 {
246 MINFO(context << " kicking idle peer, last update " << (dt.total_microseconds() / 1.e6) << " seconds ago, expecting " << (int)context.m_expect_response);
247 context.m_last_request_time = boost::date_time::not_a_date_time;
248 context.m_expect_response = 0;
249 context.m_expect_height = 0;
250 context.m_requested_objects.clear();
251 context.m_state = cryptonote_connection_context::state_standby; // we'll go back to adding, then (if we can't), download
252 }
253 else
254 {
255 MINFO(context << "dropping idle peer with negative score");
256 drop_connection_with_score(context, context.m_expect_response == 0 ? 1 : 5, false);
257 return false;
258 }
259 }
260 }
261 }
262
263 notified = true;
264 if (context.m_new_stripe_notification.compare_exchange_strong(notified, not notified))
265 {
266 if (context.m_state == cryptonote_connection_context::state_normal)
267 context.m_state = cryptonote_connection_context::state_synchronizing;
268 }
269
270 if(context.m_state == cryptonote_connection_context::state_synchronizing && context.m_last_request_time == boost::posix_time::not_a_date_time)
271 {
272 NOTIFY_REQUEST_CHAIN::request r = {};
273 context.m_needed_objects.clear();
274 context.m_expect_height = m_core.get_current_blockchain_height();
275 m_core.get_short_chain_history(r.block_ids);
276 handler_request_blocks_history( r.block_ids ); // change the limit(?), sleep(?)
277 r.prune = m_sync_pruned_blocks;
278 context.m_last_request_time = boost::posix_time::microsec_clock::universal_time();
279 context.m_expect_response = NOTIFY_RESPONSE_CHAIN_ENTRY::ID;
280 MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() );
281 post_notify<NOTIFY_REQUEST_CHAIN>(r, context);
282 MLOG_PEER_STATE("requesting chain");
283 }
284 else if(context.m_state == cryptonote_connection_context::state_standby)
285 {
286 context.m_state = cryptonote_connection_context::state_synchronizing;
287 try_add_next_blocks(context);
288 }
289
290 return true;
291 }
292 //------------------------------------------------------------------------------------------------------------------------
293 template<class t_core>
294 void t_cryptonote_protocol_handler<t_core>::log_connections()
295 {
296 std::stringstream ss;
297 ss.precision(1);
298
299 double down_sum = 0.0;
300 double down_curr_sum = 0.0;
301 double up_sum = 0.0;
302 double up_curr_sum = 0.0;
303
304 ss << std::setw(30) << std::left << "Remote Host"
305 << std::setw(20) << "Peer id"
306 << std::setw(20) << "Support Flags"
307 << std::setw(30) << "Recv/Sent (inactive,sec)"
308 << std::setw(25) << "State"
309 << std::setw(20) << "Livetime(sec)"
310 << std::setw(12) << "Down (kB/s)"
311 << std::setw(14) << "Down(now)"
312 << std::setw(10) << "Up (kB/s)"
313 << std::setw(13) << "Up(now)"
314 << ENDL;
315
316 m_p2p->for_each_connection([&](const connection_context& cntxt, nodetool::peerid_type peer_id, uint32_t support_flags)
317 {
318 bool local_ip = cntxt.m_remote_address.is_local();
319 auto connection_time = time(NULL) - cntxt.m_started;
320 ss << std::setw(30) << std::left << std::string(cntxt.m_is_income ? " [INC]":"[OUT]") +
321 cntxt.m_remote_address.str()
322 << std::setw(20) << nodetool::peerid_to_string(peer_id)
323 << std::setw(20) << std::hex << support_flags
324 << std::setw(30) << std::to_string(cntxt.m_recv_cnt)+ "(" + std::to_string(time(NULL) - cntxt.m_last_recv) + ")" + "/" + std::to_string(cntxt.m_send_cnt) + "(" + std::to_string(time(NULL) - cntxt.m_last_send) + ")"
325 << std::setw(25) << get_protocol_state_string(cntxt.m_state)
326 << std::setw(20) << std::to_string(time(NULL) - cntxt.m_started)
327 << std::setw(12) << std::fixed << (connection_time == 0 ? 0.0 : cntxt.m_recv_cnt / connection_time / 1024)
328 << std::setw(14) << std::fixed << cntxt.m_current_speed_down / 1024
329 << std::setw(10) << std::fixed << (connection_time == 0 ? 0.0 : cntxt.m_send_cnt / connection_time / 1024)
330 << std::setw(13) << std::fixed << cntxt.m_current_speed_up / 1024
331 << (local_ip ? "[LAN]" : "")
332 << std::left << (cntxt.m_remote_address.is_loopback() ? "[LOCALHOST]" : "") // 127.0.0.1
333 << ENDL;
334
335 if (connection_time > 1)
336 {
337 down_sum += (cntxt.m_recv_cnt / connection_time / 1024);
338 up_sum += (cntxt.m_send_cnt / connection_time / 1024);
339 }
340
341 down_curr_sum += (cntxt.m_current_speed_down / 1024);
342 up_curr_sum += (cntxt.m_current_speed_up / 1024);
343
344 return true;
345 });
346 ss << ENDL
347 << std::setw(125) << " "
348 << std::setw(12) << down_sum
349 << std::setw(14) << down_curr_sum
350 << std::setw(10) << up_sum
351 << std::setw(13) << up_curr_sum
352 << ENDL;
353 LOG_PRINT_L0("Connections: " << ENDL << ss.str());
354 }
355 //------------------------------------------------------------------------------------------------------------------------
356 // Returns a list of connection_info objects describing each open p2p connection
357 //------------------------------------------------------------------------------------------------------------------------
358 template<class t_core>
359 std::list<connection_info> t_cryptonote_protocol_handler<t_core>::get_connections()
360 {
361 std::list<connection_info> connections;
362
363 m_p2p->for_each_connection([&](const connection_context& cntxt, nodetool::peerid_type peer_id, uint32_t support_flags)
364 {
365 connection_info cnx;
366 auto timestamp = time(NULL);
367
368 cnx.incoming = cntxt.m_is_income ? true : false;
369
370 cnx.address = cntxt.m_remote_address.str();
371 cnx.host = cntxt.m_remote_address.host_str();
372 cnx.ip = "";
373 cnx.port = "";
374 if (cntxt.m_remote_address.get_type_id() == epee::net_utils::ipv4_network_address::get_type_id())
375 {
376 cnx.ip = cnx.host;
377 cnx.port = std::to_string(cntxt.m_remote_address.as<epee::net_utils::ipv4_network_address>().port());
378 }
379 cnx.rpc_port = cntxt.m_rpc_port;
380 cnx.rpc_credits_per_hash = cntxt.m_rpc_credits_per_hash;
381
382 cnx.peer_id = nodetool::peerid_to_string(peer_id);
383
384 cnx.support_flags = support_flags;
385
386 cnx.recv_count = cntxt.m_recv_cnt;
387 cnx.recv_idle_time = timestamp - std::max(cntxt.m_started, cntxt.m_last_recv);
388
389 cnx.send_count = cntxt.m_send_cnt;
390 cnx.send_idle_time = timestamp - std::max(cntxt.m_started, cntxt.m_last_send);
391
392 cnx.state = get_protocol_state_string(cntxt.m_state);
393
394 cnx.live_time = timestamp - cntxt.m_started;
395
396 cnx.localhost = cntxt.m_remote_address.is_loopback();
397 cnx.local_ip = cntxt.m_remote_address.is_local();
398
399 auto connection_time = time(NULL) - cntxt.m_started;
400 if (connection_time == 0)
401 {
402 cnx.avg_download = 0;
403 cnx.avg_upload = 0;
404 }
405
406 else
407 {
408 cnx.avg_download = cntxt.m_recv_cnt / connection_time / 1024;
409 cnx.avg_upload = cntxt.m_send_cnt / connection_time / 1024;
410 }
411
412 cnx.current_download = cntxt.m_current_speed_down / 1024;
413 cnx.current_upload = cntxt.m_current_speed_up / 1024;
414
415 cnx.connection_id = epee::string_tools::pod_to_hex(cntxt.m_connection_id);
416 cnx.ssl = cntxt.m_ssl;
417
418 cnx.height = cntxt.m_remote_blockchain_height;
419 cnx.pruning_seed = cntxt.m_pruning_seed;
420 cnx.address_type = (uint8_t)cntxt.m_remote_address.get_type_id();
421
422 connections.push_back(cnx);
423
424 return true;
425 });
426
427 return connections;
428 }
429 //------------------------------------------------------------------------------------------------------------------------
430 template<class t_core>
431 bool t_cryptonote_protocol_handler<t_core>::process_payload_sync_data(const CORE_SYNC_DATA& hshd, cryptonote_connection_context& context, bool is_inital)
432 {
433 if(context.m_state == cryptonote_connection_context::state_before_handshake && !is_inital)
434 return true;
435
436 if(context.m_state == cryptonote_connection_context::state_synchronizing)
437 return true;
438
439 // from v6, if the peer advertises a top block version, reject if it's not what it should be (will only work if no voting)
440 if (hshd.current_height > 0)
441 {
442 const uint8_t version = m_core.get_ideal_hard_fork_version(hshd.current_height - 1);
443 if (version >= 6 && version != hshd.top_version)
444 {
445 if (version < hshd.top_version && version == m_core.get_ideal_hard_fork_version())
446 MDEBUG(context << " peer claims higher version than we think (" <<
447 (unsigned)hshd.top_version << " for " << (hshd.current_height - 1) << " instead of " << (unsigned)version <<
448 ") - we may be forked from the network and a software upgrade may be needed, or that peer is broken or malicious");
449 return false;
450 }
451 }
452
453 // reject weird pruning schemes
454 if (hshd.pruning_seed)
455 {
456 const uint32_t log_stripes = tools::get_pruning_log_stripes(hshd.pruning_seed);
457 if (log_stripes != CRYPTONOTE_PRUNING_LOG_STRIPES || tools::get_pruning_stripe(hshd.pruning_seed) > (1u << log_stripes))
458 {
459 MWARNING(context << " peer claim unexpected pruning seed " << epee::string_tools::to_string_hex(hshd.pruning_seed) << ", disconnecting");
460 return false;
461 }
462 }
463
464 if (hshd.current_height < context.m_remote_blockchain_height)
465 {
466 MINFO(context << "Claims " << hshd.current_height << ", claimed " << context.m_remote_blockchain_height << " before");
467 hit_score(context, 1);
468 }
469 context.m_remote_blockchain_height = hshd.current_height;
470 context.m_pruning_seed = hshd.pruning_seed;
471
472 uint64_t target = m_core.get_target_blockchain_height();
473 if (target == 0)
474 target = m_core.get_current_blockchain_height();
475
476 if(m_core.have_block(hshd.top_id))
477 {
478 context.set_state_normal();
479 if(is_inital && hshd.current_height >= target && target == m_core.get_current_blockchain_height())
480 on_connection_synchronized();
481 return true;
482 }
483
484 // No chain synchronization over hidden networks (tor, i2p, etc.)
485 if(context.m_remote_address.get_zone() != epee::net_utils::zone::public_)
486 {
487 context.set_state_normal();
488 return true;
489 }
490
491 if (hshd.current_height > target)
492 {
493 /* As I don't know if accessing hshd from core could be a good practice,
494 I prefer pushing target height to the core at the same time it is pushed to the user.
495 Nz. */
496 int64_t diff = static_cast<int64_t>(hshd.current_height) - static_cast<int64_t>(m_core.get_current_blockchain_height());
497 uint64_t abs_diff = std::abs(diff);
498 uint64_t max_block_height = std::max(hshd.current_height,m_core.get_current_blockchain_height());
499 uint64_t last_block_v1 = m_core.get_nettype() == TESTNET ? 624633 : m_core.get_nettype() == MAINNET ? 1009826 : (uint64_t)-1;
500 uint64_t diff_v2 = max_block_height > last_block_v1 ? std::min(abs_diff, max_block_height - last_block_v1) : 0;
501 MCLOG(is_inital ? el::Level::Info : el::Level::Debug, "global", el::Color::Yellow, context << "Sync data returned a new top block candidate: " << m_core.get_current_blockchain_height() << " -> " << hshd.current_height
502 << " [Your node is " << abs_diff << " blocks (" << tools::get_human_readable_timespan((abs_diff - diff_v2) * DIFFICULTY_TARGET_V1 + diff_v2 * DIFFICULTY_TARGET_V2) << ") "
503 << (0 <= diff ? std::string("behind") : std::string("ahead"))
504 << "] " << ENDL << "SYNCHRONIZATION started");
505 if (hshd.current_height >= m_core.get_current_blockchain_height() + 5) // don't switch to unsafe mode just for a few blocks
506 {
507 m_core.safesyncmode(false);
508 }
509 if (m_core.get_target_blockchain_height() == 0) // only when sync starts
510 {
511 m_sync_timer.resume();
512 m_sync_timer.reset();
513 m_add_timer.pause();
514 m_add_timer.reset();
515 m_last_add_end_time = 0;
516 m_sync_spans_downloaded = 0;
517 m_sync_old_spans_downloaded = 0;
518 m_sync_bad_spans_downloaded = 0;
519 m_sync_download_chain_size = 0;
520 m_sync_download_objects_size = 0;
521 }
522 m_core.set_target_blockchain_height((hshd.current_height));
523 }
524 MINFO(context << "Remote blockchain height: " << hshd.current_height << ", id: " << hshd.top_id);
525
526 if (m_no_sync)
527 {
528 context.set_state_normal();
529 return true;
530 }
531
532 context.m_state = cryptonote_connection_context::state_synchronizing;
533 //let the socket to send response to handshake, but request callback, to let send request data after response
534 LOG_PRINT_CCONTEXT_L2("requesting callback");
535 ++context.m_callback_request_count;
536 m_p2p->request_callback(context);
537 MLOG_PEER_STATE("requesting callback");
538 context.m_num_requested = 0;
539 return true;
540 }
541 //------------------------------------------------------------------------------------------------------------------------
542 template<class t_core>
543 bool t_cryptonote_protocol_handler<t_core>::get_payload_sync_data(CORE_SYNC_DATA& hshd)
544 {
545 m_core.get_blockchain_top(hshd.current_height, hshd.top_id);
546 hshd.top_version = m_core.get_ideal_hard_fork_version(hshd.current_height);
547 difficulty_type wide_cumulative_difficulty = m_core.get_block_cumulative_difficulty(hshd.current_height);
548 hshd.cumulative_difficulty = (wide_cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
549 hshd.cumulative_difficulty_top64 = ((wide_cumulative_difficulty >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
550 hshd.current_height +=1;
551 hshd.pruning_seed = m_core.get_blockchain_pruning_seed();
552 return true;
553 }
554 //------------------------------------------------------------------------------------------------------------------------
555 template<class t_core>
556 bool t_cryptonote_protocol_handler<t_core>::get_payload_sync_data(epee::byte_slice& data)
557 {
558 CORE_SYNC_DATA hsd = {};
559 get_payload_sync_data(hsd);
560 epee::serialization::store_t_to_binary(hsd, data);
561 return true;
562 }
563 //------------------------------------------------------------------------------------------------------------------------
564 template<class t_core>
565 int t_cryptonote_protocol_handler<t_core>::handle_notify_new_block(int command, NOTIFY_NEW_BLOCK::request& arg, cryptonote_connection_context& context)
566 {
567 // @TODO: Eventually drop support for this endpoint
568
569 MLOGIF_P2P_MESSAGE(crypto::hash hash; cryptonote::block b; bool ret = cryptonote::parse_and_validate_block_from_blob(arg.b.block, b, &hash);, ret, context << "Received NOTIFY_NEW_BLOCK " << hash << " (height " << arg.current_blockchain_height << ", " << arg.b.txs.size() << " txes)");
570
571 // Redirect this request form to fluffy block handling
572 NOTIFY_NEW_FLUFFY_BLOCK::request fluffy_arg;
573 fluffy_arg.b = std::move(arg.b);
574 fluffy_arg.current_blockchain_height = arg.current_blockchain_height;
575 return handle_notify_new_fluffy_block(command, fluffy_arg, context);
576 }
577 //------------------------------------------------------------------------------------------------------------------------
578 template<class t_core>
579 int t_cryptonote_protocol_handler<t_core>::handle_notify_new_fluffy_block(int command, NOTIFY_NEW_FLUFFY_BLOCK::request& arg, cryptonote_connection_context& context)
580 {
581 // If we are synchronizing the node or setting up this connection, then do nothing
582 if(context.m_state != cryptonote_connection_context::state_normal)
583 return 1;
584 if(!is_synchronized()) // can happen if a peer connection goes to normal but another thread still hasn't finished adding queued blocks
585 {
586 LOG_DEBUG_CC(context, "Received new block while syncing, ignored");
587 return 1;
588 }
589
590 // sanity check block blob size
591 if (!m_core.check_incoming_block_size(arg.b.block))
592 {
593 drop_connection(context, false, false);
594 return 1;
595 }
596
597 // Parse and quick hash incoming block, dropping the connection on failure
598 block new_block;
599 crypto::hash new_block_hash;
600 if (!parse_and_validate_block_from_blob(arg.b.block, new_block, &new_block_hash))
601 {
602 LOG_ERROR_CCONTEXT
603 (
604 "sent wrong block: failed to parse and validate block: "
605 << epee::string_tools::buff_to_hex_nodelimer(arg.b.block)
606 << ", dropping connection"
607 );
608
609 drop_connection(context, false, false);
610 return 1;
611 }
612
613 // Log block info
614 MLOG_P2P_MESSAGE(context << "Received NOTIFY_NEW_FLUFFY_BLOCK " << new_block_hash << " (height "
615 << arg.current_blockchain_height << ", " << arg.b.txs.size() << " txes)");
616
617 // Pause mining and resume after block verification to prevent wasted mining cycles while
618 // validating the next block. Needs more research into if this is a DoS vector or not. Invalid
619 // block validation will cause disconnects and bans, so it might not be that bad.
620 m_core.pause_mine();
621 const auto resume_mine_on_leave = epee::misc_utils::create_scope_leave_handler([this](){ m_core.resume_mine(); });
622
623 // This set allows us to quickly sanity check that the block binds all txs contained in this
624 // fluffy payload, which means that no extra stowaway txs can be harbored. In the case of a
625 // deterministic block verification failure, the peer will be punished accordingly. For other
626 // cases, *once* valid PoW will be required to perform expensive consensus checks for the txs
627 // inside the block.
628 std::unordered_map<crypto::hash, uint64_t> blk_txids_set;
629 for (size_t tx_idx = 0; tx_idx < new_block.tx_hashes.size(); ++tx_idx)
630 blk_txids_set.emplace(new_block.tx_hashes[tx_idx], tx_idx);
631
632 // Check for duplicate txids in parsed block blob
633 if (blk_txids_set.size() != new_block.tx_hashes.size())
634 {
635 MERROR("sent bad block entry: there are duplicate tx hashes in parsed block: "
636 << epee::string_tools::buff_to_hex_nodelimer(arg.b.block));
637 drop_connection(context, false, false);
638 return 1;
639 }
640
641 // Keeping a map of the full transactions provided in this payload allows us to pass them
642 // directly to core::handle_single_incoming_block() -> Blockchain::add_block(), which means we
643 // can skip the mempool for faster block propagation. Later in the function, we will erase all
644 // transactions from the relayed block.
645 pool_supplement extra_block_txs;
646 if (!make_pool_supplement_from_block_entry(arg.b.txs, blk_txids_set, /*allow_pruned=*/false, extra_block_txs))
647 {
648 LOG_ERROR_CCONTEXT
649 (
650 "Failed to parse one or more transactions in fluffy block with ID " << new_block_hash <<
651 ", dropping connection"
652 );
653
654 drop_connection(context, false, false);
655 return 1;
656 }
657
658 // try adding block to the blockchain
659 block_verification_context bvc = {};
660 const bool handle_block_res = m_core.handle_single_incoming_block(arg.b.block,
661 &new_block,
662 bvc,
663 extra_block_txs);
664
665 // handle result of attempted block add
666 if (!handle_block_res || bvc.m_verifivation_failed)
667 {
668 if (bvc.m_missing_txs)
669 {
670 // Block verification failed b/c of missing transactions, so request fluffy block again with
671 // missing transactions (including the ones newly discovered in this fluffy block). Note that
672 // PoW checking happens before missing transactions checks, so if bvc.m_missing_txs is true,
673 // then that means that we passed PoW checking, so a peer can't get us to re-request fluffy
674 // blocks for free.
675
676 // Instead of requesting missing transactions by hash like BTC,
677 // we do it by index (thanks to a suggestion from moneromooo) because
678 // we're way cooler .. and also because they're smaller than hashes.
679 std::vector<uint64_t> need_tx_indices;
680 need_tx_indices.reserve(new_block.tx_hashes.size());
681
682 // Collect need_tx_indices by polling blockchain storage and mempool storage
683 for (size_t tx_idx = 0; tx_idx < new_block.tx_hashes.size(); ++tx_idx)
684 {
685 const crypto::hash &tx_hash = new_block.tx_hashes[tx_idx];
686
687 std::vector<cryptonote::blobdata> tx_blobs;
688 std::vector<crypto::hash> missed_txs;
689
690 bool need_tx = !m_core.pool_has_tx(tx_hash);
691 need_tx = need_tx && (!m_core.get_transactions({tx_hash}, tx_blobs, missed_txs, /*pruned=*/true)
692 || !missed_txs.empty());
693
694 if (need_tx)
695 need_tx_indices.push_back(tx_idx);
696 }
697
698 // Make request form
699 MDEBUG("We are missing " << need_tx_indices.size() << " txes for this fluffy block");
700 for (auto txidx: need_tx_indices)
701 MDEBUG(" tx " << new_block.tx_hashes[txidx]);
702 NOTIFY_REQUEST_FLUFFY_MISSING_TX::request missing_tx_req;
703 missing_tx_req.block_hash = new_block_hash;
704 missing_tx_req.current_blockchain_height = arg.current_blockchain_height;
705 missing_tx_req.missing_tx_indices = std::move(need_tx_indices);
706
707 // Post NOTIFY_REQUEST_FLUFFY_MISSING_TX request to peer
708 MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_FLUFFY_MISSING_TX: missing_tx_indices.size()=" << missing_tx_req.missing_tx_indices.size() );
709 post_notify<NOTIFY_REQUEST_FLUFFY_MISSING_TX>(missing_tx_req, context);
710 }
711 else // failure for some other reason besides missing txs...
712 {
713 // drop connection and punish peer
714 LOG_PRINT_CCONTEXT_L0("Block verification failed, dropping connection");
715 drop_connection_with_score(context, bvc.m_bad_pow ? P2P_IP_FAILS_BEFORE_BLOCK : 1, false);
716 return 1;
717 }
718 }
719 else if( bvc.m_added_to_main_chain )
720 {
721 // Relay an empty block
722 arg.b.txs.clear();
723 relay_block(arg, context);
724 }
725 else if( bvc.m_marked_as_orphaned )
726 {
727 context.m_needed_objects.clear();
728 context.m_state = cryptonote_connection_context::state_synchronizing;
729 NOTIFY_REQUEST_CHAIN::request r = {};
730 context.m_expect_height = m_core.get_current_blockchain_height();
731 m_core.get_short_chain_history(r.block_ids);
732 handler_request_blocks_history( r.block_ids ); // change the limit(?), sleep(?)
733 r.prune = m_sync_pruned_blocks;
734 context.m_last_request_time = boost::posix_time::microsec_clock::universal_time();
735 context.m_expect_response = NOTIFY_RESPONSE_CHAIN_ENTRY::ID;
736 MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size() );
737 post_notify<NOTIFY_REQUEST_CHAIN>(r, context);
738 MLOG_PEER_STATE("requesting chain");
739 }
740
741 // load json & DNS checkpoints every 10min/hour respectively,
742 // and verify them with respect to what blocks we already have
743 CHECK_AND_ASSERT_MES(m_core.update_checkpoints(), 1, "One or more checkpoints loaded from json or dns conflicted with existing checkpoints.");
744
745 return 1;
746 }
747 //------------------------------------------------------------------------------------------------------------------------
748 template<class t_core>
749 int t_cryptonote_protocol_handler<t_core>::handle_request_fluffy_missing_tx(int command, NOTIFY_REQUEST_FLUFFY_MISSING_TX::request& arg, cryptonote_connection_context& context)
750 {
751 MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_FLUFFY_MISSING_TX (" << arg.missing_tx_indices.size() << " txes), block hash " << arg.block_hash);
752 if (context.m_state == cryptonote_connection_context::state_before_handshake)
753 {
754 LOG_ERROR_CCONTEXT("Requested fluffy tx before handshake, dropping connection");
755 drop_connection(context, false, false);
756 return 1;
757 }
758
759 std::vector<std::pair<cryptonote::blobdata, block>> local_blocks;
760 std::vector<cryptonote::blobdata> local_txs;
761
762 block b;
763 if (!m_core.get_block_by_hash(arg.block_hash, b))
764 {
765 LOG_ERROR_CCONTEXT("failed to find block: " << arg.block_hash << ", dropping connection");
766 drop_connection(context, false, false);
767 return 1;
768 }
769
770 std::vector<crypto::hash> txids;
771 txids.reserve(b.tx_hashes.size());
772 NOTIFY_NEW_FLUFFY_BLOCK::request fluffy_response;
773 fluffy_response.b.block = t_serializable_object_to_blob(b);
774 fluffy_response.current_blockchain_height = arg.current_blockchain_height;
775 std::vector<bool> seen(b.tx_hashes.size(), false);
776 for(auto& tx_idx: arg.missing_tx_indices)
777 {
778 if(tx_idx < b.tx_hashes.size())
779 {
780 MDEBUG(" tx " << b.tx_hashes[tx_idx]);
781 if (seen[tx_idx])
782 {
783 LOG_ERROR_CCONTEXT
784 (
785 "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX"
786 << ", request is asking for duplicate tx "
787 << ", tx index = " << tx_idx << ", block tx count " << b.tx_hashes.size()
788 << ", block_height = " << arg.current_blockchain_height
789 << ", dropping connection"
790 );
791 drop_connection(context, true, false);
792 return 1;
793 }
794 txids.push_back(b.tx_hashes[tx_idx]);
795 seen[tx_idx] = true;
796 }
797 else
798 {
799 LOG_ERROR_CCONTEXT
800 (
801 "Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX"
802 << ", request is asking for a tx whose index is out of bounds "
803 << ", tx index = " << tx_idx << ", block tx count " << b.tx_hashes.size()
804 << ", block_height = " << arg.current_blockchain_height
805 << ", dropping connection"
806 );
807
808 drop_connection(context, false, false);
809 return 1;
810 }
811 }
812
813 std::vector<cryptonote::transaction> txs;
814 std::vector<crypto::hash> missed;
815 if (!m_core.get_transactions(txids, txs, missed))
816 {
817 LOG_ERROR_CCONTEXT("Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, "
818 << "failed to get requested transactions");
819 drop_connection(context, false, false);
820 return 1;
821 }
822 if (!missed.empty() || txs.size() != txids.size())
823 {
824 LOG_ERROR_CCONTEXT("Failed to handle request NOTIFY_REQUEST_FLUFFY_MISSING_TX, "
825 << missed.size() << " requested transactions not found" << ", dropping connection");
826 drop_connection(context, false, false);
827 return 1;
828 }
829
830 for(auto& tx: txs)
831 {
832 fluffy_response.b.txs.push_back({t_serializable_object_to_blob(tx), crypto::null_hash});
833 }
834
835 MLOG_P2P_MESSAGE
836 (
837 "-->>NOTIFY_RESPONSE_FLUFFY_MISSING_TX: "
838 << ", txs.size()=" << fluffy_response.b.txs.size()
839 << ", rsp.current_blockchain_height=" << fluffy_response.current_blockchain_height
840 );
841
842 post_notify<NOTIFY_NEW_FLUFFY_BLOCK>(fluffy_response, context);
843 return 1;
844 }
845 //------------------------------------------------------------------------------------------------------------------------
846 template<class t_core>
847 int t_cryptonote_protocol_handler<t_core>::handle_notify_get_txpool_complement(int command, NOTIFY_GET_TXPOOL_COMPLEMENT::request& arg, cryptonote_connection_context& context)
848 {
849 MLOG_P2P_MESSAGE("Received NOTIFY_GET_TXPOOL_COMPLEMENT (" << arg.hashes.size() << " txes)");
850 if(context.m_state != cryptonote_connection_context::state_normal)
851 return 1;
852
853 std::vector<std::pair<cryptonote::blobdata, block>> local_blocks;
854 std::vector<cryptonote::blobdata> local_txs;
855
856 std::vector<cryptonote::blobdata> txes;
857 if (!m_core.get_txpool_complement(arg.hashes, txes))
858 {
859 LOG_ERROR_CCONTEXT("failed to get txpool complement");
860 return 1;
861 }
862
863 NOTIFY_NEW_TRANSACTIONS::request new_txes;
864 new_txes.txs = std::move(txes);
865
866 MLOG_P2P_MESSAGE
867 (
868 "-->>NOTIFY_NEW_TRANSACTIONS: "
869 << ", txs.size()=" << new_txes.txs.size()
870 );
871
872 post_notify<NOTIFY_NEW_TRANSACTIONS>(new_txes, context);
873 return 1;
874 }
875 //------------------------------------------------------------------------------------------------------------------------
876 template<class t_core>
877 int t_cryptonote_protocol_handler<t_core>::handle_notify_new_transactions(int command, NOTIFY_NEW_TRANSACTIONS::request& arg, cryptonote_connection_context& context)
878 {
879 MLOG_P2P_MESSAGE("Received NOTIFY_NEW_TRANSACTIONS (" << arg.txs.size() << " txes)");
880 std::unordered_set<blobdata> seen;
881 for (const auto &blob: arg.txs)
882 {
883 MLOGIF_P2P_MESSAGE(cryptonote::transaction tx; crypto::hash hash; bool ret = cryptonote::parse_and_validate_tx_from_blob(blob, tx, hash);, ret, "Including transaction " << hash);
884 if (seen.find(blob) != seen.end())
885 {
886 LOG_PRINT_CCONTEXT_L1("Duplicate transaction in notification, dropping connection");
887 drop_connection(context, false, false);
888 return 1;
889 }
890 seen.insert(blob);
891 }
892
893 if(context.m_state != cryptonote_connection_context::state_normal)
894 return 1;
895
896 // while syncing, core will lock for a long time, so we ignore
897 // those txes as they aren't really needed anyway, and avoid a
898 // long block before replying
899 if(!is_synchronized())
900 {
901 LOG_DEBUG_CC(context, "Received new tx while syncing, ignored");
902 return 1;
903 }
904
905 /* If the txes were received over i2p/tor, the default is to "forward"
906 with a randomized delay to further enhance the "white noise" behavior,
907 potentially making it harder for ISP-level spies to determine which
908 inbound link sent the tx. If the sender disabled "white noise" over
909 i2p/tor, then the sender is "fluffing" (to only outbound) i2p/tor
910 connections with the `dandelionpp_fluff` flag set. The receiver (hidden
911 service) will immediately fluff in that scenario (i.e. this assumes that a
912 sybil spy will be unable to link an IP to an i2p/tor connection). */
913
914 const epee::net_utils::zone zone = context.m_remote_address.get_zone();
915 relay_method tx_relay = zone == epee::net_utils::zone::public_ ?
916 relay_method::stem : relay_method::forward;
917
918 std::vector<blobdata> stem_txs{};
919 std::vector<blobdata> fluff_txs{};
920 if (arg.dandelionpp_fluff)
921 {
922 tx_relay = relay_method::fluff;
923 fluff_txs.reserve(arg.txs.size());
924 }
925 else
926 stem_txs.reserve(arg.txs.size());
927
928 for (auto& tx : arg.txs)
929 {
930 tx_verification_context tvc{};
931 if (!m_core.handle_incoming_tx(tx, tvc, tx_relay, true) && !tvc.m_no_drop_offense)
932 {
933 LOG_PRINT_CCONTEXT_L1("Tx verification failed, dropping connection");
934 drop_connection(context, false, false);
935 return 1;
936 }
937
938 switch (tvc.m_relay)
939 {
940 case relay_method::local:
941 case relay_method::stem:
942 stem_txs.push_back(std::move(tx));
943 break;
944 case relay_method::block:
945 case relay_method::fluff:
946 fluff_txs.push_back(std::move(tx));
947 break;
948 default:
949 case relay_method::forward: // not supposed to happen here
950 case relay_method::none:
951 break;
952 }
953 }
954
955 if (!stem_txs.empty())
956 {
957 //TODO: add announce usage here
958 arg.dandelionpp_fluff = false;
959 arg.txs = std::move(stem_txs);
960 relay_transactions(arg, context.m_connection_id, context.m_remote_address.get_zone(), relay_method::stem);
961 }
962 if (!fluff_txs.empty())
963 {
964 //TODO: add announce usage here
965 arg.dandelionpp_fluff = true;
966 arg.txs = std::move(fluff_txs);
967 relay_transactions(arg, context.m_connection_id, context.m_remote_address.get_zone(), relay_method::fluff);
968 }
969 return 1;
970 }
971 //------------------------------------------------------------------------------------------------------------------------
972 template<class t_core>
973 int t_cryptonote_protocol_handler<t_core>::handle_request_get_objects(int command, NOTIFY_REQUEST_GET_OBJECTS::request& arg, cryptonote_connection_context& context)
974 {
975 if (context.m_state == cryptonote_connection_context::state_before_handshake)
976 {
977 LOG_ERROR_CCONTEXT("Requested objects before handshake, dropping connection");
978 drop_connection(context, false, false);
979 return 1;
980 }
981 MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_GET_OBJECTS (" << arg.blocks.size() << " blocks)");
982 if (arg.blocks.size() > CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT)
983 {
984 LOG_ERROR_CCONTEXT(
985 "Requested objects count is too big ("
986 << arg.blocks.size() << ") expected not more then "
987 << CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT);
988 drop_connection(context, false, false);
989 return 1;
990 }
991
992 NOTIFY_RESPONSE_GET_OBJECTS::request rsp;
993 if(!m_core.handle_get_objects(arg, rsp, context))
994 {
995 LOG_ERROR_CCONTEXT("failed to handle request NOTIFY_REQUEST_GET_OBJECTS, dropping connection");
996 drop_connection(context, false, false);
997 return 1;
998 }
999 context.m_last_request_time = boost::posix_time::microsec_clock::universal_time();
1000 MLOG_P2P_MESSAGE("-->>NOTIFY_RESPONSE_GET_OBJECTS: blocks.size()="
1001 << rsp.blocks.size() << ", rsp.m_current_blockchain_height=" << rsp.current_blockchain_height
1002 << ", missed_ids.size()=" << rsp.missed_ids.size());
1003 post_notify<NOTIFY_RESPONSE_GET_OBJECTS>(rsp, context);
1004 //handler_response_blocks_now(sizeof(rsp)); // XXX
1005 //handler_response_blocks_now(200);
1006 return 1;
1007 }
1008 //------------------------------------------------------------------------------------------------------------------------
1009
1010
1011 template<class t_core>
1012 double t_cryptonote_protocol_handler<t_core>::get_avg_block_size()
1013 {
1014 CRITICAL_REGION_LOCAL(m_buffer_mutex);
1015 if (m_avg_buffer.empty()) {
1016 MWARNING("m_avg_buffer.size() == 0");
1017 return 500;
1018 }
1019 double avg = 0;
1020 for (const auto &element : m_avg_buffer) avg += element;
1021 return avg / m_avg_buffer.size();
1022 }
1023
1024 template<class t_core>
1025 int t_cryptonote_protocol_handler<t_core>::handle_response_get_objects(int command, NOTIFY_RESPONSE_GET_OBJECTS::request& arg, cryptonote_connection_context& context)
1026 {
1027 MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_GET_OBJECTS (" << arg.blocks.size() << " blocks)");
1028 MLOG_PEER_STATE("received objects");
1029
1030 boost::posix_time::ptime request_time = context.m_last_request_time;
1031 context.m_last_request_time = boost::date_time::not_a_date_time;
1032
1033 if (context.m_expect_response != NOTIFY_RESPONSE_GET_OBJECTS::ID)
1034 {
1035 LOG_ERROR_CCONTEXT("Got NOTIFY_RESPONSE_GET_OBJECTS out of the blue, dropping connection");
1036 drop_connection(context, true, false);
1037 return 1;
1038 }
1039 context.m_expect_response = 0;
1040
1041 // calculate size of request
1042 size_t size = 0;
1043 size_t blocks_size = 0;
1044 for (const auto &element : arg.blocks) {
1045 blocks_size += element.block.size();
1046 for (const auto &tx : element.txs)
1047 blocks_size += tx.blob.size();
1048 }
1049 size += blocks_size;
1050
1051 for (const auto &element : arg.missed_ids)
1052 size += sizeof(element.data);
1053
1054 size += sizeof(arg.current_blockchain_height);
1055 {
1056 CRITICAL_REGION_LOCAL(m_buffer_mutex);
1057 m_avg_buffer.push_back(size);
1058 }
1059 ++m_sync_spans_downloaded;
1060 m_sync_download_objects_size += size;
1061 MDEBUG(context << " downloaded " << size << " bytes worth of blocks");
1062
1063 /*using namespace boost::chrono;
1064 auto point = steady_clock::now();
1065 auto time_from_epoh = point.time_since_epoch();
1066 auto sec = duration_cast< seconds >( time_from_epoh ).count();*/
1067
1068 //epee::net_utils::network_throttle_manager::get_global_throttle_inreq().logger_handle_net("log/dr-monero/net/req-all.data", sec, get_avg_block_size());
1069
1070 if(arg.blocks.empty())
1071 {
1072 LOG_ERROR_CCONTEXT("sent wrong NOTIFY_HAVE_OBJECTS: no blocks");
1073 drop_connection(context, true, false);
1074 ++m_sync_bad_spans_downloaded;
1075 return 1;
1076 }
1077 if(context.m_last_response_height > arg.current_blockchain_height)
1078 {
1079 LOG_ERROR_CCONTEXT("sent wrong NOTIFY_HAVE_OBJECTS: arg.m_current_blockchain_height=" << arg.current_blockchain_height
1080 << " < m_last_response_height=" << context.m_last_response_height << ", dropping connection");
1081 drop_connection(context, false, false);
1082 ++m_sync_bad_spans_downloaded;
1083 return 1;
1084 }
1085
1086 if (arg.current_blockchain_height < context.m_remote_blockchain_height)
1087 {
1088 MINFO(context << "Claims " << arg.current_blockchain_height << ", claimed " << context.m_remote_blockchain_height << " before");
1089 hit_score(context, 1);
1090 }
1091 context.m_remote_blockchain_height = arg.current_blockchain_height;
1092 if (context.m_remote_blockchain_height > m_core.get_target_blockchain_height())
1093 m_core.set_target_blockchain_height(context.m_remote_blockchain_height);
1094
1095 std::vector<crypto::hash> block_hashes;
1096 block_hashes.reserve(arg.blocks.size());
1097 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
1098 uint64_t start_height = std::numeric_limits<uint64_t>::max();
1099 crypto::hash previous{};
1100 cryptonote::block b;
1101 for(std::size_t i = 0; i < arg.blocks.size(); ++i)
1102 {
1103 if (m_stopping)
1104 {
1105 return 1;
1106 }
1107
1108 crypto::hash block_hash;
1109 if(!parse_and_validate_block_from_blob(arg.blocks[i].block, b, block_hash))
1110 {
1111 LOG_ERROR_CCONTEXT("sent wrong block: failed to parse and validate block: "
1112 << epee::string_tools::buff_to_hex_nodelimer(arg.blocks[i].block) << ", dropping connection");
1113 drop_connection(context, false, false);
1114 ++m_sync_bad_spans_downloaded;
1115 return 1;
1116 }
1117 if (b.miner_tx.vin.size() != 1 || b.miner_tx.vin.front().type() != typeid(txin_gen))
1118 {
1119 LOG_ERROR_CCONTEXT("sent wrong block: block: miner tx does not have exactly one txin_gen input"
1120 << epee::string_tools::buff_to_hex_nodelimer(arg.blocks[i].block) << ", dropping connection");
1121 drop_connection(context, false, false);
1122 ++m_sync_bad_spans_downloaded;
1123 return 1;
1124 }
1125
1126 const auto this_height = boost::get<txin_gen>(b.miner_tx.vin[0]).height;
1127 if (context.get_expected_hash(this_height) != block_hash)
1128 {
1129 LOG_ERROR_CCONTEXT("Sent invalid chain");
1130 drop_connection(context, false, false);
1131 ++m_sync_bad_spans_downloaded;
1132 return 1;
1133 }
1134
1135 // if first block
1136 if (start_height == std::numeric_limits<uint64_t>::max())
1137 {
1138 start_height = this_height;
1139 if (start_height > context.m_expect_height)
1140 {
1141 LOG_ERROR_CCONTEXT("sent block ahead of expected height, dropping connection");
1142 drop_connection(context, false, false);
1143 ++m_sync_bad_spans_downloaded;
1144 return 1;
1145 }
1146
1147 if (this_height == 0 || context.get_expected_hash(this_height - 1) != b.prev_id)
1148 {
1149 LOG_ERROR_CCONTEXT("Sent invalid chain");
1150 drop_connection(context, false, false);
1151 ++m_sync_bad_spans_downloaded;
1152 return 1;
1153 }
1154 }
1155 else if (b.prev_id != previous)
1156 {
1157 LOG_ERROR_CCONTEXT("Sent invalid chain");
1158 drop_connection(context, false, false);
1159 ++m_sync_bad_spans_downloaded;
1160 return 1;
1161 }
1162 previous = block_hash;
1163
1164 if (start_height + i != this_height)
1165 {
1166 LOG_ERROR_CCONTEXT("Sent invalid chain");
1167 drop_connection(context, false, false);
1168 ++m_sync_bad_spans_downloaded;
1169 return 1;
1170 }
1171
1172 auto req_it = context.m_requested_objects.find(block_hash);
1173 if(req_it == context.m_requested_objects.end())
1174 {
1175 LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_GET_OBJECTS: block with id=" << epee::string_tools::pod_to_hex(get_blob_hash(arg.blocks[i].block))
1176 << " wasn't requested, dropping connection");
1177 drop_connection(context, false, false);
1178 ++m_sync_bad_spans_downloaded;
1179 return 1;
1180 }
1181 if(b.tx_hashes.size() != arg.blocks[i].txs.size())
1182 {
1183 LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_GET_OBJECTS: block with id=" << epee::string_tools::pod_to_hex(get_blob_hash(arg.blocks[i].block))
1184 << ", tx_hashes.size()=" << b.tx_hashes.size() << " mismatch with block_complete_entry.m_txs.size()=" << arg.blocks[i].txs.size() << ", dropping connection");
1185 drop_connection(context, false, false);
1186 ++m_sync_bad_spans_downloaded;
1187 return 1;
1188 }
1189
1190 context.m_requested_objects.erase(req_it);
1191 block_hashes.push_back(block_hash);
1192 }
1193
1194 if(!context.m_requested_objects.empty())
1195 {
1196 MERROR(context << "returned not all requested objects (context.m_requested_objects.size()="
1197 << context.m_requested_objects.size() << "), dropping connection");
1198 drop_connection(context, false, false);
1199 ++m_sync_bad_spans_downloaded;
1200 return 1;
1201 }
1202
1203 const bool pruned_ok = should_ask_for_pruned_data(context, start_height, arg.blocks.size(), true);
1204 if (!pruned_ok)
1205 {
1206 // if we don't want pruned data, check we did not get any
1207 for (block_complete_entry& block_entry: arg.blocks)
1208 {
1209 if (block_entry.pruned)
1210 {
1211 MERROR(context << "returned a pruned block, dropping connection");
1212 drop_connection(context, false, false);
1213 ++m_sync_bad_spans_downloaded;
1214 return 1;
1215 }
1216 if (block_entry.block_weight)
1217 {
1218 MERROR(context << "returned a block weight for a non pruned block, dropping connection");
1219 drop_connection(context, false, false);
1220 ++m_sync_bad_spans_downloaded;
1221 return 1;
1222 }
1223 for (const tx_blob_entry &tx_entry: block_entry.txs)
1224 {
1225 if (tx_entry.prunable_hash != crypto::null_hash)
1226 {
1227 MERROR(context << "returned at least one pruned object which we did not expect, dropping connection");
1228 drop_connection(context, false, false);
1229 ++m_sync_bad_spans_downloaded;
1230 return 1;
1231 }
1232 }
1233 }
1234 }
1235 else
1236 {
1237 // we accept pruned data, check that if we got some, then no weights are zero
1238 for (block_complete_entry& block_entry: arg.blocks)
1239 {
1240 if (block_entry.block_weight == 0 && block_entry.pruned)
1241 {
1242 MERROR(context << "returned at least one pruned block with 0 weight, dropping connection");
1243 drop_connection(context, false, false);
1244 ++m_sync_bad_spans_downloaded;
1245 return 1;
1246 }
1247 }
1248 }
1249
1250 {
1251 MLOG_YELLOW(el::Level::Debug, context << " Got NEW BLOCKS inside of " << __FUNCTION__ << ": size: " << arg.blocks.size()
1252 << ", blocks: " << start_height << " - " << (start_height + arg.blocks.size() - 1) <<
1253 " (pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << ")");
1254
1255 // add that new span to the block queue
1256 const boost::posix_time::time_duration dt = now - request_time;
1257 const float rate = size * 1e6 / (dt.total_microseconds() + 1);
1258 MDEBUG(context << " adding span: " << arg.blocks.size() << " at height " << start_height << ", " << dt.total_microseconds()/1e6 << " seconds, " << (rate/1024) << " kB/s, size now " << (m_block_queue.get_data_size() + blocks_size) / 1048576.f << " MB");
1259 m_block_queue.add_blocks(start_height, arg.blocks, context.m_connection_id, context.m_remote_address, rate, blocks_size);
1260
1261 const crypto::hash last_block_hash = cryptonote::get_block_hash(b);
1262 context.m_last_known_hash = last_block_hash;
1263
1264 if (!m_core.get_test_drop_download() || !m_core.get_test_drop_download_height()) { // DISCARD BLOCKS for testing
1265 return 1;
1266 }
1267 }
1268
1269 try_add_next_blocks(context);
1270 return 1;
1271 }
1272
1273 // Get an estimate for the remaining sync time from given current to target blockchain height, in seconds
1274 template<class t_core>
1275 uint64_t t_cryptonote_protocol_handler<t_core>::get_estimated_remaining_sync_seconds(uint64_t current_blockchain_height, uint64_t target_blockchain_height)
1276 {
1277 // The average sync speed varies so much, even averaged over quite long time periods like 10 minutes,
1278 // that using some sliding window would be difficult to implement without often leading to bad estimates.
1279 // The simplest strategy - always average sync speed over the maximum available interval i.e. since sync
1280 // started at all (from "m_sync_start_time" and "m_sync_start_height") - gives already useful results
1281 // and seems to be quite robust. Some quite special cases like "Internet connection suddenly becoming
1282 // much faster after syncing already a long time, and staying fast" are not well supported however.
1283
1284 if (target_blockchain_height <= current_blockchain_height)
1285 {
1286 // Syncing stuck, or other special circumstance: Avoid errors, simply give back 0
1287 return 0;
1288 }
1289
1290 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
1291 const boost::posix_time::time_duration sync_time = now - m_sync_start_time;
1292 cryptonote::network_type nettype = m_core.get_nettype();
1293
1294 // Don't simply use remaining number of blocks for the estimate but "sync weight" as provided by
1295 // "cumulative_block_sync_weight" which knows about strongly varying Monero mainnet block sizes
1296 uint64_t synced_weight = tools::cumulative_block_sync_weight(nettype, m_sync_start_height, current_blockchain_height - m_sync_start_height);
1297 float us_per_weight = (float)sync_time.total_microseconds() / (float)synced_weight;
1298 uint64_t remaining_weight = tools::cumulative_block_sync_weight(nettype, current_blockchain_height, target_blockchain_height - current_blockchain_height);
1299 float remaining_us = us_per_weight * (float)remaining_weight;
1300 return (uint64_t)(remaining_us / 1e6);
1301 }
1302
1303 // Return a textual remaining sync time estimate, or the empty string if waiting period not yet over
1304 template<class t_core>
1305 std::string t_cryptonote_protocol_handler<t_core>::get_periodic_sync_estimate(uint64_t current_blockchain_height, uint64_t target_blockchain_height)
1306 {
1307 std::string text = "";
1308 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
1309 boost::posix_time::time_duration period_sync_time = now - m_period_start_time;
1310 if (period_sync_time > boost::posix_time::minutes(2))
1311 {
1312 // Period is over, time to report another estimate
1313 uint64_t remaining_seconds = get_estimated_remaining_sync_seconds(current_blockchain_height, target_blockchain_height);
1314 text = tools::get_human_readable_timespan(remaining_seconds);
1315
1316 // Start the new period
1317 m_period_start_time = now;
1318 }
1319 return text;
1320 }
1321
1322 template<class t_core>
1323 int t_cryptonote_protocol_handler<t_core>::try_add_next_blocks(cryptonote_connection_context& context)
1324 {
1325 bool force_next_span = false;
1326
1327 {
1328 // We try to lock the sync lock. If we can, it means no other thread is
1329 // currently adding blocks, so we do that for as long as we can from the
1330 // block queue. Then, we go back to download.
1331 const boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock};
1332 if (!sync.owns_lock())
1333 {
1334 MINFO(context << "Failed to lock m_sync_lock, going back to download");
1335 goto skip;
1336 }
1337 MDEBUG(context << " lock m_sync_lock, adding blocks to chain...");
1338 MLOG_PEER_STATE("adding blocks");
1339
1340 {
1341 m_core.pause_mine();
1342 m_add_timer.resume();
1343 bool starting = true;
1344 epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([this, &starting]() {
1345 m_add_timer.pause();
1346 m_core.resume_mine();
1347 if (!starting)
1348 m_last_add_end_time = tools::get_tick_count();
1349 });
1350 m_sync_start_time = boost::posix_time::microsec_clock::universal_time();
1351 m_sync_start_height = m_core.get_current_blockchain_height();
1352 m_period_start_time = m_sync_start_time;
1353
1354 while (1)
1355 {
1356 const uint64_t previous_height = m_core.get_current_blockchain_height();
1357 uint64_t start_height;
1358 std::vector<cryptonote::block_complete_entry> blocks;
1359 boost::uuids::uuid span_connection_id;
1360 epee::net_utils::network_address span_origin;
1361 if (!m_block_queue.get_next_span(start_height, blocks, span_connection_id, span_origin))
1362 {
1363 MDEBUG(context << " no next span found, going back to download");
1364 break;
1365 }
1366
1367 if (blocks.empty())
1368 {
1369 MERROR(context << "Next span has no blocks");
1370 m_block_queue.remove_spans(span_connection_id, start_height);
1371 continue;
1372 }
1373
1374 MDEBUG(context << " next span in the queue has blocks " << start_height << "-" << (start_height + blocks.size() - 1)
1375 << ", we need " << previous_height);
1376
1377 block new_block;
1378 crypto::hash last_block_hash;
1379 if (!parse_and_validate_block_from_blob(blocks.back().block, new_block, last_block_hash))
1380 {
1381 MERROR(context << "Failed to parse block, but it should already have been parsed");
1382 m_block_queue.remove_spans(span_connection_id, start_height);
1383 continue;
1384 }
1385 if (m_core.have_block(last_block_hash))
1386 {
1387 const uint64_t subchain_height = start_height + blocks.size();
1388 LOG_DEBUG_CC(context, "These are old blocks, ignoring: blocks " << start_height << " - " << (subchain_height-1) << ", blockchain height " << m_core.get_current_blockchain_height());
1389 m_block_queue.remove_spans(span_connection_id, start_height);
1390 ++m_sync_old_spans_downloaded;
1391 continue;
1392 }
1393 if (!parse_and_validate_block_from_blob(blocks.front().block, new_block))
1394 {
1395 MERROR(context << "Failed to parse block, but it should already have been parsed");
1396 m_block_queue.remove_spans(span_connection_id, start_height);
1397 continue;
1398 }
1399 bool parent_known = m_core.have_block(new_block.prev_id);
1400 if (!parent_known)
1401 {
1402 const std::uint64_t confirmed_height = m_block_queue.have_height(new_block.prev_id);
1403 if (confirmed_height != std::numeric_limits<std::uint64_t>::max() && confirmed_height + 1 != start_height)
1404 {
1405 MERROR(context << "Found incorrect height for " << new_block.prev_id << " provided by " << span_connection_id);
1406 drop_connection(span_connection_id);
1407 return 1;
1408 }
1409
1410 // it could be:
1411 // - later in the current chain
1412 // - later in an alt chain
1413 // - orphan
1414 // if it was requested, then it'll be resolved later, otherwise it's an orphan
1415 bool parent_requested = m_block_queue.requested(new_block.prev_id);
1416 if (!parent_requested)
1417 {
1418 // we might be able to ask for that block directly, as we now can request out of order,
1419 // otherwise we continue out of order, unless this block is the one we need, in which
1420 // case we request block hashes, though it might be safer to disconnect ?
1421 if (start_height > previous_height)
1422 {
1423 if (should_drop_connection(context, get_next_needed_pruning_stripe().first))
1424 {
1425 MDEBUG(context << "Got block with unknown parent which was not requested, but peer does not have that block - dropping connection");
1426 if (!context.m_is_income)
1427 m_p2p->add_used_stripe_peer(context);
1428 drop_connection(context, false, true);
1429 return 1;
1430 }
1431 MDEBUG(context << "Got block with unknown parent which was not requested, but peer does not have that block - back to download");
1432
1433 goto skip;
1434 }
1435
1436 // this can happen if a connection was sicced onto a late span, if it did not have those blocks,
1437 // since we don't know that at the sic time
1438 LOG_ERROR_CCONTEXT("Got block with unknown parent which was not requested - querying block hashes");
1439 m_block_queue.remove_spans(span_connection_id, start_height);
1440 context.m_needed_objects.clear();
1441 context.m_last_response_height = 0;
1442 goto skip;
1443 }
1444
1445 // parent was requested, so we wait for it to be retrieved
1446 MINFO(context << " parent was requested, we'll get back to it");
1447 break;
1448 }
1449
1450 const boost::posix_time::ptime start = boost::posix_time::microsec_clock::universal_time();
1451
1452 if (starting)
1453 {
1454 starting = false;
1455 if (m_last_add_end_time)
1456 {
1457 const uint64_t tnow = tools::get_tick_count();
1458 const uint64_t ns = tools::ticks_to_ns(tnow - m_last_add_end_time);
1459 MINFO("Restarting adding block after idle for " << ns/1e9 << " seconds");
1460 }
1461 }
1462
1463 std::vector<block> pblocks;
1464 if (!m_core.prepare_handle_incoming_blocks(blocks, pblocks))
1465 {
1466 LOG_ERROR_CCONTEXT("Failure in prepare_handle_incoming_blocks");
1467 drop_connections(span_origin);
1468 return 1;
1469 }
1470 if (!pblocks.empty() && pblocks.size() != blocks.size())
1471 {
1472 m_core.cleanup_handle_incoming_blocks();
1473 LOG_ERROR_CCONTEXT("Internal error: blocks.size() != block_entry.txs.size()");
1474 return 1;
1475 }
1476
1477 uint64_t block_process_time_full = 0, transactions_process_time_full = 0;
1478 size_t num_txs = 0, blockidx = 0;
1479 for(const block_complete_entry& block_entry: blocks)
1480 {
1481 if (m_stopping)
1482 {
1483 m_core.cleanup_handle_incoming_blocks();
1484 return 1;
1485 }
1486
1487 // process transactions
1488 TIME_MEASURE_START(transactions_process_time);
1489 num_txs += block_entry.txs.size();
1490
1491 pool_supplement block_txs;
1492 if (!make_full_pool_supplement_from_block_entry(block_entry, block_txs))
1493 {
1494 drop_connections(span_origin);
1495 if (!m_p2p->for_connection(span_connection_id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t f)->bool{
1496 LOG_ERROR_CCONTEXT("transaction parsing failed for 1 or more txs in NOTIFY_RESPONSE_GET_OBJECTS,"
1497 "dropping connections");
1498 drop_connection(context, false, true);
1499 return 1;
1500 }))
1501 LOG_ERROR_CCONTEXT("span connection id not found");
1502
1503 if (!m_core.cleanup_handle_incoming_blocks())
1504 {
1505 LOG_PRINT_CCONTEXT_L0("Failure in cleanup_handle_incoming_blocks");
1506 return 1;
1507 }
1508 // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it
1509 m_block_queue.remove_spans(span_connection_id, start_height);
1510 return 1;
1511 }
1512 TIME_MEASURE_FINISH(transactions_process_time);
1513 transactions_process_time_full += transactions_process_time;
1514
1515 // process block
1516
1517 TIME_MEASURE_START(block_process_time);
1518 block_verification_context bvc = {};
1519
1520 m_core.handle_incoming_block(block_entry.block,
1521 pblocks.empty() ? NULL : &pblocks[blockidx],
1522 bvc,
1523 block_txs,
1524 false); // <--- process block
1525
1526 if(bvc.m_verifivation_failed)
1527 {
1528 drop_connections(span_origin);
1529 if (!m_p2p->for_connection(span_connection_id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t f)->bool{
1530 LOG_PRINT_CCONTEXT_L1("Block verification failed, dropping connection");
1531 drop_connection_with_score(context, bvc.m_bad_pow ? P2P_IP_FAILS_BEFORE_BLOCK : 1, true);
1532 return 1;
1533 }))
1534 LOG_ERROR_CCONTEXT("span connection id not found");
1535
1536 if (!m_core.cleanup_handle_incoming_blocks())
1537 {
1538 LOG_PRINT_CCONTEXT_L0("Failure in cleanup_handle_incoming_blocks");
1539 return 1;
1540 }
1541
1542 // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it
1543 m_block_queue.remove_spans(span_connection_id, start_height);
1544 return 1;
1545 }
1546 if(bvc.m_marked_as_orphaned)
1547 {
1548 drop_connections(span_origin);
1549 if (!m_p2p->for_connection(span_connection_id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t f)->bool{
1550 LOG_PRINT_CCONTEXT_L1("Block received at sync phase was marked as orphaned, dropping connection");
1551 drop_connection(context, true, true);
1552 return 1;
1553 }))
1554 LOG_ERROR_CCONTEXT("span connection id not found");
1555
1556 if (!m_core.cleanup_handle_incoming_blocks())
1557 {
1558 LOG_PRINT_CCONTEXT_L0("Failure in cleanup_handle_incoming_blocks");
1559 return 1;
1560 }
1561
1562 // in case the peer had dropped beforehand, remove the span anyway so other threads can wake up and get it
1563 m_block_queue.remove_spans(span_connection_id, start_height);
1564 return 1;
1565 }
1566
1567 TIME_MEASURE_FINISH(block_process_time);
1568 block_process_time_full += block_process_time;
1569 ++blockidx;
1570
1571 } // each download block
1572
1573 MDEBUG(context << "Block process time (" << blocks.size() << " blocks, " << num_txs << " txs): " << block_process_time_full + transactions_process_time_full << " (" << transactions_process_time_full << "/" << block_process_time_full << ") ms");
1574
1575 if (!m_core.cleanup_handle_incoming_blocks())
1576 {
1577 LOG_PRINT_CCONTEXT_L0("Failure in cleanup_handle_incoming_blocks");
1578 return 1;
1579 }
1580
1581 m_block_queue.remove_spans(span_connection_id, start_height);
1582
1583 const uint64_t current_blockchain_height = m_core.get_current_blockchain_height();
1584 if (current_blockchain_height > previous_height)
1585 {
1586 const uint64_t target_blockchain_height = m_core.get_target_blockchain_height();
1587 const boost::posix_time::time_duration dt = boost::posix_time::microsec_clock::universal_time() - start;
1588 std::string progress_message = "";
1589 if (current_blockchain_height < target_blockchain_height)
1590 {
1591 uint64_t completion_percent = (current_blockchain_height * 100 / target_blockchain_height);
1592 if (completion_percent == 100) // never show 100% if not actually up to date
1593 completion_percent = 99;
1594 progress_message = " (" + std::to_string(completion_percent) + "%, "
1595 + std::to_string(target_blockchain_height - current_blockchain_height) + " left";
1596 std::string time_message = get_periodic_sync_estimate(current_blockchain_height, target_blockchain_height);
1597 if (!time_message.empty())
1598 {
1599 uint64_t total_blocks_to_sync = target_blockchain_height - m_sync_start_height;
1600 uint64_t total_blocks_synced = current_blockchain_height - m_sync_start_height;
1601 progress_message += ", " + std::to_string(total_blocks_synced * 100 / total_blocks_to_sync) + "% of total synced";
1602 progress_message += ", estimated " + time_message + " left";
1603 }
1604 progress_message += ")";
1605 }
1606 const uint32_t previous_stripe = tools::get_pruning_stripe(previous_height, target_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
1607 const uint32_t current_stripe = tools::get_pruning_stripe(current_blockchain_height, target_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
1608 std::string timing_message = "";
1609 if (ELPP->vRegistry()->allowed(el::Level::Info, "sync-info"))
1610 timing_message = std::string(" (") + std::to_string(dt.total_microseconds()/1e6) + " sec, "
1611 + std::to_string((current_blockchain_height - previous_height) * 1e6 / dt.total_microseconds())
1612 + " blocks/sec), " + std::to_string(m_block_queue.get_data_size() / 1048576.f) + " MB queued in "
1613 + std::to_string(m_block_queue.get_num_filled_spans()) + " spans, stripe "
1614 + std::to_string(previous_stripe) + " -> " + std::to_string(current_stripe);
1615 if (ELPP->vRegistry()->allowed(el::Level::Debug, "sync-info"))
1616 timing_message += std::string(": ") + m_block_queue.get_overview(current_blockchain_height);
1617 MGINFO_YELLOW("Synced " << current_blockchain_height << "/" << target_blockchain_height
1618 << progress_message << timing_message);
1619 if (previous_stripe != current_stripe)
1620 notify_new_stripe(context, current_stripe);
1621 }
1622 }
1623 }
1624
1625 MLOG_PEER_STATE("stopping adding blocks");
1626
1627 if (should_download_next_span(context, false))
1628 {
1629 force_next_span = true;
1630 }
1631 else if (should_drop_connection(context, get_next_needed_pruning_stripe().first))
1632 {
1633 if (!context.m_is_income)
1634 {
1635 m_p2p->add_used_stripe_peer(context);
1636 drop_connection(context, false, false);
1637 }
1638 return 1;
1639 }
1640 }
1641
1642 skip:
1643 if (!request_missing_objects(context, true, force_next_span))
1644 {
1645 LOG_ERROR_CCONTEXT("Failed to request missing objects, dropping connection");
1646 drop_connection(context, false, false);
1647 return 1;
1648 }
1649 return 1;
1650 }
1651 //------------------------------------------------------------------------------------------------------------------------
1652 template<class t_core>
1653 void t_cryptonote_protocol_handler<t_core>::notify_new_stripe(cryptonote_connection_context& cntxt, uint32_t stripe)
1654 {
1655 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool
1656 {
1657 if (cntxt.m_connection_id == context.m_connection_id)
1658 return true;
1659 if (context.m_state == cryptonote_connection_context::state_normal)
1660 {
1661 const uint32_t peer_stripe = tools::get_pruning_stripe(context.m_pruning_seed);
1662 if (stripe && peer_stripe && peer_stripe != stripe)
1663 return true;
1664 context.m_new_stripe_notification = true;
1665 LOG_PRINT_CCONTEXT_L2("requesting callback");
1666 ++context.m_callback_request_count;
1667 m_p2p->request_callback(context);
1668 MLOG_PEER_STATE("requesting callback");
1669 }
1670 return true;
1671 });
1672 }
1673 //------------------------------------------------------------------------------------------------------------------------
1674 template<class t_core>
1675 bool t_cryptonote_protocol_handler<t_core>::on_idle()
1676 {
1677 m_idle_peer_kicker.do_call(boost::bind(&t_cryptonote_protocol_handler<t_core>::kick_idle_peers, this));
1678 m_standby_checker.do_call(boost::bind(&t_cryptonote_protocol_handler<t_core>::check_standby_peers, this));
1679 m_sync_search_checker.do_call(boost::bind(&t_cryptonote_protocol_handler<t_core>::update_sync_search, this));
1680 return m_core.on_idle();
1681 }
1682 //------------------------------------------------------------------------------------------------------------------------
1683 template<class t_core>
1684 bool t_cryptonote_protocol_handler<t_core>::kick_idle_peers()
1685 {
1686 MTRACE("Checking for idle peers...");
1687 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool
1688 {
1689 if (context.m_state == cryptonote_connection_context::state_synchronizing && context.m_last_request_time != boost::date_time::not_a_date_time)
1690 {
1691 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
1692 const boost::posix_time::time_duration dt = now - context.m_last_request_time;
1693 const auto ms = dt.total_microseconds();
1694 if (ms > IDLE_PEER_KICK_TIME || (context.m_expect_response && ms > NON_RESPONSIVE_PEER_KICK_TIME))
1695 {
1696 context.m_idle_peer_notification = true;
1697 LOG_PRINT_CCONTEXT_L2("requesting callback");
1698 ++context.m_callback_request_count;
1699 m_p2p->request_callback(context);
1700 MLOG_PEER_STATE("requesting callback");
1701 }
1702 }
1703 return true;
1704 });
1705
1706 return true;
1707 }
1708 //------------------------------------------------------------------------------------------------------------------------
1709 template<class t_core>
1710 bool t_cryptonote_protocol_handler<t_core>::update_sync_search()
1711 {
1712 const uint64_t target = m_core.get_target_blockchain_height();
1713 const uint64_t height = m_core.get_current_blockchain_height();
1714 if (target > height) // if we're not synced yet, don't do it
1715 return true;
1716
1717 MTRACE("Checking for outgoing syncing peers...");
1718 std::unordered_map<epee::net_utils::zone, unsigned> n_syncing, n_synced;
1719 std::unordered_map<epee::net_utils::zone, boost::uuids::uuid> last_synced_peer_id;
1720 std::vector<epee::net_utils::zone> zones;
1721 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool
1722 {
1723 if (!peer_id || context.m_is_income) // only consider connected outgoing peers
1724 return true;
1725
1726 const epee::net_utils::zone zone = context.m_remote_address.get_zone();
1727 if (n_syncing.find(zone) == n_syncing.end())
1728 {
1729 n_syncing[zone] = 0;
1730 n_synced[zone] = 0;
1731 last_synced_peer_id[zone] = boost::uuids::nil_uuid();
1732 zones.push_back(zone);
1733 }
1734
1735 if (context.m_state == cryptonote_connection_context::state_synchronizing)
1736 ++n_syncing[zone];
1737 if (context.m_state == cryptonote_connection_context::state_normal)
1738 {
1739 ++n_synced[zone];
1740 if (!context.m_anchor)
1741 last_synced_peer_id[zone] = context.m_connection_id;
1742 }
1743 return true;
1744 });
1745
1746 for (const auto& zone : zones)
1747 {
1748 const unsigned int max_out_peers = get_max_out_peers(zone);
1749 MTRACE("[" << epee::net_utils::zone_to_string(zone) << "] " << n_syncing[zone] << " syncing, " << n_synced[zone] << " synced, " << max_out_peers << " max out peers");
1750
1751 // if we're at max out peers, and not enough are syncing, drop the last sync'd non-anchor
1752 if (n_synced[zone] + n_syncing[zone] >= max_out_peers && n_syncing[zone] < P2P_DEFAULT_SYNC_SEARCH_CONNECTIONS_COUNT && last_synced_peer_id[zone] != boost::uuids::nil_uuid())
1753 {
1754 if (!m_p2p->for_connection(last_synced_peer_id[zone], [&](cryptonote_connection_context& ctx, nodetool::peerid_type peer_id, uint32_t f)->bool{
1755 MINFO(ctx << "dropping synced peer, " << n_syncing[zone] << " syncing, " << n_synced[zone] << " synced, " << max_out_peers << " max out peers");
1756 drop_connection(ctx, false, false);
1757 return true;
1758 }))
1759 MDEBUG("Failed to find peer we wanted to drop");
1760 }
1761 }
1762
1763 return true;
1764 }
1765 //------------------------------------------------------------------------------------------------------------------------
1766 template<class t_core>
1767 bool t_cryptonote_protocol_handler<t_core>::check_standby_peers()
1768 {
1769 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool
1770 {
1771 if (context.m_state == cryptonote_connection_context::state_standby)
1772 {
1773 LOG_PRINT_CCONTEXT_L2("requesting callback");
1774 ++context.m_callback_request_count;
1775 m_p2p->request_callback(context);
1776 }
1777 return true;
1778 });
1779 return true;
1780 }
1781 //------------------------------------------------------------------------------------------------------------------------
1782 template<class t_core>
1783 int t_cryptonote_protocol_handler<t_core>::handle_request_chain(int command, NOTIFY_REQUEST_CHAIN::request& arg, cryptonote_connection_context& context)
1784 {
1785 MLOG_P2P_MESSAGE("Received NOTIFY_REQUEST_CHAIN (" << arg.block_ids.size() << " blocks");
1786 if (context.m_state == cryptonote_connection_context::state_before_handshake)
1787 {
1788 LOG_ERROR_CCONTEXT("Requested chain before handshake, dropping connection");
1789 drop_connection(context, false, false);
1790 return 1;
1791 }
1792 NOTIFY_RESPONSE_CHAIN_ENTRY::request r;
1793 if(!m_core.find_blockchain_supplement(arg.block_ids, !arg.prune, r))
1794 {
1795 LOG_ERROR_CCONTEXT("Failed to handle NOTIFY_REQUEST_CHAIN.");
1796 return 1;
1797 }
1798 if (r.m_block_ids.size() >= 2)
1799 {
1800 cryptonote::block b;
1801 if (!m_core.get_block_by_hash(r.m_block_ids[1], b))
1802 {
1803 LOG_ERROR_CCONTEXT("Failed to handle NOTIFY_REQUEST_CHAIN: first block not found");
1804 return 1;
1805 }
1806 r.first_block = cryptonote::block_to_blob(b);
1807 }
1808 MLOG_P2P_MESSAGE("-->>NOTIFY_RESPONSE_CHAIN_ENTRY: m_start_height=" << r.start_height << ", m_total_height=" << r.total_height << ", m_block_ids.size()=" << r.m_block_ids.size());
1809 post_notify<NOTIFY_RESPONSE_CHAIN_ENTRY>(r, context);
1810 return 1;
1811 }
1812 //------------------------------------------------------------------------------------------------------------------------
1813 template<class t_core>
1814 bool t_cryptonote_protocol_handler<t_core>::should_download_next_span(cryptonote_connection_context& context, bool standby)
1815 {
1816 std::vector<crypto::hash> hashes;
1817 boost::posix_time::ptime request_time;
1818 boost::uuids::uuid connection_id;
1819 bool filled;
1820
1821 const uint64_t blockchain_height = m_core.get_current_blockchain_height();
1822 if (context.m_remote_blockchain_height <= blockchain_height)
1823 return false;
1824 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
1825 const bool has_next_block = tools::has_unpruned_block(blockchain_height, context.m_remote_blockchain_height, context.m_pruning_seed);
1826 if (has_next_block)
1827 {
1828 if (!m_block_queue.has_next_span(blockchain_height, filled, request_time, connection_id))
1829 {
1830 MDEBUG(context << " we should download it as no peer reserved it");
1831 return true;
1832 }
1833 if (!filled)
1834 {
1835 const long dt = (now - request_time).total_microseconds();
1836 if (dt >= REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD)
1837 {
1838 MDEBUG(context << " we should download it as it's not been received yet after " << dt/1e6);
1839 return true;
1840 }
1841
1842 // in standby, be ready to double download early since we're idling anyway
1843 // let the fastest peer trigger first
1844 const double dl_speed = context.m_max_speed_down;
1845 if (standby && dt >= REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY && dl_speed > 0)
1846 {
1847 bool download = false;
1848 if (m_p2p->for_connection(connection_id, [&](cryptonote_connection_context& ctx, nodetool::peerid_type peer_id, uint32_t f)->bool{
1849 const time_t nowt = time(NULL);
1850 const time_t time_since_last_recv = nowt - ctx.m_last_recv;
1851 const float last_activity = std::min((float)time_since_last_recv, dt/1e6f);
1852 const bool stalled = last_activity > LAST_ACTIVITY_STALL_THRESHOLD;
1853 if (stalled)
1854 {
1855 MDEBUG(context << " we should download it as the downloading peer is stalling for " << nowt - ctx.m_last_recv << " seconds");
1856 download = true;
1857 return true;
1858 }
1859
1860 // estimate the standby peer can give us 80% of its max speed
1861 // and let it download if that speed is > N times as fast as the current one
1862 // N starts at 10 after REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY,
1863 // decreases to 1.25 at REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD,
1864 // so that at times goes without the download being done, a retry becomes easier
1865 const float max_multiplier = 10.f;
1866 const float min_multiplier = 1.25f;
1867 float multiplier = max_multiplier;
1868 if (dt >= REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY)
1869 {
1870 multiplier = max_multiplier - (dt-REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY) * (max_multiplier - min_multiplier) / (REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD - REQUEST_NEXT_SCHEDULED_SPAN_THRESHOLD_STANDBY);
1871 multiplier = std::min(max_multiplier, std::max(min_multiplier, multiplier));
1872 }
1873 if (dl_speed * .8f > ctx.m_current_speed_down * multiplier)
1874 {
1875 MDEBUG(context << " we should download it as we are substantially faster (" << dl_speed << " vs "
1876 << ctx.m_current_speed_down << ", multiplier " << multiplier << " after " << dt/1e6 << " seconds)");
1877 download = true;
1878 return true;
1879 }
1880 return true;
1881 }))
1882 {
1883 if (download)
1884 return true;
1885 }
1886 else
1887 {
1888 MWARNING(context << " we should download it as the downloading peer is unexpectedly not known to us");
1889 return true;
1890 }
1891 }
1892 }
1893 }
1894
1895 return false;
1896 }
1897 //------------------------------------------------------------------------------------------------------------------------
1898 template<class t_core>
1899 bool t_cryptonote_protocol_handler<t_core>::should_drop_connection(cryptonote_connection_context& context, uint32_t next_stripe)
1900 {
1901 if (context.m_anchor)
1902 {
1903 MDEBUG(context << "This is an anchor peer, not dropping");
1904 return false;
1905 }
1906 if (context.m_pruning_seed == 0)
1907 {
1908 MDEBUG(context << "This peer is not striped, not dropping");
1909 return false;
1910 }
1911
1912 const uint32_t peer_stripe = tools::get_pruning_stripe(context.m_pruning_seed);
1913 if (next_stripe == peer_stripe)
1914 {
1915 MDEBUG(context << "This peer has needed stripe " << peer_stripe << ", not dropping");
1916 return false;
1917 }
1918 const uint32_t local_stripe = tools::get_pruning_stripe(m_core.get_blockchain_pruning_seed());
1919 if (m_sync_pruned_blocks && local_stripe && next_stripe != local_stripe)
1920 {
1921 MDEBUG(context << "We can sync pruned blocks off this peer, not dropping");
1922 return false;
1923 }
1924
1925 if (!context.m_needed_objects.empty())
1926 {
1927 const uint64_t next_available_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1;
1928 if (tools::has_unpruned_block(next_available_block_height, context.m_remote_blockchain_height, context.m_pruning_seed))
1929 {
1930 MDEBUG(context << "This peer has unpruned next block at height " << next_available_block_height << ", not dropping");
1931 return false;
1932 }
1933 }
1934
1935 if (next_stripe > 0)
1936 {
1937 unsigned int n_out_peers = 0, n_peers_on_next_stripe = 0;
1938 m_p2p->for_each_connection([&](cryptonote_connection_context& ctx, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{
1939 if (!ctx.m_is_income)
1940 ++n_out_peers;
1941 if (ctx.m_state >= cryptonote_connection_context::state_synchronizing && tools::get_pruning_stripe(ctx.m_pruning_seed) == next_stripe)
1942 ++n_peers_on_next_stripe;
1943 return true;
1944 });
1945 // TODO: investigate tallying by zone and comparing to max out peers by zone
1946 const unsigned int max_out_peers = get_max_out_peers(epee::net_utils::zone::public_);
1947 const uint32_t distance = (peer_stripe + (1<<CRYPTONOTE_PRUNING_LOG_STRIPES) - next_stripe) % (1<<CRYPTONOTE_PRUNING_LOG_STRIPES);
1948 if ((n_out_peers >= max_out_peers && n_peers_on_next_stripe == 0) || (distance > 1 && n_peers_on_next_stripe <= 2) || distance > 2)
1949 {
1950 MDEBUG(context << "we want seed " << next_stripe << ", and either " << n_out_peers << " is at max out peers ("
1951 << max_out_peers << ") or distance " << distance << " from " << next_stripe << " to " << peer_stripe <<
1952 " is too large and we have only " << n_peers_on_next_stripe << " peers on next seed, dropping connection to make space");
1953 return true;
1954 }
1955 }
1956 MDEBUG(context << "End of checks, not dropping");
1957 return false;
1958 }
1959 //------------------------------------------------------------------------------------------------------------------------
1960 template<class t_core>
1961 size_t t_cryptonote_protocol_handler<t_core>::skip_unneeded_hashes(cryptonote_connection_context& context, bool check_block_queue) const
1962 {
1963 // take out blocks we already have
1964 size_t skip = 0;
1965 while (skip < context.m_needed_objects.size() && (m_core.have_block(context.m_needed_objects[skip].first) || (check_block_queue && m_block_queue.have(context.m_needed_objects[skip].first))))
1966 {
1967 // if we're popping the last hash, record it so we can ask again from that hash,
1968 // this prevents never being able to progress on peers we get old hash lists from
1969 if (skip + 1 == context.m_needed_objects.size())
1970 context.m_last_known_hash = context.m_needed_objects[skip].first;
1971 ++skip;
1972 }
1973 if (skip > 0)
1974 {
1975 MDEBUG(context << "skipping " << skip << "/" << context.m_needed_objects.size() << " blocks");
1976 context.m_needed_objects = std::vector<std::pair<crypto::hash, uint64_t>>(context.m_needed_objects.begin() + skip, context.m_needed_objects.end());
1977 }
1978 return skip;
1979 }
1980 //------------------------------------------------------------------------------------------------------------------------
1981 template<class t_core>
1982 bool t_cryptonote_protocol_handler<t_core>::should_ask_for_pruned_data(cryptonote_connection_context& context, uint64_t first_block_height, uint64_t nblocks, bool check_block_weights) const
1983 {
1984 if (!m_sync_pruned_blocks)
1985 return false;
1986 if (!m_core.is_within_compiled_block_hash_area(first_block_height + nblocks - 1))
1987 return false;
1988 const uint32_t local_stripe = tools::get_pruning_stripe(m_core.get_blockchain_pruning_seed());
1989 if (local_stripe == 0)
1990 return false;
1991 // don't request pre-bulletprooof pruned blocks, we can't reconstruct their weight (yet)
1992 static const uint64_t bp_fork_height = m_core.get_earliest_ideal_height_for_version(HF_VERSION_SMALLER_BP + 1);
1993 if (first_block_height < bp_fork_height)
1994 return false;
1995 // assumes the span size is less or equal to the stripe size
1996 bool full_data_needed = tools::get_pruning_stripe(first_block_height, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES) == local_stripe
1997 || tools::get_pruning_stripe(first_block_height + nblocks - 1, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES) == local_stripe;
1998 if (full_data_needed)
1999 return false;
2000 if (check_block_weights && !m_core.has_block_weights(first_block_height, nblocks))
2001 return false;
2002 return true;
2003 }
2004 //------------------------------------------------------------------------------------------------------------------------
2005 template<class t_core>
2006 bool t_cryptonote_protocol_handler<t_core>::request_missing_objects(cryptonote_connection_context& context, bool check_having_blocks, bool force_next_span)
2007 {
2008 // flush stale spans
2009 std::set<boost::uuids::uuid> live_connections;
2010 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{
2011 live_connections.insert(context.m_connection_id);
2012 return true;
2013 });
2014 m_block_queue.flush_stale_spans(live_connections);
2015
2016 // if we don't need to get next span, and the block queue is full enough, wait a bit
2017 if (!force_next_span)
2018 {
2019 do
2020 {
2021 size_t nspans = m_block_queue.get_num_filled_spans();
2022 size_t size = m_block_queue.get_data_size();
2023 const uint64_t bc_height = m_core.get_current_blockchain_height();
2024 const auto next_needed_pruning_stripe = get_next_needed_pruning_stripe();
2025 const uint32_t add_stripe = tools::get_pruning_stripe(bc_height, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
2026 const uint32_t peer_stripe = tools::get_pruning_stripe(context.m_pruning_seed);
2027 const uint32_t local_stripe = tools::get_pruning_stripe(m_core.get_blockchain_pruning_seed());
2028 const size_t block_queue_size_threshold = m_block_download_max_size ? m_block_download_max_size : BLOCK_QUEUE_SIZE_THRESHOLD;
2029 bool queue_proceed = nspans < BLOCK_QUEUE_NSPANS_THRESHOLD || size < block_queue_size_threshold;
2030 // get rid of blocks we already requested, or already have
2031 if (skip_unneeded_hashes(context, true) && context.m_needed_objects.empty() && context.m_num_requested == 0)
2032 {
2033 if (context.m_remote_blockchain_height > m_block_queue.get_next_needed_height(bc_height))
2034 {
2035 MERROR(context << "Nothing we can request from this peer, and we did not request anything previously");
2036 return false;
2037 }
2038 MDEBUG(context << "Nothing to get from this peer, and it's not ahead of us, all done");
2039 context.set_state_normal();
2040 if (m_core.get_current_blockchain_height() >= m_core.get_target_blockchain_height())
2041 on_connection_synchronized();
2042 return true;
2043 }
2044 uint64_t next_needed_height = m_block_queue.get_next_needed_height(bc_height);
2045 uint64_t next_block_height;
2046 if (context.m_needed_objects.empty())
2047 next_block_height = next_needed_height;
2048 else
2049 next_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1;
2050 bool stripe_proceed_main = ((m_sync_pruned_blocks && local_stripe && add_stripe != local_stripe) || add_stripe == 0 || peer_stripe == 0 || add_stripe == peer_stripe) && (next_block_height < bc_height + BLOCK_QUEUE_FORCE_DOWNLOAD_NEAR_BLOCKS || next_needed_height < bc_height + BLOCK_QUEUE_FORCE_DOWNLOAD_NEAR_BLOCKS);
2051 bool stripe_proceed_secondary = tools::has_unpruned_block(next_block_height, context.m_remote_blockchain_height, context.m_pruning_seed);
2052 bool proceed = stripe_proceed_main || (queue_proceed && stripe_proceed_secondary);
2053 if (!stripe_proceed_main && !stripe_proceed_secondary && should_drop_connection(context, tools::get_pruning_stripe(next_block_height, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES)))
2054 {
2055 if (!context.m_is_income)
2056 m_p2p->add_used_stripe_peer(context);
2057 return false; // drop outgoing connections
2058 }
2059
2060 MDEBUG(context << "proceed " << proceed << " (queue " << queue_proceed << ", stripe " << stripe_proceed_main << "/" <<
2061 stripe_proceed_secondary << "), " << next_needed_pruning_stripe.first << "-" << next_needed_pruning_stripe.second <<
2062 " needed, bc add stripe " << add_stripe << ", we have " << peer_stripe << "), bc_height " << bc_height);
2063 MDEBUG(context << " - next_block_height " << next_block_height << ", seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) <<
2064 ", next_needed_height "<< next_needed_height);
2065 MDEBUG(context << " - last_response_height " << context.m_last_response_height << ", m_needed_objects size " << context.m_needed_objects.size());
2066
2067 // if we're waiting for next span, try to get it before unblocking threads below,
2068 // or a runaway downloading of future spans might happen
2069 if (stripe_proceed_main && should_download_next_span(context, true))
2070 {
2071 MDEBUG(context << " we should try for that next span too, we think we could get it faster, resuming");
2072 force_next_span = true;
2073 MLOG_PEER_STATE("resuming");
2074 break;
2075 }
2076
2077 if (proceed)
2078 {
2079 if (context.m_state != cryptonote_connection_context::state_standby)
2080 {
2081 LOG_DEBUG_CC(context, "Block queue is " << nspans << " and " << size << ", resuming");
2082 MLOG_PEER_STATE("resuming");
2083 }
2084 break;
2085 }
2086
2087 // this one triggers if all threads are in standby, which should not happen,
2088 // but happened at least once, so we unblock at least one thread if so
2089 boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock};
2090 if (sync.owns_lock())
2091 {
2092 bool filled = false;
2093 boost::posix_time::ptime time;
2094 boost::uuids::uuid connection_id;
2095 if (m_block_queue.has_next_span(m_core.get_current_blockchain_height(), filled, time, connection_id) && filled)
2096 {
2097 LOG_DEBUG_CC(context, "No other thread is adding blocks, and next span needed is ready, resuming");
2098 MLOG_PEER_STATE("resuming");
2099 context.m_state = cryptonote_connection_context::state_standby;
2100 ++context.m_callback_request_count;
2101 m_p2p->request_callback(context);
2102 return true;
2103 }
2104 else
2105 {
2106 sync.unlock();
2107
2108 // if this has gone on for too long, drop incoming connection to guard against some wedge state
2109 if (!context.m_is_income)
2110 {
2111 const uint64_t now = tools::get_tick_count();
2112 const uint64_t dt = now - m_last_add_end_time;
2113 if (m_last_add_end_time && tools::ticks_to_ns(dt) >= DROP_ON_SYNC_WEDGE_THRESHOLD)
2114 {
2115 MDEBUG(context << "ns " << tools::ticks_to_ns(dt) << " from " << m_last_add_end_time << " and " << now);
2116 MDEBUG(context << "Block addition seems to have wedged, dropping connection");
2117 return false;
2118 }
2119 }
2120 }
2121 }
2122
2123 if (context.m_state != cryptonote_connection_context::state_standby)
2124 {
2125 if (!queue_proceed)
2126 LOG_DEBUG_CC(context, "Block queue is " << nspans << " and " << size << ", pausing");
2127 else if (!stripe_proceed_main && !stripe_proceed_secondary)
2128 LOG_DEBUG_CC(context, "We do not have the stripe required to download another block, pausing");
2129 context.m_state = cryptonote_connection_context::state_standby;
2130 MLOG_PEER_STATE("pausing");
2131 }
2132
2133 return true;
2134 } while(0);
2135 context.m_state = cryptonote_connection_context::state_synchronizing;
2136 }
2137
2138 MDEBUG(context << " request_missing_objects: check " << check_having_blocks << ", force_next_span " << force_next_span
2139 << ", m_needed_objects " << context.m_needed_objects.size() << " lrh " << context.m_last_response_height << ", chain "
2140 << m_core.get_current_blockchain_height() << ", pruning seed " << epee::string_tools::to_string_hex(context.m_pruning_seed));
2141 if(context.m_needed_objects.size() || force_next_span)
2142 {
2143 //we know objects that we need, request this objects
2144 NOTIFY_REQUEST_GET_OBJECTS::request req;
2145 bool is_next = false;
2146 size_t count = 0;
2147 const size_t count_limit = m_core.get_block_sync_size(m_core.get_current_blockchain_height());
2148 std::pair<uint64_t, uint64_t> span = std::make_pair(0, 0);
2149 if (force_next_span)
2150 {
2151 if (span.second == 0)
2152 {
2153 std::vector<crypto::hash> hashes;
2154 boost::uuids::uuid span_connection_id;
2155 boost::posix_time::ptime time;
2156 span = m_block_queue.get_next_span_if_scheduled(hashes, span_connection_id, time);
2157 if (span.second > 0)
2158 {
2159 is_next = true;
2160 req.blocks.reserve(hashes.size());
2161 for (const auto &hash: hashes)
2162 {
2163 req.blocks.push_back(hash);
2164 context.m_requested_objects.insert(hash);
2165 }
2166 m_block_queue.reset_next_span_time();
2167 }
2168 }
2169 }
2170 if (span.second == 0)
2171 {
2172 MDEBUG(context << " span size is 0");
2173 if (context.m_last_response_height + 1 < context.m_needed_objects.size())
2174 {
2175 MERROR(context << " ERROR: inconsistent context: lrh " << context.m_last_response_height << ", nos " << context.m_needed_objects.size());
2176 context.m_needed_objects.clear();
2177 context.m_last_response_height = 0;
2178 goto skip;
2179 }
2180 if (skip_unneeded_hashes(context, false) && context.m_needed_objects.empty() && context.m_num_requested == 0)
2181 {
2182 if (context.m_remote_blockchain_height > m_block_queue.get_next_needed_height(m_core.get_current_blockchain_height()))
2183 {
2184 MERROR(context << "Nothing we can request from this peer, and we did not request anything previously");
2185 return false;
2186 }
2187 MDEBUG(context << "Nothing to get from this peer, and it's not ahead of us, all done");
2188 context.set_state_normal();
2189 if (m_core.get_current_blockchain_height() >= m_core.get_target_blockchain_height())
2190 on_connection_synchronized();
2191 return true;
2192 }
2193
2194 const uint64_t first_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1;
2195 static const uint64_t bp_fork_height = m_core.get_earliest_ideal_height_for_version(8);
2196 bool sync_pruned_blocks = m_sync_pruned_blocks && first_block_height >= bp_fork_height && m_core.get_blockchain_pruning_seed();
2197 span = m_block_queue.reserve_span(first_block_height, context.m_last_response_height, count_limit, context.m_connection_id, context.m_remote_address, sync_pruned_blocks, m_core.get_blockchain_pruning_seed(), context.m_pruning_seed, context.m_remote_blockchain_height, context.m_needed_objects);
2198 MDEBUG(context << " span from " << first_block_height << ": " << span.first << "/" << span.second);
2199 if (span.second > 0)
2200 {
2201 const uint32_t stripe = tools::get_pruning_stripe(span.first, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
2202 if (context.m_pruning_seed && stripe != tools::get_pruning_stripe(context.m_pruning_seed))
2203 {
2204 MDEBUG(context << " starting early on next seed (" << span.first << " with stripe " << stripe <<
2205 ", context seed " << epee::string_tools::to_string_hex(context.m_pruning_seed) << ")");
2206 }
2207 }
2208 }
2209 if (span.second == 0 && !force_next_span)
2210 {
2211 MDEBUG(context << " still no span reserved, we may be in the corner case of next span scheduled and everything else scheduled/filled");
2212 std::vector<crypto::hash> hashes;
2213 boost::uuids::uuid span_connection_id;
2214 boost::posix_time::ptime time;
2215 span = m_block_queue.get_next_span_if_scheduled(hashes, span_connection_id, time);
2216 if (span.second > 0 && !tools::has_unpruned_block(span.first, context.m_remote_blockchain_height, context.m_pruning_seed))
2217 span = std::make_pair(0, 0);
2218 if (span.second > 0)
2219 {
2220 is_next = true;
2221 req.blocks.reserve(hashes.size());
2222 for (const auto &hash: hashes)
2223 {
2224 req.blocks.push_back(hash);
2225 ++count;
2226 context.m_requested_objects.insert(hash);
2227 // that's atrocious O(n) wise, but this is rare
2228 auto i = std::find_if(context.m_needed_objects.begin(), context.m_needed_objects.end(),
2229 [&hash](const std::pair<crypto::hash, uint64_t> &o) { return o.first == hash; });
2230 if (i != context.m_needed_objects.end())
2231 context.m_needed_objects.erase(i);
2232 }
2233 }
2234 }
2235 MDEBUG(context << " span: " << span.first << "/" << span.second << " (" << span.first << " - " << (span.first + span.second - 1) << ")");
2236 if (span.second > 0)
2237 {
2238 if (!is_next)
2239 {
2240 const uint64_t first_context_block_height = context.m_last_response_height - context.m_needed_objects.size() + 1;
2241 uint64_t skip = span.first - first_context_block_height;
2242 if (skip > context.m_needed_objects.size())
2243 {
2244 MERROR("ERROR: skip " << skip << ", m_needed_objects " << context.m_needed_objects.size() << ", first_context_block_height" << first_context_block_height);
2245 return false;
2246 }
2247 if (skip > 0)
2248 context.m_needed_objects = std::vector<std::pair<crypto::hash, uint64_t>>(context.m_needed_objects.begin() + skip, context.m_needed_objects.end());
2249 if (context.m_needed_objects.size() < span.second)
2250 {
2251 MERROR("ERROR: span " << span.first << "/" << span.second << ", m_needed_objects " << context.m_needed_objects.size());
2252 return false;
2253 }
2254
2255 req.blocks.reserve(req.blocks.size() + span.second);
2256 for (size_t n = 0; n < span.second; ++n)
2257 {
2258 req.blocks.push_back(context.m_needed_objects[n].first);
2259 ++count;
2260 context.m_requested_objects.insert(context.m_needed_objects[n].first);
2261 }
2262 context.m_needed_objects = std::vector<std::pair<crypto::hash, uint64_t>>(context.m_needed_objects.begin() + span.second, context.m_needed_objects.end());
2263 }
2264
2265 req.prune = should_ask_for_pruned_data(context, span.first, span.second, true);
2266
2267 // if we need to ask for full data and that peer does not have the right stripe, we can't ask it
2268 if (!req.prune && context.m_pruning_seed)
2269 {
2270 const uint32_t peer_stripe = tools::get_pruning_stripe(context.m_pruning_seed);
2271 const uint32_t first_stripe = tools::get_pruning_stripe(span.first, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
2272 const uint32_t last_stripe = tools::get_pruning_stripe(span.first + span.second - 1, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
2273 if (((first_stripe && peer_stripe != first_stripe) || (last_stripe && peer_stripe != last_stripe)) && !m_sync_pruned_blocks)
2274 {
2275 MDEBUG(context << "We need full data, but the peer does not have it, dropping peer");
2276 return false;
2277 }
2278 }
2279 context.m_last_request_time = boost::posix_time::microsec_clock::universal_time();
2280 context.m_expect_height = span.first;
2281 context.m_expect_response = NOTIFY_RESPONSE_GET_OBJECTS::ID;
2282 MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_GET_OBJECTS: blocks.size()=" << req.blocks.size()
2283 << "requested blocks count=" << count << " / " << count_limit << " from " << span.first << ", first hash " << req.blocks.front());
2284 //epee::net_utils::network_throttle_manager::get_global_throttle_inreq().logger_handle_net("log/dr-monero/net/req-all.data", sec, get_avg_block_size());
2285
2286 MDEBUG("Asking for " << (req.prune ? "pruned" : "full") << " data, start/end "
2287 << tools::get_pruning_stripe(span.first, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES)
2288 << "/" << tools::get_pruning_stripe(span.first + span.second - 1, context.m_remote_blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES)
2289 << ", ours " << tools::get_pruning_stripe(m_core.get_blockchain_pruning_seed()) << ", peer stripe " << tools::get_pruning_stripe(context.m_pruning_seed));
2290
2291 context.m_num_requested += req.blocks.size();
2292 post_notify<NOTIFY_REQUEST_GET_OBJECTS>(req, context);
2293 MLOG_PEER_STATE("requesting objects");
2294 return true;
2295 }
2296
2297 // we can do nothing, so drop this peer to make room for others unless we think we've downloaded all we need
2298 const uint64_t blockchain_height = m_core.get_current_blockchain_height();
2299 if (std::max(blockchain_height, m_block_queue.get_next_needed_height(blockchain_height)) >= m_core.get_target_blockchain_height())
2300 {
2301 context.set_state_normal();
2302 MLOG_PEER_STATE("Nothing to do for now, switching to normal state");
2303 return true;
2304 }
2305 MLOG_PEER_STATE("We can download nothing from this peer, dropping");
2306 return false;
2307 }
2308
2309 skip:
2310 context.m_needed_objects.clear();
2311
2312 // we might have been called from the "received chain entry" handler, and end up
2313 // here because we can't use any of those blocks (maybe because all of them are
2314 // actually already requested). In this case, if we can add blocks instead, do so
2315 if (m_core.get_current_blockchain_height() < m_core.get_target_blockchain_height())
2316 {
2317 const boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock};
2318 if (sync.owns_lock())
2319 {
2320 uint64_t start_height;
2321 std::vector<cryptonote::block_complete_entry> blocks;
2322 boost::uuids::uuid span_connection_id;
2323 epee::net_utils::network_address span_origin;
2324 if (m_block_queue.get_next_span(start_height, blocks, span_connection_id, span_origin, true))
2325 {
2326 LOG_DEBUG_CC(context, "No other thread is adding blocks, resuming");
2327 MLOG_PEER_STATE("will try to add blocks next");
2328 context.m_state = cryptonote_connection_context::state_standby;
2329 ++context.m_callback_request_count;
2330 m_p2p->request_callback(context);
2331 return true;
2332 }
2333 }
2334 }
2335
2336 if(context.m_last_response_height < context.m_remote_blockchain_height-1)
2337 {//we have to fetch more objects ids, request blockchain entry
2338
2339 NOTIFY_REQUEST_CHAIN::request r = {};
2340 context.m_expect_height = m_core.get_current_blockchain_height();
2341 m_core.get_short_chain_history(r.block_ids);
2342 CHECK_AND_ASSERT_MES(!r.block_ids.empty(), false, "Short chain history is empty");
2343
2344 // we'll want to start off from where we are on that peer, which may not be added yet
2345 if (context.m_last_known_hash != crypto::null_hash && r.block_ids.front() != context.m_last_known_hash)
2346 {
2347 context.m_expect_height = std::numeric_limits<uint64_t>::max();
2348 r.block_ids.push_front(context.m_last_known_hash);
2349 }
2350
2351 handler_request_blocks_history( r.block_ids ); // change the limit(?), sleep(?)
2352 r.prune = m_sync_pruned_blocks;
2353
2354 //std::string blob; // for calculate size of request
2355 //epee::serialization::store_t_to_binary(r, blob);
2356 //epee::net_utils::network_throttle_manager::get_global_throttle_inreq().logger_handle_net("log/dr-monero/net/req-all.data", sec, get_avg_block_size());
2357 //LOG_PRINT_CCONTEXT_L1("r = " << 200);
2358
2359 context.m_last_request_time = boost::posix_time::microsec_clock::universal_time();
2360 context.m_expect_response = NOTIFY_RESPONSE_CHAIN_ENTRY::ID;
2361 MLOG_P2P_MESSAGE("-->>NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << r.block_ids.size());
2362 post_notify<NOTIFY_REQUEST_CHAIN>(r, context);
2363 MLOG_PEER_STATE("requesting chain");
2364 }else
2365 {
2366 CHECK_AND_ASSERT_MES(context.m_last_response_height == context.m_remote_blockchain_height-1
2367 && !context.m_needed_objects.size()
2368 && !context.m_requested_objects.size(), false, "request_missing_blocks final condition failed!"
2369 << "\r\nm_last_response_height=" << context.m_last_response_height
2370 << "\r\nm_remote_blockchain_height=" << context.m_remote_blockchain_height
2371 << "\r\nm_needed_objects.size()=" << context.m_needed_objects.size()
2372 << "\r\nm_requested_objects.size()=" << context.m_requested_objects.size()
2373 << "\r\non connection [" << epee::net_utils::print_connection_context_short(context)<< "]");
2374
2375 context.set_state_normal();
2376 if (context.m_remote_blockchain_height >= m_core.get_target_blockchain_height())
2377 {
2378 if (m_core.get_current_blockchain_height() >= m_core.get_target_blockchain_height())
2379 on_connection_synchronized();
2380 }
2381 else
2382 {
2383 MINFO(context << " we've reached this peer's blockchain height (theirs " << context.m_remote_blockchain_height << ", our target " << m_core.get_target_blockchain_height());
2384 }
2385 }
2386 return true;
2387 }
2388 //------------------------------------------------------------------------------------------------------------------------
2389 template<class t_core>
2390 bool t_cryptonote_protocol_handler<t_core>::on_connection_synchronized()
2391 {
2392 bool val_expected = false;
2393 uint64_t current_blockchain_height = m_core.get_current_blockchain_height();
2394 if(!m_core.is_within_compiled_block_hash_area(current_blockchain_height) && m_synchronized.compare_exchange_strong(val_expected, true))
2395 {
2396 if ((current_blockchain_height > m_sync_start_height) && (m_sync_spans_downloaded > 0))
2397 {
2398 uint64_t synced_blocks = current_blockchain_height - m_sync_start_height;
2399 // Report only after syncing an "interesting" number of blocks:
2400 if (synced_blocks > 20)
2401 {
2402 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
2403 uint64_t synced_seconds = (now - m_sync_start_time).total_seconds();
2404 if (synced_seconds == 0)
2405 {
2406 synced_seconds = 1;
2407 }
2408 float blocks_per_second = (1000 * synced_blocks / synced_seconds) / 1000.0f;
2409 MGINFO_YELLOW("Synced " << synced_blocks << " blocks in "
2410 << tools::get_human_readable_timespan(synced_seconds) << " (" << blocks_per_second << " blocks per second)");
2411 }
2412 }
2413 MGINFO_YELLOW(ENDL << "**********************************************************************" << ENDL
2414 << "You are now synchronized with the network. You may now start monero-wallet-cli." << ENDL
2415 << ENDL
2416 << "Use the \"help\" command to see the list of available commands." << ENDL
2417 << "**********************************************************************");
2418 m_sync_timer.pause();
2419 if (ELPP->vRegistry()->allowed(el::Level::Info, "sync-info"))
2420 {
2421 const uint64_t sync_time = m_sync_timer.value();
2422 const uint64_t add_time = m_add_timer.value();
2423 if (sync_time && add_time)
2424 {
2425 MCLOG_YELLOW(el::Level::Info, "sync-info", "Sync time: " << sync_time/1e9/60 << " min, idle time " <<
2426 (100.f * (1.0f - add_time / (float)sync_time)) << "%" << ", " <<
2427 (10 * m_sync_download_objects_size / 1024 / 1024) / 10.f << " + " <<
2428 (10 * m_sync_download_chain_size / 1024 / 1024) / 10.f << " MB downloaded, " <<
2429 100.0f * m_sync_old_spans_downloaded / m_sync_spans_downloaded << "% old spans, " <<
2430 100.0f * m_sync_bad_spans_downloaded / m_sync_spans_downloaded << "% bad spans");
2431 }
2432 }
2433 m_core.on_synchronized();
2434 }
2435 m_core.safesyncmode(true);
2436 m_p2p->clear_used_stripe_peers();
2437
2438 // ask for txpool complement from any suitable node if we did not yet
2439 val_expected = true;
2440 if (m_ask_for_txpool_complement.compare_exchange_strong(val_expected, false))
2441 {
2442 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool
2443 {
2444 if(context.m_state < cryptonote_connection_context::state_synchronizing)
2445 {
2446 MDEBUG(context << "not ready, ignoring");
2447 return true;
2448 }
2449 if (!request_txpool_complement(context))
2450 {
2451 MERROR(context << "Failed to request txpool complement");
2452 return true;
2453 }
2454 return false;
2455 });
2456 }
2457
2458 return true;
2459 }
2460 //------------------------------------------------------------------------------------------------------------------------
2461 template<class t_core>
2462 size_t t_cryptonote_protocol_handler<t_core>::get_synchronizing_connections_count()
2463 {
2464 size_t count = 0;
2465 m_p2p->for_each_connection([&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{
2466 if(context.m_state == cryptonote_connection_context::state_synchronizing)
2467 ++count;
2468 return true;
2469 });
2470 return count;
2471 }
2472 //------------------------------------------------------------------------------------------------------------------------
2473 template<class t_core>
2474 int t_cryptonote_protocol_handler<t_core>::handle_response_chain_entry(int command, NOTIFY_RESPONSE_CHAIN_ENTRY::request& arg, cryptonote_connection_context& context)
2475 {
2476 MLOG_P2P_MESSAGE("Received NOTIFY_RESPONSE_CHAIN_ENTRY: m_block_ids.size()=" << arg.m_block_ids.size()
2477 << ", m_start_height=" << arg.start_height << ", m_total_height=" << arg.total_height);
2478 MLOG_PEER_STATE("received chain");
2479
2480 if (context.m_expect_response != NOTIFY_RESPONSE_CHAIN_ENTRY::ID)
2481 {
2482 LOG_ERROR_CCONTEXT("Got NOTIFY_RESPONSE_CHAIN_ENTRY out of the blue, dropping connection");
2483 drop_connection(context, true, false);
2484 return 1;
2485 }
2486 context.m_expect_response = 0;
2487 if (arg.start_height + 1 > context.m_expect_height) // we expect an overlapping block
2488 {
2489 LOG_ERROR_CCONTEXT("Got NOTIFY_RESPONSE_CHAIN_ENTRY past expected height, dropping connection");
2490 drop_connection(context, true, false);
2491 return 1;
2492 }
2493
2494 context.m_last_request_time = boost::date_time::not_a_date_time;
2495
2496 m_sync_download_chain_size += arg.m_block_ids.size() * sizeof(crypto::hash);
2497
2498 if(!arg.m_block_ids.size())
2499 {
2500 LOG_ERROR_CCONTEXT("sent empty m_block_ids, dropping connection");
2501 drop_connection(context, true, false);
2502 return 1;
2503 }
2504 if (arg.total_height < arg.m_block_ids.size() || arg.start_height > arg.total_height - arg.m_block_ids.size())
2505 {
2506 LOG_ERROR_CCONTEXT("sent invalid start/nblocks/height, dropping connection");
2507 drop_connection(context, true, false);
2508 return 1;
2509 }
2510 if (!arg.m_block_weights.empty() && arg.m_block_weights.size() != arg.m_block_ids.size())
2511 {
2512 LOG_ERROR_CCONTEXT("sent invalid block weight array, dropping connection");
2513 drop_connection(context, true, false);
2514 return 1;
2515 }
2516 MDEBUG(context << "first block hash " << arg.m_block_ids.front() << ", last " << arg.m_block_ids.back());
2517
2518 if (arg.total_height >= CRYPTONOTE_MAX_BLOCK_NUMBER || arg.m_block_ids.size() > BLOCKS_IDS_SYNCHRONIZING_MAX_COUNT)
2519 {
2520 LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with total_height=" << arg.total_height << " and block_ids=" << arg.m_block_ids.size());
2521 drop_connection(context, false, false);
2522 return 1;
2523 }
2524 if (arg.total_height < context.m_remote_blockchain_height)
2525 {
2526 MINFO(context << "Claims " << arg.total_height << ", claimed " << context.m_remote_blockchain_height << " before");
2527 hit_score(context, 1);
2528 }
2529 context.m_remote_blockchain_height = arg.total_height;
2530 context.m_last_response_height = arg.start_height + arg.m_block_ids.size()-1;
2531 if(context.m_last_response_height > context.m_remote_blockchain_height)
2532 {
2533 LOG_ERROR_CCONTEXT("sent wrong NOTIFY_RESPONSE_CHAIN_ENTRY, with m_total_height=" << arg.total_height
2534 << ", m_start_height=" << arg.start_height
2535 << ", m_block_ids.size()=" << arg.m_block_ids.size());
2536 drop_connection(context, false, false);
2537 return 1;
2538 }
2539
2540 uint64_t n_use_blocks = m_core.prevalidate_block_hashes(arg.start_height, arg.m_block_ids, arg.m_block_weights);
2541 if (n_use_blocks == 0 || n_use_blocks + HASH_OF_HASHES_STEP <= arg.m_block_ids.size())
2542 {
2543 LOG_ERROR_CCONTEXT("Most blocks are invalid, dropping connection");
2544 drop_connection(context, true, false);
2545 return 1;
2546 }
2547
2548 context.m_expected_heights_start = arg.start_height;
2549
2550 context.m_expected_heights.clear();
2551 context.m_expected_heights.reserve(arg.m_block_ids.size());
2552 context.m_needed_objects.clear();
2553 context.m_needed_objects.reserve(arg.m_block_ids.size());
2554 uint64_t added = 0;
2555 std::unordered_set<crypto::hash> blocks_found;
2556 bool expect_unknown = false;
2557 for (size_t i = 0; i < arg.m_block_ids.size(); ++i)
2558 {
2559 if (!blocks_found.insert(arg.m_block_ids[i]).second)
2560 {
2561 LOG_ERROR_CCONTEXT("Duplicate blocks in chain entry response, dropping connection");
2562 drop_connection_with_score(context, 5, false);
2563 return 1;
2564 }
2565 int where;
2566 const bool have_block = m_core.have_block_unlocked(arg.m_block_ids[i], &where);
2567 if (i == 0)
2568 {
2569 // our outgoing chainlist only has proven blocks (i.e. downloaded)
2570 if (!have_block && m_block_queue.have_height(arg.m_block_ids[i]) != arg.start_height)
2571 {
2572 LOG_ERROR_CCONTEXT("First block hash is unknown, dropping connection");
2573 drop_connection_with_score(context, 5, false);
2574 return 1;
2575 }
2576 if (!have_block)
2577 expect_unknown = true;
2578 }
2579 if (0 < i)
2580 {
2581 // after the first, blocks may be known or unknown, but if they are known,
2582 // they should be at the same height if on the main chain
2583 if (have_block)
2584 {
2585 switch (where)
2586 {
2587 default:
2588 case HAVE_BLOCK_INVALID:
2589 LOG_ERROR_CCONTEXT("Block is invalid or known without known type, dropping connection");
2590 drop_connection(context, true, false);
2591 return 1;
2592 case HAVE_BLOCK_MAIN_CHAIN:
2593 if (expect_unknown)
2594 {
2595 LOG_ERROR_CCONTEXT("Block is on the main chain, but we did not expect a known block, dropping connection");
2596 drop_connection_with_score(context, 5, false);
2597 return 1;
2598 }
2599 if (m_core.get_block_id_by_height(arg.start_height + i) != arg.m_block_ids[i])
2600 {
2601 LOG_ERROR_CCONTEXT("Block is on the main chain, but not at the expected height, dropping connection");
2602 drop_connection_with_score(context, 5, false);
2603 return 1;
2604 }
2605 break;
2606 case HAVE_BLOCK_ALT_CHAIN:
2607 if (expect_unknown)
2608 {
2609 LOG_ERROR_CCONTEXT("Block is on the main chain, but we did not expect a known block, dropping connection");
2610 drop_connection_with_score(context, 5, false);
2611 return 1;
2612 }
2613 break;
2614 }
2615 }
2616 else
2617 expect_unknown = true;
2618 }
2619 const uint64_t block_weight = arg.m_block_weights.empty() ? 0 : arg.m_block_weights[i];
2620 context.m_expected_heights.push_back(arg.m_block_ids[i]);
2621 context.m_needed_objects.push_back(std::make_pair(arg.m_block_ids[i], block_weight));
2622 if (++added == n_use_blocks)
2623 break;
2624 }
2625 context.m_last_response_height -= arg.m_block_ids.size() - n_use_blocks;
2626
2627 if (!request_missing_objects(context, false))
2628 {
2629 LOG_ERROR_CCONTEXT("Failed to request missing objects, dropping connection");
2630 drop_connection(context, false, false);
2631 return 1;
2632 }
2633
2634 if (arg.total_height > m_core.get_target_blockchain_height())
2635 m_core.set_target_blockchain_height(arg.total_height);
2636
2637 context.m_num_requested = 0;
2638 return 1;
2639 }
2640 //------------------------------------------------------------------------------------------------------------------------
2641 template<class t_core>
2642 bool t_cryptonote_protocol_handler<t_core>::relay_block(NOTIFY_NEW_FLUFFY_BLOCK::request& arg, cryptonote_connection_context& exclude_context)
2643 {
2644 // sort peers between fluffy ones and others
2645 std::vector<std::pair<epee::net_utils::zone, boost::uuids::uuid>> fluffyConnections;
2646 m_p2p->for_each_connection([this, &exclude_context, &fluffyConnections](connection_context& context, nodetool::peerid_type peer_id, uint32_t support_flags)
2647 {
2648 // peer_id also filters out connections before handshake
2649 if (peer_id && exclude_context.m_connection_id != context.m_connection_id && context.m_remote_address.get_zone() == epee::net_utils::zone::public_)
2650 {
2651 LOG_DEBUG_CC(context, "RELAYING FLUFFY BLOCK TO PEER");
2652 fluffyConnections.push_back({context.m_remote_address.get_zone(), context.m_connection_id});
2653 }
2654 return true;
2655 });
2656
2657 // send fluffy ones first, we want to encourage people to run that
2658 if (!fluffyConnections.empty())
2659 {
2660 epee::levin::message_writer fluffyBlob{32 * 1024};
2661 epee::serialization::store_t_to_binary(arg, fluffyBlob.buffer);
2662 m_p2p->relay_notify_to_list(NOTIFY_NEW_FLUFFY_BLOCK::ID, std::move(fluffyBlob), std::move(fluffyConnections));
2663 }
2664
2665 return true;
2666 }
2667 //------------------------------------------------------------------------------------------------------------------------
2668 template<class t_core>
2669 bool t_cryptonote_protocol_handler<t_core>::relay_transactions(NOTIFY_NEW_TRANSACTIONS::request& arg, const boost::uuids::uuid& source, epee::net_utils::zone zone, relay_method tx_relay)
2670 {
2671 /* Push all outgoing transactions to this function. The behavior needs to
2672 identify how the transaction is going to be relayed, and then update the
2673 local mempool before doing the relay. The code was already updating the
2674 DB twice on received transactions - it is difficult to workaround this
2675 due to the internal design. */
2676 return m_p2p->send_txs(std::move(arg.txs), zone, source, tx_relay) != epee::net_utils::zone::invalid;
2677 }
2678 //------------------------------------------------------------------------------------------------------------------------
2679 template<class t_core>
2680 bool t_cryptonote_protocol_handler<t_core>::request_txpool_complement(cryptonote_connection_context &context)
2681 {
2682 NOTIFY_GET_TXPOOL_COMPLEMENT::request r = {};
2683 if (!m_core.get_pool_transaction_hashes(r.hashes, false))
2684 {
2685 MERROR("Failed to get txpool hashes");
2686 return false;
2687 }
2688 MLOG_P2P_MESSAGE("-->>NOTIFY_GET_TXPOOL_COMPLEMENT: hashes.size()=" << r.hashes.size() );
2689 post_notify<NOTIFY_GET_TXPOOL_COMPLEMENT>(r, context);
2690 MLOG_PEER_STATE("requesting txpool complement");
2691 return true;
2692 }
2693 //------------------------------------------------------------------------------------------------------------------------
2694 template<class t_core>
2695 void t_cryptonote_protocol_handler<t_core>::hit_score(cryptonote_connection_context &context, int32_t score)
2696 {
2697 if (score <= 0)
2698 {
2699 MERROR("Negative score hit");
2700 return;
2701 }
2702 context.m_score -= score;
2703 if (context.m_score <= DROP_PEERS_ON_SCORE)
2704 drop_connection_with_score(context, 5, false);
2705 }
2706 //------------------------------------------------------------------------------------------------------------------------
2707 template<class t_core>
2708 std::string t_cryptonote_protocol_handler<t_core>::get_peers_overview() const
2709 {
2710 std::stringstream ss;
2711 const boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
2712 m_p2p->for_each_connection([&](const connection_context &ctx, nodetool::peerid_type peer_id, uint32_t support_flags) {
2713 const uint32_t stripe = tools::get_pruning_stripe(ctx.m_pruning_seed);
2714 char state_char = cryptonote::get_protocol_state_char(ctx.m_state);
2715 ss << stripe + state_char;
2716 if (ctx.m_last_request_time != boost::date_time::not_a_date_time)
2717 ss << (((now - ctx.m_last_request_time).total_microseconds() > IDLE_PEER_KICK_TIME) ? "!" : "?");
2718 ss << + " ";
2719 return true;
2720 });
2721 return ss.str();
2722 }
2723 //------------------------------------------------------------------------------------------------------------------------
2724 template<class t_core>
2725 std::pair<uint32_t, uint32_t> t_cryptonote_protocol_handler<t_core>::get_next_needed_pruning_stripe() const
2726 {
2727 const uint64_t want_height_from_blockchain = m_core.get_current_blockchain_height();
2728 const uint64_t want_height_from_block_queue = m_block_queue.get_next_needed_height(want_height_from_blockchain);
2729 const uint64_t want_height = std::max(want_height_from_blockchain, want_height_from_block_queue);
2730 uint64_t blockchain_height = m_core.get_target_blockchain_height();
2731 // if we don't know the remote chain size yet, assume infinitely large so we get the right stripe if we're not near the tip
2732 if (blockchain_height == 0)
2733 blockchain_height = CRYPTONOTE_MAX_BLOCK_NUMBER;
2734 const uint32_t next_pruning_stripe = tools::get_pruning_stripe(want_height, blockchain_height, CRYPTONOTE_PRUNING_LOG_STRIPES);
2735 if (next_pruning_stripe == 0)
2736 return std::make_pair(0, 0);
2737 // if we already have a few peers on this stripe, but none on next one, try next one
2738 unsigned int n_next = 0, n_subsequent = 0, n_others = 0;
2739 const uint32_t subsequent_pruning_stripe = 1 + next_pruning_stripe % (1<<CRYPTONOTE_PRUNING_LOG_STRIPES);
2740 m_p2p->for_each_connection([&](const connection_context &context, nodetool::peerid_type peer_id, uint32_t support_flags) {
2741 if (context.m_state >= cryptonote_connection_context::state_synchronizing)
2742 {
2743 if (context.m_pruning_seed == 0 || tools::get_pruning_stripe(context.m_pruning_seed) == next_pruning_stripe)
2744 ++n_next;
2745 else if (tools::get_pruning_stripe(context.m_pruning_seed) == subsequent_pruning_stripe)
2746 ++n_subsequent;
2747 else
2748 ++n_others;
2749 }
2750 return true;
2751 });
2752 // TODO: investigate tallying by zone and comparing to max out peers by zone
2753 const unsigned int max_out_peers = get_max_out_peers(epee::net_utils::zone::public_);
2754 const bool use_next = (n_next > max_out_peers / 2 && n_subsequent <= 1) || (n_next > 2 && n_subsequent == 0);
2755 const uint32_t ret_stripe = use_next ? subsequent_pruning_stripe: next_pruning_stripe;
2756 MIDEBUG(const std::string po = get_peers_overview(), "get_next_needed_pruning_stripe: want height " << want_height << " (" <<
2757 want_height_from_blockchain << " from blockchain, " << want_height_from_block_queue << " from block queue), stripe " <<
2758 next_pruning_stripe << " (" << n_next << "/" << max_out_peers << " on it and " << n_subsequent << " on " <<
2759 subsequent_pruning_stripe << ", " << n_others << " others) -> " << ret_stripe << " (+" <<
2760 (ret_stripe - next_pruning_stripe + (1 << CRYPTONOTE_PRUNING_LOG_STRIPES)) % (1 << CRYPTONOTE_PRUNING_LOG_STRIPES) <<
2761 "), current peers " << po);
2762 return std::make_pair(next_pruning_stripe, ret_stripe);
2763 }
2764 //------------------------------------------------------------------------------------------------------------------------
2765 template<class t_core>
2766 bool t_cryptonote_protocol_handler<t_core>::needs_new_sync_connections(epee::net_utils::zone zone) const
2767 {
2768 const uint64_t target = m_core.get_target_blockchain_height();
2769 const uint64_t height = m_core.get_current_blockchain_height();
2770 if (target && target <= height)
2771 return false;
2772 size_t n_out_peers = 0;
2773 m_p2p->for_each_connection([&](cryptonote_connection_context& ctx, nodetool::peerid_type peer_id, uint32_t support_flags)->bool{
2774 if (!ctx.m_is_income && ctx.m_remote_address.get_zone() == zone)
2775 ++n_out_peers;
2776 return true;
2777 });
2778 if (n_out_peers >= get_max_out_peers(zone))
2779 return false;
2780 return true;
2781 }
2782 //------------------------------------------------------------------------------------------------------------------------
2783 template<class t_core>
2784 bool t_cryptonote_protocol_handler<t_core>::is_busy_syncing()
2785 {
2786 const boost::unique_lock<boost::mutex> sync{m_sync_lock, boost::try_to_lock};
2787 return !sync.owns_lock();
2788 }
2789 //------------------------------------------------------------------------------------------------------------------------
2790 template<class t_core>
2791 void t_cryptonote_protocol_handler<t_core>::drop_connection_with_score(cryptonote_connection_context &context, unsigned score, bool flush_all_spans)
2792 {
2793 LOG_DEBUG_CC(context, "dropping connection id " << context.m_connection_id << " (pruning seed " <<
2794 epee::string_tools::to_string_hex(context.m_pruning_seed) <<
2795 "), score " << score << ", flush_all_spans " << flush_all_spans);
2796
2797 if (score > 0)
2798 m_p2p->add_host_fail(context.m_remote_address, score);
2799
2800 m_block_queue.flush_spans(context.m_connection_id, flush_all_spans);
2801
2802 m_p2p->drop_connection(context);
2803 }
2804 //------------------------------------------------------------------------------------------------------------------------
2805 template<class t_core>
2806 void t_cryptonote_protocol_handler<t_core>::drop_connection(cryptonote_connection_context &context, bool add_fail, bool flush_all_spans)
2807 {
2808 return drop_connection_with_score(context, add_fail ? 1 : 0, flush_all_spans);
2809 }
2810 //------------------------------------------------------------------------------------------------------------------------
2811 template<class t_core>
2812 void t_cryptonote_protocol_handler<t_core>::drop_connection(const boost::uuids::uuid& id)
2813 {
2814 m_p2p->for_connection(id, [this](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t f)->bool{
2815 // This _could be_ outside of strand, so careful on actions
2816 drop_connection(context, true, false);
2817 return true;
2818 });
2819 }
2820 //------------------------------------------------------------------------------------------------------------------------
2821 template<class t_core>
2822 void t_cryptonote_protocol_handler<t_core>::drop_connections(const epee::net_utils::network_address address)
2823 {
2824 MWARNING("dropping connections to " << address.str());
2825
2826 m_p2p->add_host_fail(address, 5);
2827
2828 std::vector<boost::uuids::uuid> drop;
2829 m_p2p->for_each_connection([&](const connection_context& cntxt, nodetool::peerid_type peer_id, uint32_t support_flags) {
2830 if (address.is_same_host(cntxt.m_remote_address))
2831 drop.push_back(cntxt.m_connection_id);
2832 return true;
2833 });
2834 for (const boost::uuids::uuid &id: drop)
2835 {
2836 m_block_queue.flush_spans(id, true);
2837 m_p2p->for_connection(id, [&](cryptonote_connection_context& context, nodetool::peerid_type peer_id, uint32_t f)->bool{
2838 // This _could be_ outside of strand, so careful on actions
2839 drop_connection(context, true, false);
2840 return true;
2841 });
2842 }
2843 }
2844 //------------------------------------------------------------------------------------------------------------------------
2845 template<class t_core>
2846 void t_cryptonote_protocol_handler<t_core>::on_connection_close(cryptonote_connection_context &context)
2847 {
2848 uint64_t target = 0;
2849 m_p2p->for_each_connection([&](const connection_context& cntxt, nodetool::peerid_type peer_id, uint32_t support_flags) {
2850 if (cntxt.m_state >= cryptonote_connection_context::state_synchronizing && cntxt.m_connection_id != context.m_connection_id)
2851 target = std::max(target, cntxt.m_remote_blockchain_height);
2852 return true;
2853 });
2854 const uint64_t previous_target = m_core.get_target_blockchain_height();
2855 if (target < previous_target)
2856 {
2857 MINFO("Target height decreasing from " << previous_target << " to " << target);
2858 m_core.set_target_blockchain_height(target);
2859 if (target == 0 && context.m_state > cryptonote_connection_context::state_before_handshake && !m_stopping)
2860 {
2861 MCWARNING("global", "monerod is now disconnected from the network");
2862 m_ask_for_txpool_complement = true;
2863 }
2864 }
2865
2866 m_block_queue.flush_spans(context.m_connection_id, false);
2867 MLOG_PEER_STATE("closed");
2868 }
2869
2870 //------------------------------------------------------------------------------------------------------------------------
2871 template<class t_core>
2872 void t_cryptonote_protocol_handler<t_core>::stop()
2873 {
2874 m_stopping = true;
2875 m_core.stop();
2876 }
2877 } // namespace
2878