Debian Codegraph @

monero/src/cryptonote_core/cryptonote_core.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 //
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification, are
6 // permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice, this list of
9 // conditions and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
12 // of conditions and the following disclaimer in the documentation and/or other
13 // materials provided with the distribution.
14 //
15 // 3. Neither the name of the copyright holder nor the names of its contributors may be
16 // used to endorse or promote products derived from this software without specific
17 // prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
30
31 #include <boost/algorithm/string.hpp>
32 #include <boost/uuid/nil_generator.hpp>
33
34 #include "string_tools.h"
35 using namespace epee;
36
37 #include <unordered_set>
38 #include "cryptonote_core.h"
39 #include "common/util.h"
40 #include "common/updates.h"
41 #include "common/download.h"
42 #include "common/threadpool.h"
43 #include "common/command_line.h"
44 #include "cryptonote_basic/events.h"
45 #include "warnings.h"
46 #include "crypto/crypto.h"
47 #include "cryptonote_config.h"
48 #include "misc_language.h"
49 #include "file_io_utils.h"
50 #include <csignal>
51 #include "checkpoints/checkpoints.h"
52 #include "ringct/rctTypes.h"
53 #include "blockchain_db/blockchain_db.h"
54 #include "ringct/rctSigs.h"
55 #include "rpc/zmq_pub.h"
56 #include "common/notify.h"
57 #include "hardforks/hardforks.h"
58 #include "tx_verification_utils.h"
59 #include "version.h"
60
61 #include <boost/filesystem.hpp>
62
63 #undef MONERO_DEFAULT_LOG_CATEGORY
64 #define MONERO_DEFAULT_LOG_CATEGORY "cn"
65
66 DISABLE_VS_WARNINGS(4355)
67
68 #define MERROR_VER(x) MCERROR("verify", x)
69
70 // basically at least how many bytes the block itself serializes to without the miner tx
71 #define BLOCK_SIZE_SANITY_LEEWAY 100
72
73 namespace cryptonote
74 {
75 const command_line::arg_descriptor<bool, false> arg_testnet_on = {
76 "testnet"
77 , "Run on testnet. The wallet must be launched with --testnet flag."
78 , false
79 };
80 const command_line::arg_descriptor<bool, false> arg_stagenet_on = {
81 "stagenet"
82 , "Run on stagenet. The wallet must be launched with --stagenet flag."
83 , false
84 };
85 const command_line::arg_descriptor<bool> arg_regtest_on = {
86 "regtest"
87 , "Run in a regression testing mode."
88 , false
89 };
90 const command_line::arg_descriptor<bool> arg_keep_fakechain = {
91 "keep-fakechain"
92 , "Don't delete any existing database when in fakechain mode."
93 , false
94 };
95 const command_line::arg_descriptor<difficulty_type> arg_fixed_difficulty = {
96 "fixed-difficulty"
97 , "Fixed difficulty used for testing."
98 , 0
99 };
100 const command_line::arg_descriptor<std::string, false, true, 2> arg_data_dir = {
101 "data-dir"
102 , "Specify data directory"
103 , tools::get_default_data_dir()
104 , {{ &arg_testnet_on, &arg_stagenet_on }}
105 , [](std::array<bool, 2> testnet_stagenet, bool defaulted, std::string val)->std::string {
106 if (testnet_stagenet[0])
107 return (boost::filesystem::path(val) / "testnet").string();
108 else if (testnet_stagenet[1])
109 return (boost::filesystem::path(val) / "stagenet").string();
110 return val;
111 }
112 };
113 const command_line::arg_descriptor<bool> arg_offline = {
114 "offline"
115 , "Do not listen for peers, nor connect to any"
116 };
117 const command_line::arg_descriptor<bool> arg_disable_dns_checkpoints = {
118 "disable-dns-checkpoints"
119 , "Do not retrieve checkpoints from DNS"
120 };
121 const command_line::arg_descriptor<size_t> arg_block_download_max_size = {
122 "block-download-max-size"
123 , "Set maximum size of block download queue in bytes (0 for default)"
124 , 0
125 };
126 const command_line::arg_descriptor<bool> arg_sync_pruned_blocks = {
127 "sync-pruned-blocks"
128 , "Allow syncing from nodes with only pruned blocks"
129 };
130
131 static const command_line::arg_descriptor<bool> arg_test_drop_download = {
132 "test-drop-download"
133 , "For net tests: in download, discard ALL blocks instead checking/saving them (very fast)"
134 };
135 static const command_line::arg_descriptor<uint64_t> arg_test_drop_download_height = {
136 "test-drop-download-height"
137 , "Like test-drop-download but discards only after around certain height"
138 , 0
139 };
140 static const command_line::arg_descriptor<int> arg_test_dbg_lock_sleep = {
141 "test-dbg-lock-sleep"
142 , "Sleep time in ms, defaults to 0 (off), used to debug before/after locking mutex. Values 100 to 1000 are good for tests."
143 , 0
144 };
145 static const command_line::arg_descriptor<bool> arg_dns_checkpoints = {
146 "enforce-dns-checkpointing"
147 , "checkpoints from DNS server will be enforced"
148 , false
149 };
150 static const command_line::arg_descriptor<uint64_t> arg_fast_block_sync = {
151 "fast-block-sync"
152 , "Sync up most of the way by using embedded, known block hashes."
153 , 1
154 };
155 static const command_line::arg_descriptor<uint64_t> arg_prep_blocks_threads = {
156 "prep-blocks-threads"
157 , "Max number of threads to use when preparing block hashes in groups."
158 , 4
159 };
160 static const command_line::arg_descriptor<uint64_t> arg_show_time_stats = {
161 "show-time-stats"
162 , "Show time-stats when processing blocks/txs and disk synchronization."
163 , 0
164 };
165 static const command_line::arg_descriptor<size_t> arg_block_sync_size = {
166 "block-sync-size"
167 , "How many blocks to sync at once during chain synchronization (0 = adaptive)."
168 , 0
169 };
170 static const command_line::arg_descriptor<std::string> arg_check_updates = {
171 "check-updates"
172 , "Check for new versions of monero: [disabled|notify|download|update]"
173 , "notify"
174 };
175 static const command_line::arg_descriptor<bool> arg_fluffy_blocks = {
176 "fluffy-blocks"
177 , "Relay blocks as fluffy blocks (obsolete, now default)"
178 , true
179 };
180 static const command_line::arg_descriptor<size_t> arg_max_txpool_weight = {
181 "max-txpool-weight"
182 , "Set maximum txpool weight in bytes."
183 , DEFAULT_TXPOOL_MAX_WEIGHT
184 };
185 static const command_line::arg_descriptor<std::string> arg_block_notify = {
186 "block-notify"
187 , "Run a program for each new block, '%s' will be replaced by the block hash"
188 , ""
189 };
190 static const command_line::arg_descriptor<bool> arg_prune_blockchain = {
191 "prune-blockchain"
192 , "Prune blockchain"
193 , false
194 };
195 static const command_line::arg_descriptor<std::string> arg_reorg_notify = {
196 "reorg-notify"
197 , "Run a program for each reorg, '%s' will be replaced by the split height, "
198 "'%h' will be replaced by the new blockchain height, '%n' will be "
199 "replaced by the number of new blocks in the new chain, and '%d' will be "
200 "replaced by the number of blocks discarded from the old chain"
201 , ""
202 };
203 static const command_line::arg_descriptor<std::string> arg_block_rate_notify = {
204 "block-rate-notify"
205 , "Run a program when the block rate undergoes large fluctuations. This might "
206 "be a sign of large amounts of hash rate going on and off the Monero network, "
207 "and thus be of potential interest in predicting attacks. %t will be replaced "
208 "by the number of minutes for the observation window, %b by the number of "
209 "blocks observed within that window, and %e by the number of blocks that was "
210 "expected in that window. It is suggested that this notification is used to "
211 "automatically increase the number of confirmations required before a payment "
212 "is acted upon."
213 , ""
214 };
215 static const command_line::arg_descriptor<bool> arg_keep_alt_blocks = {
216 "keep-alt-blocks"
217 , "Keep alternative blocks on restart"
218 , false
219 };
220
221 //-----------------------------------------------------------------------------------------------
222 core::core(i_cryptonote_protocol* pprotocol):
223 m_mempool(m_blockchain_storage),
224 m_blockchain_storage(m_mempool),
225 m_miner(this, [this](const cryptonote::block &b, uint64_t height, const crypto::hash *seed_hash, unsigned int threads, crypto::hash &hash) {
226 return cryptonote::get_block_longhash(&m_blockchain_storage, b, hash, height, seed_hash, threads);
227 }),
228 m_starter_message_showed(false),
229 m_target_blockchain_height(0),
230 m_checkpoints_path(""),
231 m_last_dns_checkpoints_update(0),
232 m_last_json_checkpoints_update(0),
233 m_disable_dns_checkpoints(false),
234 m_update_download(0),
235 m_nettype(UNDEFINED),
236 m_update_available(false)
237 {
238 m_checkpoints_updating.clear();
239 set_cryptonote_protocol(pprotocol);
240 }
241 void core::set_cryptonote_protocol(i_cryptonote_protocol* pprotocol)
242 {
243 if(pprotocol)
244 m_pprotocol = pprotocol;
245 else
246 m_pprotocol = &m_protocol_stub;
247 }
248 //-----------------------------------------------------------------------------------
249 const checkpoints& core::get_checkpoints() const
250 {
251 return m_blockchain_storage.get_checkpoints();
252 }
253 void core::set_checkpoints(checkpoints&& chk_pts)
254 {
255 m_blockchain_storage.set_checkpoints(std::move(chk_pts));
256 }
257 //-----------------------------------------------------------------------------------
258 void core::set_checkpoints_file_path(const std::string& path)
259 {
260 m_checkpoints_path = path;
261 }
262 //-----------------------------------------------------------------------------------
263 void core::set_enforce_dns_checkpoints(bool enforce_dns)
264 {
265 m_blockchain_storage.set_enforce_dns_checkpoints(enforce_dns);
266 }
267 //-----------------------------------------------------------------------------------------------
268 bool core::update_checkpoints(const bool skip_dns /* = false */)
269 {
270 if (m_nettype != MAINNET || m_disable_dns_checkpoints) return true;
271
272 if (m_checkpoints_updating.test_and_set()) return true;
273
274 bool res = true;
275 if (!skip_dns && time(NULL) - m_last_dns_checkpoints_update >= 3600)
276 {
277 res = m_blockchain_storage.update_checkpoints(m_checkpoints_path, true);
278 m_last_dns_checkpoints_update = time(NULL);
279 m_last_json_checkpoints_update = time(NULL);
280 }
281 else if (time(NULL) - m_last_json_checkpoints_update >= 600)
282 {
283 res = m_blockchain_storage.update_checkpoints(m_checkpoints_path, false);
284 m_last_json_checkpoints_update = time(NULL);
285 }
286
287 m_checkpoints_updating.clear();
288
289 // if anything fishy happened getting new checkpoints, bring down the house
290 if (!res)
291 {
292 graceful_exit();
293 }
294 return res;
295 }
296 //-----------------------------------------------------------------------------------
297 void core::stop()
298 {
299 m_miner.stop();
300 m_blockchain_storage.cancel();
301
302 tools::download_async_handle handle;
303 {
304 boost::lock_guard<boost::mutex> lock(m_update_mutex);
305 handle = m_update_download;
306 m_update_download = 0;
307 }
308 if (handle)
309 tools::download_cancel(handle);
310 }
311 //-----------------------------------------------------------------------------------
312 void core::init_options(boost::program_options::options_description& desc)
313 {
314 command_line::add_arg(desc, arg_data_dir);
315
316 command_line::add_arg(desc, arg_test_drop_download);
317 command_line::add_arg(desc, arg_test_drop_download_height);
318
319 command_line::add_arg(desc, arg_testnet_on);
320 command_line::add_arg(desc, arg_stagenet_on);
321 command_line::add_arg(desc, arg_regtest_on);
322 command_line::add_arg(desc, arg_keep_fakechain);
323 command_line::add_arg(desc, arg_fixed_difficulty);
324 command_line::add_arg(desc, arg_dns_checkpoints);
325 command_line::add_arg(desc, arg_prep_blocks_threads);
326 command_line::add_arg(desc, arg_fast_block_sync);
327 command_line::add_arg(desc, arg_show_time_stats);
328 command_line::add_arg(desc, arg_block_sync_size);
329 command_line::add_arg(desc, arg_check_updates);
330 command_line::add_arg(desc, arg_fluffy_blocks);
331 command_line::add_arg(desc, arg_test_dbg_lock_sleep);
332 command_line::add_arg(desc, arg_offline);
333 command_line::add_arg(desc, arg_disable_dns_checkpoints);
334 command_line::add_arg(desc, arg_block_download_max_size);
335 command_line::add_arg(desc, arg_sync_pruned_blocks);
336 command_line::add_arg(desc, arg_max_txpool_weight);
337 command_line::add_arg(desc, arg_block_notify);
338 command_line::add_arg(desc, arg_prune_blockchain);
339 command_line::add_arg(desc, arg_reorg_notify);
340 command_line::add_arg(desc, arg_block_rate_notify);
341 command_line::add_arg(desc, arg_keep_alt_blocks);
342
343 miner::init_options(desc);
344 BlockchainDB::init_options(desc);
345 }
346 //-----------------------------------------------------------------------------------------------
347 bool core::handle_command_line(const boost::program_options::variables_map& vm)
348 {
349 if (m_nettype != FAKECHAIN)
350 {
351 const bool testnet = command_line::get_arg(vm, arg_testnet_on);
352 const bool stagenet = command_line::get_arg(vm, arg_stagenet_on);
353 m_nettype = testnet ? TESTNET : stagenet ? STAGENET : MAINNET;
354 }
355
356 m_config_folder = command_line::get_arg(vm, arg_data_dir);
357
358 auto data_dir = boost::filesystem::path(m_config_folder);
359
360 if (m_nettype == MAINNET)
361 {
362 cryptonote::checkpoints checkpoints;
363 if (!checkpoints.init_default_checkpoints(m_nettype))
364 {
365 throw std::runtime_error("Failed to initialize checkpoints");
366 }
367 set_checkpoints(std::move(checkpoints));
368
369 boost::filesystem::path json(JSON_HASH_FILE_NAME);
370 boost::filesystem::path checkpoint_json_hashfile_fullpath = data_dir / json;
371
372 set_checkpoints_file_path(checkpoint_json_hashfile_fullpath.string());
373 }
374
375
376 set_enforce_dns_checkpoints(command_line::get_arg(vm, arg_dns_checkpoints));
377 test_drop_download_height(command_line::get_arg(vm, arg_test_drop_download_height));
378 m_offline = get_arg(vm, arg_offline);
379 m_disable_dns_checkpoints = get_arg(vm, arg_disable_dns_checkpoints);
380
381 if (!command_line::is_arg_defaulted(vm, arg_fluffy_blocks))
382 MWARNING(arg_fluffy_blocks.name << " is obsolete, it is now default");
383
384 if (command_line::get_arg(vm, arg_test_drop_download) == true)
385 test_drop_download();
386
387 epee::debug::g_test_dbg_lock_sleep() = command_line::get_arg(vm, arg_test_dbg_lock_sleep);
388
389 return true;
390 }
391 //-----------------------------------------------------------------------------------------------
392 uint64_t core::get_current_blockchain_height() const
393 {
394 return m_blockchain_storage.get_current_blockchain_height();
395 }
396 //-----------------------------------------------------------------------------------------------
397 void core::get_blockchain_top(uint64_t& height, crypto::hash& top_id) const
398 {
399 top_id = m_blockchain_storage.get_tail_id(height);
400 }
401 //-----------------------------------------------------------------------------------------------
402 bool core::get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks, std::vector<cryptonote::blobdata>& txs) const
403 {
404 return m_blockchain_storage.get_blocks(start_offset, count, blocks, txs);
405 }
406 //-----------------------------------------------------------------------------------------------
407 bool core::get_blocks(uint64_t start_offset, size_t count, std::vector<std::pair<cryptonote::blobdata,block>>& blocks) const
408 {
409 return m_blockchain_storage.get_blocks(start_offset, count, blocks);
410 }
411 //-----------------------------------------------------------------------------------------------
412 bool core::get_blocks(uint64_t start_offset, size_t count, std::vector<block>& blocks) const
413 {
414 std::vector<std::pair<cryptonote::blobdata, cryptonote::block>> bs;
415 if (!m_blockchain_storage.get_blocks(start_offset, count, bs))
416 return false;
417 for (const auto &b: bs)
418 blocks.push_back(b.second);
419 return true;
420 }
421 //-----------------------------------------------------------------------------------------------
422 bool core::get_transactions(const std::vector<crypto::hash>& txs_ids, std::vector<cryptonote::blobdata>& txs, std::vector<crypto::hash>& missed_txs, bool pruned) const
423 {
424 return m_blockchain_storage.get_transactions_blobs(txs_ids, txs, missed_txs, pruned);
425 }
426 //-----------------------------------------------------------------------------------------------
427 bool core::get_split_transactions_blobs(const std::vector<crypto::hash>& txs_ids, std::vector<std::tuple<crypto::hash, cryptonote::blobdata, crypto::hash, cryptonote::blobdata>>& txs, std::vector<crypto::hash>& missed_txs) const
428 {
429 return m_blockchain_storage.get_split_transactions_blobs(txs_ids, txs, missed_txs);
430 }
431 //-----------------------------------------------------------------------------------------------
432 bool core::get_txpool_backlog(std::vector<tx_backlog_entry>& backlog, bool include_sensitive_txes) const
433 {
434 m_mempool.get_transaction_backlog(backlog, include_sensitive_txes);
435 return true;
436 }
437 //-----------------------------------------------------------------------------------------------
438 bool core::get_transactions(const std::vector<crypto::hash>& txs_ids, std::vector<transaction>& txs, std::vector<crypto::hash>& missed_txs, bool pruned) const
439 {
440 return m_blockchain_storage.get_transactions(txs_ids, txs, missed_txs, pruned);
441 }
442 //-----------------------------------------------------------------------------------------------
443 bool core::get_alternative_blocks(std::vector<block>& blocks) const
444 {
445 return m_blockchain_storage.get_alternative_blocks(blocks);
446 }
447 //-----------------------------------------------------------------------------------------------
448 size_t core::get_alternative_blocks_count() const
449 {
450 return m_blockchain_storage.get_alternative_blocks_count();
451 }
452 //-----------------------------------------------------------------------------------------------
453 bool core::init(const boost::program_options::variables_map& vm, const cryptonote::test_options *test_options, const GetCheckpointsCallback& get_checkpoints/* = nullptr */, bool allow_dns)
454 {
455 start_time = std::time(nullptr);
456
457 const bool regtest = command_line::get_arg(vm, arg_regtest_on);
458 if (test_options != NULL || regtest)
459 {
460 m_nettype = FAKECHAIN;
461 }
462 bool r = handle_command_line(vm);
463 CHECK_AND_ASSERT_MES(r, false, "Failed to handle command line");
464 m_disable_dns_checkpoints |= not allow_dns;
465
466 std::string db_sync_mode = command_line::get_arg(vm, cryptonote::arg_db_sync_mode);
467 bool db_salvage = command_line::get_arg(vm, cryptonote::arg_db_salvage) != 0;
468 bool fast_sync = command_line::get_arg(vm, arg_fast_block_sync) != 0;
469 uint64_t blocks_threads = command_line::get_arg(vm, arg_prep_blocks_threads);
470 std::string check_updates_string = command_line::get_arg(vm, arg_check_updates);
471 size_t max_txpool_weight = command_line::get_arg(vm, arg_max_txpool_weight);
472 bool prune_blockchain = command_line::get_arg(vm, arg_prune_blockchain);
473 bool keep_alt_blocks = command_line::get_arg(vm, arg_keep_alt_blocks);
474 bool keep_fakechain = command_line::get_arg(vm, arg_keep_fakechain);
475
476 boost::filesystem::path folder(m_config_folder);
477 if (m_nettype == FAKECHAIN)
478 folder /= "fake";
479
480 // make sure the data directory exists, and try to lock it
481 CHECK_AND_ASSERT_MES (boost::filesystem::exists(folder) || boost::filesystem::create_directories(folder), false,
482 std::string("Failed to create directory ").append(folder.string()).c_str());
483
484 // check for blockchain.bin
485 try
486 {
487 const boost::filesystem::path old_files = folder;
488 if (boost::filesystem::exists(old_files / "blockchain.bin"))
489 {
490 MWARNING("Found old-style blockchain.bin in " << old_files.string());
491 MWARNING("Monero now uses a new format. You can either remove blockchain.bin to start syncing");
492 MWARNING("the blockchain anew, or use monero-blockchain-export and monero-blockchain-import to");
493 MWARNING("convert your existing blockchain.bin to the new format. See README.md for instructions.");
494 return false;
495 }
496 }
497 // folder might not be a directory, etc, etc
498 catch (...) { }
499
500 std::unique_ptr<BlockchainDB> db(new_db());
501 if (db == NULL)
502 {
503 LOG_ERROR("Failed to initialize a database");
504 return false;
505 }
506
507 folder /= db->get_db_name();
508 MGINFO("Loading blockchain from folder " << folder.string() << " ...");
509
510 const std::string filename = folder.string();
511 // default to fast:async:1 if overridden
512 blockchain_db_sync_mode sync_mode = db_defaultsync;
513 bool sync_on_blocks = true;
514 uint64_t sync_threshold = 1;
515
516 if (m_nettype == FAKECHAIN && !keep_fakechain)
517 {
518 // reset the db by removing the database file before opening it
519 if (!db->remove_data_file(filename))
520 {
521 MERROR("Failed to remove data file in " << filename);
522 return false;
523 }
524 }
525
526 try
527 {
528 uint64_t db_flags = 0;
529
530 std::vector<std::string> options;
531 boost::trim(db_sync_mode);
532 boost::split(options, db_sync_mode, boost::is_any_of(" :"));
533 const bool db_sync_mode_is_default = command_line::is_arg_defaulted(vm, cryptonote::arg_db_sync_mode);
534
535 for(const auto &option : options)
536 MDEBUG("option: " << option);
537
538 // default to fast:async:1
539 uint64_t DEFAULT_FLAGS = DBF_FAST;
540
541 if(options.size() == 0)
542 {
543 // default to fast:async:1
544 db_flags = DEFAULT_FLAGS;
545 }
546
547 bool safemode = false;
548 if(options.size() >= 1)
549 {
550 if(options[0] == "safe")
551 {
552 safemode = true;
553 db_flags = DBF_SAFE;
554 sync_mode = db_sync_mode_is_default ? db_defaultsync : db_nosync;
555 }
556 else if(options[0] == "fast")
557 {
558 db_flags = DBF_FAST;
559 sync_mode = db_sync_mode_is_default ? db_defaultsync : db_async;
560 }
561 else if(options[0] == "fastest")
562 {
563 db_flags = DBF_FASTEST;
564 sync_threshold = 1000; // default to fastest:async:1000
565 sync_mode = db_sync_mode_is_default ? db_defaultsync : db_async;
566 }
567 else
568 db_flags = DEFAULT_FLAGS;
569 }
570
571 if(options.size() >= 2 && !safemode)
572 {
573 if(options[1] == "sync")
574 sync_mode = db_sync_mode_is_default ? db_defaultsync : db_sync;
575 else if(options[1] == "async")
576 sync_mode = db_sync_mode_is_default ? db_defaultsync : db_async;
577 }
578
579 if(options.size() >= 3 && !safemode)
580 {
581 char *endptr;
582 uint64_t threshold = strtoull(options[2].c_str(), &endptr, 0);
583 if (*endptr == '\0' || !strcmp(endptr, "blocks"))
584 {
585 sync_on_blocks = true;
586 sync_threshold = threshold;
587 }
588 else if (!strcmp(endptr, "bytes"))
589 {
590 sync_on_blocks = false;
591 sync_threshold = threshold;
592 }
593 else
594 {
595 LOG_ERROR("Invalid db sync mode: " << options[2]);
596 return false;
597 }
598 }
599
600 if (db_salvage)
601 db_flags |= DBF_SALVAGE;
602
603 db->open(filename, db_flags);
604 if(!db->m_open)
605 return false;
606 }
607 catch (const DB_ERROR& e)
608 {
609 LOG_ERROR("Error opening database: " << e.what());
610 return false;
611 }
612
613 m_blockchain_storage.set_user_options(blocks_threads,
614 sync_on_blocks, sync_threshold, sync_mode, fast_sync);
615
616 try
617 {
618 if (!command_line::is_arg_defaulted(vm, arg_block_notify))
619 {
620 struct hash_notify
621 {
622 tools::Notify cmdline;
623
624 void operator()(std::uint64_t, epee::span<const block> blocks) const
625 {
626 for (const block& bl : blocks)
627 cmdline.notify("%s", epee::string_tools::pod_to_hex(get_block_hash(bl)).c_str(), NULL);
628 }
629 };
630
631 m_blockchain_storage.add_block_notify(hash_notify{{command_line::get_arg(vm, arg_block_notify).c_str()}});
632 }
633 }
634 catch (const std::exception &e)
635 {
636 MERROR("Failed to parse block notify spec: " << e.what());
637 }
638
639 try
640 {
641 if (!command_line::is_arg_defaulted(vm, arg_reorg_notify))
642 m_blockchain_storage.set_reorg_notify(std::shared_ptr<tools::Notify>(new tools::Notify(command_line::get_arg(vm, arg_reorg_notify).c_str())));
643 }
644 catch (const std::exception &e)
645 {
646 MERROR("Failed to parse reorg notify spec: " << e.what());
647 }
648
649 try
650 {
651 if (!command_line::is_arg_defaulted(vm, arg_block_rate_notify))
652 m_block_rate_notify.reset(new tools::Notify(command_line::get_arg(vm, arg_block_rate_notify).c_str()));
653 }
654 catch (const std::exception &e)
655 {
656 MERROR("Failed to parse block rate notify spec: " << e.what());
657 }
658
659 const std::pair<uint8_t, uint64_t> regtest_hard_forks[3] = {std::make_pair(1, 0), std::make_pair(mainnet_hard_forks[num_mainnet_hard_forks-1].version, 1), std::make_pair(0, 0)};
660 const cryptonote::test_options regtest_test_options = {
661 regtest_hard_forks,
662 0
663 };
664 const difficulty_type fixed_difficulty = command_line::get_arg(vm, arg_fixed_difficulty);
665 r = m_blockchain_storage.init(db.release(), m_nettype, m_offline, regtest ? &regtest_test_options : test_options, fixed_difficulty, get_checkpoints);
666 CHECK_AND_ASSERT_MES(r, false, "Failed to initialize blockchain storage");
667
668 r = m_mempool.init(max_txpool_weight, m_nettype == FAKECHAIN);
669 CHECK_AND_ASSERT_MES(r, false, "Failed to initialize memory pool");
670
671 // now that we have a valid m_blockchain_storage, we can clean out any
672 // transactions in the pool that do not conform to the current fork
673 m_mempool.validate(m_blockchain_storage.get_current_hard_fork_version());
674
675 bool show_time_stats = command_line::get_arg(vm, arg_show_time_stats) != 0;
676 m_blockchain_storage.set_show_time_stats(show_time_stats);
677 CHECK_AND_ASSERT_MES(r, false, "Failed to initialize blockchain storage");
678
679 block_sync_size = command_line::get_arg(vm, arg_block_sync_size);
680 if (block_sync_size > BLOCKS_SYNCHRONIZING_MAX_COUNT)
681 MERROR("Error --block-sync-size cannot be greater than " << BLOCKS_SYNCHRONIZING_MAX_COUNT);
682
683 MGINFO("Loading checkpoints");
684
685 // load json & DNS checkpoints, and verify them
686 // with respect to what blocks we already have
687 const bool skip_dns_checkpoints = !command_line::get_arg(vm, arg_dns_checkpoints);
688 CHECK_AND_ASSERT_MES(update_checkpoints(skip_dns_checkpoints), false, "One or more checkpoints loaded from json or dns conflicted with existing checkpoints.");
689
690 // DNS versions checking
691 if (check_updates_string == "disabled" || not allow_dns)
692 check_updates_level = UPDATES_DISABLED;
693 else if (check_updates_string == "notify")
694 check_updates_level = UPDATES_NOTIFY;
695 else if (check_updates_string == "download")
696 check_updates_level = UPDATES_DOWNLOAD;
697 else if (check_updates_string == "update")
698 check_updates_level = UPDATES_UPDATE;
699 else {
700 MERROR("Invalid argument to --dns-versions-check: " << check_updates_string);
701 return false;
702 }
703
704 r = m_miner.init(vm, m_nettype);
705 CHECK_AND_ASSERT_MES(r, false, "Failed to initialize miner instance");
706
707 if (!keep_alt_blocks && !m_blockchain_storage.get_db().is_read_only())
708 m_blockchain_storage.get_db().drop_alt_blocks();
709
710 if (prune_blockchain)
711 {
712 // display a message if the blockchain is not pruned yet
713 if (!m_blockchain_storage.get_blockchain_pruning_seed())
714 {
715 MGINFO("Pruning blockchain...");
716 CHECK_AND_ASSERT_MES(m_blockchain_storage.prune_blockchain(), false, "Failed to prune blockchain");
717 }
718 else
719 {
720 CHECK_AND_ASSERT_MES(m_blockchain_storage.update_blockchain_pruning(), false, "Failed to update blockchain pruning");
721 }
722 }
723
724 return load_state_data();
725 }
726 //-----------------------------------------------------------------------------------------------
727 bool core::set_genesis_block(const block& b)
728 {
729 return m_blockchain_storage.reset_and_set_genesis_block(b);
730 }
731 //-----------------------------------------------------------------------------------------------
732 bool core::load_state_data()
733 {
734 // may be some code later
735 return true;
736 }
737 //-----------------------------------------------------------------------------------------------
738 bool core::deinit()
739 {
740 m_miner.stop();
741 m_mempool.deinit();
742 m_blockchain_storage.deinit();
743 return true;
744 }
745 //-----------------------------------------------------------------------------------------------
746 void core::test_drop_download()
747 {
748 m_test_drop_download = false;
749 }
750 //-----------------------------------------------------------------------------------------------
751 void core::test_drop_download_height(uint64_t height)
752 {
753 m_test_drop_download_height = height;
754 }
755 //-----------------------------------------------------------------------------------------------
756 bool core::get_test_drop_download() const
757 {
758 return m_test_drop_download;
759 }
760 //-----------------------------------------------------------------------------------------------
761 bool core::get_test_drop_download_height() const
762 {
763 if (m_test_drop_download_height == 0)
764 return true;
765
766 if (get_blockchain_storage().get_current_blockchain_height() <= m_test_drop_download_height)
767 return true;
768
769 return false;
770 }
771 //-----------------------------------------------------------------------------------------------
772 bool core::handle_incoming_tx(const blobdata& tx_blob, tx_verification_context& tvc, relay_method tx_relay, bool relayed)
773 {
774 tvc = {};
775
776 TRY_ENTRY();
777
778 CRITICAL_REGION_LOCAL(m_incoming_tx_lock);
779
780 if (tx_blob.size() > get_max_tx_size())
781 {
782 LOG_PRINT_L1("WRONG TRANSACTION BLOB, too big size " << tx_blob.size() << ", rejected");
783 tvc.m_verifivation_failed = true;
784 tvc.m_too_big = true;
785 return false;
786 }
787
788 transaction tx;
789 crypto::hash txid;
790 if (!parse_and_validate_tx_from_blob(tx_blob, tx, txid))
791 {
792 LOG_PRINT_L1("Incoming transactions failed to parse, rejected");
793 tvc.m_verifivation_failed = true;
794 return false;
795 }
796
797 const uint64_t tx_weight = get_transaction_weight(tx, tx_blob.size());
798 if (!add_new_tx(tx, txid, tx_blob, tx_weight, tvc, tx_relay, relayed))
799 return false;
800
801 if (tvc.m_verifivation_failed)
802 {
803 MERROR_VER("Transaction verification failed: " << txid);
804 return false;
805 }
806 else if (tvc.m_verifivation_impossible)
807 {
808 MERROR_VER("Transaction verification impossible: " << txid);
809 return false;
810 }
811 else if (!tvc.m_added_to_pool)
812 {
813 MDEBUG("Transaction " << txid << " not added to pool");
814 return true;
815 }
816
817 MDEBUG("tx added to pool: " << txid);
818
819 return true;
820 CATCH_ENTRY_L0("core::handle_incoming_tx()", false);
821 }
822 //-----------------------------------------------------------------------------------------------
823 bool core::check_tx_semantic(const transaction& tx, tx_verification_context& tvc,
824 uint8_t hf_version)
825 {
826 if(!tx.vin.size())
827 {
828 MERROR_VER("tx with empty inputs, rejected for tx id= " << get_transaction_hash(tx));
829 tvc.m_verifivation_failed = true;
830 tvc.m_invalid_input = true;
831 return false;
832 }
833
834 if(!check_inputs_types_supported(tx))
835 {
836 MERROR_VER("unsupported input types for tx id= " << get_transaction_hash(tx));
837 tvc.m_verifivation_failed = true;
838 tvc.m_invalid_input = true;
839 return false;
840 }
841
842 if(!check_outs_valid(tx))
843 {
844 MERROR_VER("tx with invalid outputs, rejected for tx id= " << get_transaction_hash(tx));
845 tvc.m_verifivation_failed = true;
846 tvc.m_invalid_output = true;
847 return false;
848 }
849 if (tx.version > 1)
850 {
851 if (tx.rct_signatures.outPk.size() != tx.vout.size())
852 {
853 MERROR_VER("tx with mismatched vout/outPk count, rejected for tx id= " << get_transaction_hash(tx));
854 tvc.m_verifivation_failed = true;
855 tvc.m_invalid_output = true;
856 return false;
857 }
858 }
859
860 if(!check_money_overflow(tx))
861 {
862 MERROR_VER("tx has money overflow, rejected for tx id= " << get_transaction_hash(tx));
863 tvc.m_verifivation_failed = true;
864 tvc.m_overspend = true;
865 return false;
866 }
867
868 if (tx.version == 1)
869 {
870 uint64_t amount_in = 0;
871 get_inputs_money_amount(tx, amount_in);
872 uint64_t amount_out = get_outs_money_amount(tx);
873
874 if(amount_in <= amount_out)
875 {
876 MERROR_VER("tx with wrong amounts: ins " << amount_in << ", outs " << amount_out << ", rejected for tx id= " << get_transaction_hash(tx));
877 tvc.m_verifivation_failed = true;
878 tvc.m_overspend = true;
879 return false;
880 }
881 }
882 // for version > 1, ringct signatures check verifies amounts match
883
884 //check if tx use different key images
885 if(!check_tx_inputs_keyimages_diff(tx))
886 {
887 MERROR_VER("tx uses a single key image more than once");
888 tvc.m_verifivation_failed = true;
889 tvc.m_invalid_input = true;
890 return false;
891 }
892
893 if (!check_tx_inputs_ring_members_diff(tx, hf_version))
894 {
895 MERROR_VER("tx uses duplicate ring members");
896 tvc.m_verifivation_failed = true;
897 tvc.m_invalid_input = true;
898 return false;
899 }
900
901 if (!check_tx_inputs_keyimages_domain(tx))
902 {
903 MERROR_VER("tx uses key image not in the valid domain");
904 tvc.m_verifivation_failed = true;
905 tvc.m_invalid_input = true;
906 return false;
907 }
908
909 if (!check_output_types(tx, hf_version))
910 {
911 MERROR_VER("tx does not use valid output type(s)");
912 tvc.m_verifivation_failed = true;
913 tvc.m_invalid_output = true;
914 return false;
915 }
916
917 return true;
918 }
919 //-----------------------------------------------------------------------------------------------
920 bool core::is_key_image_spent(const crypto::key_image &key_image) const
921 {
922 return m_blockchain_storage.have_tx_keyimg_as_spent(key_image);
923 }
924 //-----------------------------------------------------------------------------------------------
925 bool core::are_key_images_spent(const std::vector<crypto::key_image>& key_im, std::vector<bool> &spent) const
926 {
927 spent.clear();
928 for(auto& ki: key_im)
929 {
930 spent.push_back(m_blockchain_storage.have_tx_keyimg_as_spent(ki));
931 }
932 return true;
933 }
934 //-----------------------------------------------------------------------------------------------
935 size_t core::get_block_sync_size(uint64_t height) const
936 {
937 static const uint64_t quick_height = m_nettype == TESTNET ? 801219 : m_nettype == MAINNET ? 1220516 : 0;
938 size_t res = 0;
939 if (block_sync_size > 0)
940 res = block_sync_size;
941 else if (height >= quick_height)
942 res = BLOCKS_SYNCHRONIZING_DEFAULT_COUNT;
943 else
944 res = BLOCKS_SYNCHRONIZING_DEFAULT_COUNT_PRE_V4;
945
946 static size_t max_block_size = 0;
947 if (max_block_size == 0)
948 {
949 const char *env = getenv("SEEDHASH_EPOCH_BLOCKS");
950 if (env)
951 {
952 int n = atoi(env);
953 if (n <= 0)
954 n = BLOCKS_SYNCHRONIZING_MAX_COUNT;
955 size_t p = 1;
956 while (p < (size_t)n)
957 p <<= 1;
958 max_block_size = p;
959 }
960 else
961 max_block_size = BLOCKS_SYNCHRONIZING_MAX_COUNT;
962 }
963 if (res > max_block_size)
964 {
965 static bool warned = false;
966 if (!warned)
967 {
968 MWARNING("Clamping block sync size to " << max_block_size);
969 warned = true;
970 }
971 res = max_block_size;
972 }
973 return res;
974 }
975 //-----------------------------------------------------------------------------------------------
976 bool core::are_key_images_spent_in_pool(const std::vector<crypto::key_image>& key_im, std::vector<bool> &spent) const
977 {
978 spent.clear();
979
980 return m_mempool.check_for_key_images(key_im, spent);
981 }
982 //-----------------------------------------------------------------------------------------------
983 std::pair<boost::multiprecision::uint128_t, boost::multiprecision::uint128_t> core::get_coinbase_tx_sum(const uint64_t start_offset, const size_t count)
984 {
985 boost::multiprecision::uint128_t emission_amount = 0;
986 boost::multiprecision::uint128_t total_fee_amount = 0;
987 if (count)
988 {
989 const uint64_t end = start_offset + count - 1;
990 m_blockchain_storage.for_blocks_range(start_offset, end,
991 [this, &emission_amount, &total_fee_amount](uint64_t, const crypto::hash& hash, const block& b){
992 std::vector<transaction> txs;
993 std::vector<crypto::hash> missed_txs;
994 uint64_t coinbase_amount = get_outs_money_amount(b.miner_tx);
995 this->get_transactions(b.tx_hashes, txs, missed_txs, true);
996 uint64_t tx_fee_amount = 0;
997 for(const auto& tx: txs)
998 {
999 tx_fee_amount += get_tx_fee(tx);
1000 }
1001
1002 emission_amount += coinbase_amount - tx_fee_amount;
1003 total_fee_amount += tx_fee_amount;
1004 return true;
1005 });
1006 }
1007
1008 return std::pair<boost::multiprecision::uint128_t, boost::multiprecision::uint128_t>(emission_amount, total_fee_amount);
1009 }
1010 //-----------------------------------------------------------------------------------------------
1011 bool core::check_tx_inputs_keyimages_diff(const transaction& tx)
1012 {
1013 std::unordered_set<crypto::key_image> ki;
1014 for(const auto& in: tx.vin)
1015 {
1016 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
1017 if(!ki.insert(tokey_in.k_image).second)
1018 return false;
1019 }
1020 return true;
1021 }
1022 //-----------------------------------------------------------------------------------------------
1023 bool core::check_tx_inputs_ring_members_diff(const transaction& tx, const uint8_t hf_version)
1024 {
1025 if (hf_version >= 6)
1026 {
1027 for(const auto& in: tx.vin)
1028 {
1029 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
1030 for (size_t n = 1; n < tokey_in.key_offsets.size(); ++n)
1031 if (tokey_in.key_offsets[n] == 0)
1032 return false;
1033 }
1034 }
1035 return true;
1036 }
1037 //-----------------------------------------------------------------------------------------------
1038 bool core::check_tx_inputs_keyimages_domain(const transaction& tx)
1039 {
1040 std::unordered_set<crypto::key_image> ki;
1041 for(const auto& in: tx.vin)
1042 {
1043 CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false);
1044 if (!(rct::scalarmultKey(rct::ki2rct(tokey_in.k_image), rct::curveOrder()) == rct::identity()))
1045 return false;
1046 }
1047 return true;
1048 }
1049 //-----------------------------------------------------------------------------------------------
1050 bool core::add_new_tx(transaction& tx, tx_verification_context& tvc, relay_method tx_relay, bool relayed)
1051 {
1052 crypto::hash tx_hash = get_transaction_hash(tx);
1053 blobdata bl;
1054 t_serializable_object_to_blob(tx, bl);
1055 size_t tx_weight = get_transaction_weight(tx, bl.size());
1056 return add_new_tx(tx, tx_hash, bl, tx_weight, tvc, tx_relay, relayed);
1057 }
1058 //-----------------------------------------------------------------------------------------------
1059 size_t core::get_blockchain_total_transactions() const
1060 {
1061 return m_blockchain_storage.get_total_transactions();
1062 }
1063 //-----------------------------------------------------------------------------------------------
1064 bool core::add_new_tx(transaction& tx, const crypto::hash& tx_hash, const cryptonote::blobdata &blob, size_t tx_weight, tx_verification_context& tvc, relay_method tx_relay, bool relayed)
1065 {
1066 if(m_mempool.have_tx(tx_hash, relay_category::legacy))
1067 {
1068 LOG_PRINT_L2("tx " << tx_hash << "already have transaction in tx_pool");
1069 return true;
1070 }
1071
1072 if(m_blockchain_storage.have_tx(tx_hash))
1073 {
1074 LOG_PRINT_L2("tx " << tx_hash << " already have transaction in blockchain");
1075 return true;
1076 }
1077
1078 uint8_t version = m_blockchain_storage.get_current_hard_fork_version();
1079 const bool res = m_mempool.add_tx(tx, tx_hash, blob, tx_weight, tvc, tx_relay, relayed, version);
1080
1081 // If new incoming tx passed verification and entered the pool, notify ZMQ
1082 if (!tvc.m_verifivation_failed && tvc.m_added_to_pool && matches_category(tx_relay, relay_category::legacy))
1083 {
1084 m_blockchain_storage.notify_txpool_event({txpool_event{
1085 .tx = tx,
1086 .hash = tx_hash,
1087 .blob_size = blob.size(),
1088 .weight = tx_weight,
1089 .res = true}});
1090 }
1091
1092 return res;
1093 }
1094 //-----------------------------------------------------------------------------------------------
1095 bool core::relay_txpool_transactions()
1096 {
1097 // we attempt to relay txes that should be relayed, but were not
1098 std::vector<std::tuple<crypto::hash, cryptonote::blobdata, relay_method>> txs;
1099 if (m_mempool.get_relayable_transactions(txs) && !txs.empty())
1100 {
1101 NOTIFY_NEW_TRANSACTIONS::request public_req{};
1102 NOTIFY_NEW_TRANSACTIONS::request private_req{};
1103 NOTIFY_NEW_TRANSACTIONS::request stem_req{};
1104 for (auto& tx : txs)
1105 {
1106 switch (std::get<2>(tx))
1107 {
1108 default:
1109 case relay_method::none:
1110 break;
1111 case relay_method::local:
1112 private_req.txs.push_back(std::move(std::get<1>(tx)));
1113 break;
1114 case relay_method::forward:
1115 stem_req.txs.push_back(std::move(std::get<1>(tx)));
1116 break;
1117 case relay_method::block:
1118 case relay_method::fluff:
1119 case relay_method::stem:
1120 public_req.txs.push_back(std::move(std::get<1>(tx)));
1121 break;
1122 }
1123 }
1124
1125 /* All txes are sent on randomized timers per connection in
1126 `src/cryptonote_protocol/levin_notify.cpp.` They are either sent with
1127 "white noise" delays or via diffusion (Dandelion++ fluff). So
1128 re-relaying public and private _should_ be acceptable here. */
1129 const boost::uuids::uuid source = boost::uuids::nil_uuid();
1130 if (!public_req.txs.empty())
1131 get_protocol()->relay_transactions(public_req, source, epee::net_utils::zone::public_, relay_method::fluff);
1132 if (!private_req.txs.empty())
1133 get_protocol()->relay_transactions(private_req, source, epee::net_utils::zone::invalid, relay_method::local);
1134 if (!stem_req.txs.empty())
1135 get_protocol()->relay_transactions(stem_req, source, epee::net_utils::zone::public_, relay_method::stem);
1136 }
1137 return true;
1138 }
1139 //-----------------------------------------------------------------------------------------------
1140 bool core::notify_txpool_event(const epee::span<const cryptonote::blobdata> tx_blobs, epee::span<const crypto::hash> tx_hashes, epee::span<const cryptonote::transaction> txs, const std::vector<bool> &just_broadcasted) const
1141 {
1142 if (tx_blobs.size() != tx_hashes.size() || tx_blobs.size() != txs.size() || tx_blobs.size() != just_broadcasted.size())
1143 return false;
1144
1145 /* Publish txs via ZMQ that are "just broadcasted" by the daemon. This is
1146 done here in order to guarantee txs
1147 are pub'd via ZMQ when we know the daemon has/will broadcast to other
1148 nodes & *after* the tx is visible in the pool. This should get called
1149 when the user submits a tx to a daemon in the "fluff" epoch relaying txs
1150 via a public network. */
1151 if (std::count(just_broadcasted.begin(), just_broadcasted.end(), true) == 0)
1152 return true;
1153
1154 std::vector<txpool_event> results{};
1155 results.resize(tx_blobs.size());
1156 for (std::size_t i = 0; i < results.size(); ++i)
1157 {
1158 results[i].tx = std::move(txs[i]);
1159 results[i].hash = std::move(tx_hashes[i]);
1160 results[i].blob_size = tx_blobs[i].size();
1161 results[i].weight = results[i].tx.pruned ? get_pruned_transaction_weight(results[i].tx) : get_transaction_weight(results[i].tx, results[i].blob_size);
1162 results[i].res = just_broadcasted[i];
1163 }
1164
1165 m_blockchain_storage.notify_txpool_event(std::move(results));
1166
1167 return true;
1168 }
1169 //-----------------------------------------------------------------------------------------------
1170 void core::on_transactions_relayed(const epee::span<const cryptonote::blobdata> tx_blobs, const relay_method tx_relay)
1171 {
1172 // lock ensures duplicate txs aren't pub'd via zmq
1173 CRITICAL_REGION_LOCAL(m_incoming_tx_lock);
1174
1175 std::vector<crypto::hash> tx_hashes{};
1176 tx_hashes.resize(tx_blobs.size());
1177
1178 std::vector<cryptonote::transaction> txs{};
1179 txs.resize(tx_blobs.size());
1180
1181 for (std::size_t i = 0; i < tx_blobs.size(); ++i)
1182 {
1183 if (!parse_and_validate_tx_from_blob(tx_blobs[i], txs[i], tx_hashes[i]))
1184 {
1185 LOG_ERROR("Failed to parse relayed transaction");
1186 return;
1187 }
1188 }
1189
1190 std::vector<bool> just_broadcasted{};
1191 just_broadcasted.reserve(tx_hashes.size());
1192
1193 m_mempool.set_relayed(epee::to_span(tx_hashes), tx_relay, just_broadcasted);
1194
1195 if (matches_category(tx_relay, relay_category::legacy))
1196 notify_txpool_event(tx_blobs, epee::to_span(tx_hashes), epee::to_span(txs), just_broadcasted);
1197 }
1198 //-----------------------------------------------------------------------------------------------
1199 bool core::get_block_template(block& b, const account_public_address& adr, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce, uint64_t &seed_height, crypto::hash &seed_hash)
1200 {
1201 return m_blockchain_storage.create_block_template(b, adr, diffic, height, expected_reward, ex_nonce, seed_height, seed_hash);
1202 }
1203 //-----------------------------------------------------------------------------------------------
1204 bool core::get_block_template(block& b, const crypto::hash *prev_block, const account_public_address& adr, difficulty_type& diffic, uint64_t& height, uint64_t& expected_reward, const blobdata& ex_nonce, uint64_t &seed_height, crypto::hash &seed_hash)
1205 {
1206 return m_blockchain_storage.create_block_template(b, prev_block, adr, diffic, height, expected_reward, ex_nonce, seed_height, seed_hash);
1207 }
1208 //-----------------------------------------------------------------------------------------------
1209 bool core::get_miner_data(uint8_t& major_version, uint64_t& height, crypto::hash& prev_id, crypto::hash& seed_hash, difficulty_type& difficulty, uint64_t& median_weight, uint64_t& already_generated_coins, std::vector<tx_block_template_backlog_entry>& tx_backlog)
1210 {
1211 return m_blockchain_storage.get_miner_data(major_version, height, prev_id, seed_hash, difficulty, median_weight, already_generated_coins, tx_backlog);
1212 }
1213 //-----------------------------------------------------------------------------------------------
1214 bool core::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, bool clip_pruned, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const
1215 {
1216 return m_blockchain_storage.find_blockchain_supplement(qblock_ids, clip_pruned, resp);
1217 }
1218 //-----------------------------------------------------------------------------------------------
1219 bool core::find_blockchain_supplement(const uint64_t req_start_block, const std::list<crypto::hash>& qblock_ids, std::vector<std::pair<std::pair<cryptonote::blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, cryptonote::blobdata> > > >& blocks, uint64_t& total_height, uint64_t& start_height, bool pruned, bool get_miner_tx_hash, size_t max_block_count, size_t max_tx_count) const
1220 {
1221 return m_blockchain_storage.find_blockchain_supplement(req_start_block, qblock_ids, blocks, total_height, start_height, pruned, get_miner_tx_hash, max_block_count, max_tx_count);
1222 }
1223 //-----------------------------------------------------------------------------------------------
1224 bool core::get_outs(const COMMAND_RPC_GET_OUTPUTS_BIN::request& req, COMMAND_RPC_GET_OUTPUTS_BIN::response& res) const
1225 {
1226 return m_blockchain_storage.get_outs(req, res);
1227 }
1228 //-----------------------------------------------------------------------------------------------
1229 bool core::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, uint64_t &start_height, std::vector<uint64_t> &distribution, uint64_t &base) const
1230 {
1231 return m_blockchain_storage.get_output_distribution(amount, from_height, to_height, start_height, distribution, base);
1232 }
1233 //-----------------------------------------------------------------------------------------------
1234 bool core::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) const
1235 {
1236 return m_blockchain_storage.get_tx_outputs_gindexs(tx_id, indexs);
1237 }
1238 //-----------------------------------------------------------------------------------------------
1239 bool core::get_tx_outputs_gindexs(const crypto::hash& tx_id, size_t n_txes, std::vector<std::vector<uint64_t>>& indexs) const
1240 {
1241 return m_blockchain_storage.get_tx_outputs_gindexs(tx_id, n_txes, indexs);
1242 }
1243 //-----------------------------------------------------------------------------------------------
1244 void core::pause_mine()
1245 {
1246 m_miner.pause();
1247 }
1248 //-----------------------------------------------------------------------------------------------
1249 void core::resume_mine()
1250 {
1251 m_miner.resume();
1252 }
1253 //-----------------------------------------------------------------------------------------------
1254 block_complete_entry get_block_complete_entry(block& b, tx_memory_pool &pool)
1255 {
1256 block_complete_entry bce;
1257 bce.block = cryptonote::block_to_blob(b);
1258 bce.block_weight = 0; // we can leave it to 0, those txes aren't pruned
1259 for (const auto &tx_hash: b.tx_hashes)
1260 {
1261 cryptonote::blobdata txblob;
1262 CHECK_AND_ASSERT_THROW_MES(pool.get_transaction(tx_hash, txblob, relay_category::all), "Transaction not found in pool");
1263 bce.txs.push_back({txblob, crypto::null_hash});
1264 }
1265 return bce;
1266 }
1267 //-----------------------------------------------------------------------------------------------
1268 bool core::handle_block_found(block& b, block_verification_context &bvc)
1269 {
1270 bvc = {};
1271 m_miner.pause();
1272 std::vector<block_complete_entry> blocks;
1273 try
1274 {
1275 blocks.push_back(get_block_complete_entry(b, m_mempool));
1276 }
1277 catch (const std::exception &e)
1278 {
1279 m_miner.resume();
1280 return false;
1281 }
1282 std::vector<block> pblocks;
1283 if (!prepare_handle_incoming_blocks(blocks, pblocks))
1284 {
1285 MERROR("Block found, but failed to prepare to add");
1286 m_miner.resume();
1287 return false;
1288 }
1289 m_blockchain_storage.add_new_block(b, bvc);
1290 cleanup_handle_incoming_blocks(true);
1291 //anyway - update miner template
1292 update_miner_block_template();
1293 m_miner.resume();
1294
1295
1296 CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "mined block failed verification");
1297 if(bvc.m_added_to_main_chain)
1298 {
1299 cryptonote_connection_context exclude_context = {};
1300 NOTIFY_NEW_FLUFFY_BLOCK::request arg{};
1301 arg.current_blockchain_height = m_blockchain_storage.get_current_blockchain_height();
1302 std::vector<crypto::hash> missed_txs;
1303 std::vector<cryptonote::blobdata> txs;
1304 m_blockchain_storage.get_transactions_blobs(b.tx_hashes, txs, missed_txs);
1305 if(missed_txs.size() && m_blockchain_storage.get_block_id_by_height(get_block_height(b)) != get_block_hash(b))
1306 {
1307 LOG_PRINT_L1("Block found but, seems that reorganize just happened after that, do not relay this block");
1308 return true;
1309 }
1310 CHECK_AND_ASSERT_MES(txs.size() == b.tx_hashes.size() && !missed_txs.size(), false, "can't find some transactions in found block:" << get_block_hash(b) << " txs.size()=" << txs.size()
1311 << ", b.tx_hashes.size()=" << b.tx_hashes.size() << ", missed_txs.size()" << missed_txs.size());
1312
1313 block_to_blob(b, arg.b.block);
1314 //pack transactions
1315 for(auto& tx: txs)
1316 arg.b.txs.push_back({tx, crypto::null_hash});
1317
1318 m_pprotocol->relay_block(arg, exclude_context);
1319 }
1320 return true;
1321 }
1322 //-----------------------------------------------------------------------------------------------
1323 bool core::is_synchronized() const
1324 {
1325 return m_pprotocol != nullptr && m_pprotocol->is_synchronized();
1326 }
1327 //-----------------------------------------------------------------------------------------------
1328 void core::on_synchronized()
1329 {
1330 m_miner.on_synchronized();
1331 }
1332 //-----------------------------------------------------------------------------------------------
1333 void core::safesyncmode(const bool onoff)
1334 {
1335 m_blockchain_storage.safesyncmode(onoff);
1336 }
1337 //-----------------------------------------------------------------------------------------------
1338 bool core::add_new_block(const block& b, block_verification_context& bvc,
1339 pool_supplement& extra_block_txs)
1340 {
1341 return m_blockchain_storage.add_new_block(b, bvc, extra_block_txs);
1342 }
1343 //-----------------------------------------------------------------------------------------------
1344 bool core::prepare_handle_incoming_blocks(const std::vector<block_complete_entry> &blocks_entry, std::vector<block> &blocks)
1345 {
1346 m_incoming_tx_lock.lock();
1347 if (!m_blockchain_storage.prepare_handle_incoming_blocks(blocks_entry, blocks))
1348 {
1349 cleanup_handle_incoming_blocks(false);
1350 return false;
1351 }
1352 return true;
1353 }
1354
1355 //-----------------------------------------------------------------------------------------------
1356 bool core::cleanup_handle_incoming_blocks(bool force_sync)
1357 {
1358 bool success = false;
1359 try {
1360 success = m_blockchain_storage.cleanup_handle_incoming_blocks(force_sync);
1361 }
1362 catch (...) {}
1363 m_incoming_tx_lock.unlock();
1364 return success;
1365 }
1366
1367 //-----------------------------------------------------------------------------------------------
1368 bool core::handle_incoming_block(const blobdata& block_blob, const block *b,
1369 block_verification_context& bvc, bool update_miner_blocktemplate)
1370 {
1371 pool_supplement ps{};
1372 return handle_incoming_block(block_blob, b, bvc, ps, update_miner_blocktemplate);
1373 }
1374
1375 //-----------------------------------------------------------------------------------------------
1376 bool core::handle_incoming_block(const blobdata& block_blob, const block *b,
1377 block_verification_context& bvc, pool_supplement& extra_block_txs, bool update_miner_blocktemplate)
1378 {
1379 TRY_ENTRY();
1380
1381 bvc = {};
1382
1383 if (!check_incoming_block_size(block_blob))
1384 {
1385 bvc.m_verifivation_failed = true;
1386 return false;
1387 }
1388
1389 if (((size_t)-1) <= 0xffffffff && block_blob.size() >= 0x3fffffff)
1390 MWARNING("This block's size is " << block_blob.size() << ", closing on the 32 bit limit");
1391
1392 block lb;
1393 if (!b)
1394 {
1395 crypto::hash block_hash;
1396 if(!parse_and_validate_block_from_blob(block_blob, lb, block_hash))
1397 {
1398 LOG_PRINT_L1("Failed to parse and validate new block");
1399 bvc.m_verifivation_failed = true;
1400 return false;
1401 }
1402 b = &lb;
1403 }
1404 add_new_block(*b, bvc, extra_block_txs);
1405 if(update_miner_blocktemplate && bvc.m_added_to_main_chain)
1406 update_miner_block_template();
1407 return true;
1408
1409 CATCH_ENTRY_L0("core::handle_incoming_block()", false);
1410 }
1411 //-----------------------------------------------------------------------------------------------
1412 bool core::handle_single_incoming_block(const blobdata& block_blob,
1413 const block *b,
1414 block_verification_context& bvc,
1415 pool_supplement& extra_block_txs,
1416 bool update_miner_blocktemplate)
1417 {
1418 // Note: this estimate can be quite far off since fluffy blocks won't contain all their
1419 // transactions in the payload, but also this value doesn't *need* to be super precise. It
1420 // is used to trigger database backing store syncing once it hits a threshold, and since
1421 // we under-count the byte size here, it might result in under-syncing the backing store.
1422 // If force refresh is enabled, though, which the user turns on if they are vigilant about
1423 // saving each block, then it doesn't matter either way: cleanup_handle_incoming_blocks()
1424 // always triggers a sync.
1425 size_t block_total_bytes = block_blob.size();
1426 for (const auto &t : extra_block_txs.txs_by_txid)
1427 block_total_bytes += t.second.second.size();
1428
1429 CRITICAL_REGION_LOCAL(m_incoming_tx_lock);
1430
1431 // Match each call to prepare_handle_incoming_block_no_preprocess() with a call to
1432 // cleanup_handle_incoming_blocks()
1433 m_blockchain_storage.prepare_handle_incoming_block_no_preprocess(block_total_bytes);
1434 const auto auto_cleanup = epee::misc_utils::create_scope_leave_handler([this](){
1435 this->m_blockchain_storage.cleanup_handle_incoming_blocks();
1436 });
1437
1438 return handle_incoming_block(block_blob,
1439 b,
1440 bvc,
1441 extra_block_txs,
1442 update_miner_blocktemplate);
1443 }
1444 //-----------------------------------------------------------------------------------------------
1445 // Used by the RPC server to check the size of an incoming
1446 // block_blob
1447 bool core::check_incoming_block_size(const blobdata& block_blob) const
1448 {
1449 // note: we assume block weight is always >= block blob size, so we check incoming
1450 // blob size against the block weight limit, which acts as a sanity check without
1451 // having to parse/weigh first; in fact, since the block blob is the block header
1452 // plus the tx hashes, the weight will typically be much larger than the blob size
1453 if(block_blob.size() > m_blockchain_storage.get_current_cumulative_block_weight_limit() + BLOCK_SIZE_SANITY_LEEWAY)
1454 {
1455 LOG_PRINT_L1("WRONG BLOCK BLOB, sanity check failed on size " << block_blob.size() << ", rejected");
1456 return false;
1457 }
1458 return true;
1459 }
1460 //-----------------------------------------------------------------------------------------------
1461 crypto::hash core::get_tail_id() const
1462 {
1463 return m_blockchain_storage.get_tail_id();
1464 }
1465 //-----------------------------------------------------------------------------------------------
1466 difficulty_type core::get_block_cumulative_difficulty(uint64_t height) const
1467 {
1468 return m_blockchain_storage.get_db().get_block_cumulative_difficulty(height);
1469 }
1470 //-----------------------------------------------------------------------------------------------
1471 size_t core::get_pool_transactions_count(bool include_sensitive_txes) const
1472 {
1473 return m_mempool.get_transactions_count(include_sensitive_txes);
1474 }
1475 //-----------------------------------------------------------------------------------------------
1476 bool core::have_block_unlocked(const crypto::hash& id, int *where) const
1477 {
1478 return m_blockchain_storage.have_block_unlocked(id, where);
1479 }
1480 //-----------------------------------------------------------------------------------------------
1481 bool core::have_block(const crypto::hash& id, int *where) const
1482 {
1483 return m_blockchain_storage.have_block(id, where);
1484 }
1485 //-----------------------------------------------------------------------------------------------
1486 bool core::get_pool_transactions_info(const std::vector<crypto::hash>& txids, std::vector<std::pair<crypto::hash, tx_memory_pool::tx_details>>& txs, bool include_sensitive_txes) const
1487 {
1488 return m_mempool.get_transactions_info(txids, txs, include_sensitive_txes);
1489 }
1490 //-----------------------------------------------------------------------------------------------
1491 bool core::get_pool_transactions(std::vector<transaction>& txs, bool include_sensitive_data) const
1492 {
1493 m_mempool.get_transactions(txs, include_sensitive_data);
1494 return true;
1495 }
1496 //-----------------------------------------------------------------------------------------------
1497 bool core::get_pool_transaction_hashes(std::vector<crypto::hash>& txs, bool include_sensitive_data) const
1498 {
1499 m_mempool.get_transaction_hashes(txs, include_sensitive_data);
1500 return true;
1501 }
1502 //-----------------------------------------------------------------------------------------------
1503 bool core::get_pool_info(time_t start_time, bool include_sensitive_txes, size_t max_tx_count, std::vector<std::pair<crypto::hash, tx_memory_pool::tx_details>>& added_txs, std::vector<crypto::hash>& remaining_added_txids, std::vector<crypto::hash>& removed_txs, bool& incremental) const
1504 {
1505 return m_mempool.get_pool_info(start_time, include_sensitive_txes, max_tx_count, added_txs, remaining_added_txids, removed_txs, incremental);
1506 }
1507 //-----------------------------------------------------------------------------------------------
1508 bool core::get_pool_transaction_stats(struct txpool_stats& stats, bool include_sensitive_data) const
1509 {
1510 m_mempool.get_transaction_stats(stats, include_sensitive_data);
1511 return true;
1512 }
1513 //-----------------------------------------------------------------------------------------------
1514 bool core::get_pool_transaction(const crypto::hash &id, cryptonote::blobdata& tx, relay_category tx_category) const
1515 {
1516 return m_mempool.get_transaction(id, tx, tx_category);
1517 }
1518 //-----------------------------------------------------------------------------------------------
1519 bool core::pool_has_tx(const crypto::hash &id) const
1520 {
1521 return m_mempool.have_tx(id, relay_category::legacy);
1522 }
1523 //-----------------------------------------------------------------------------------------------
1524 bool core::get_pool_transactions_and_spent_keys_info(std::vector<tx_info>& tx_infos, std::vector<spent_key_image_info>& key_image_infos, bool include_sensitive_data) const
1525 {
1526 return m_mempool.get_transactions_and_spent_keys_info(tx_infos, key_image_infos, include_sensitive_data);
1527 }
1528 //-----------------------------------------------------------------------------------------------
1529 bool core::get_pool_for_rpc(std::vector<cryptonote::rpc::tx_in_pool>& tx_infos, cryptonote::rpc::key_images_with_tx_hashes& key_image_infos) const
1530 {
1531 return m_mempool.get_pool_for_rpc(tx_infos, key_image_infos);
1532 }
1533 //-----------------------------------------------------------------------------------------------
1534 bool core::get_short_chain_history(std::list<crypto::hash>& ids) const
1535 {
1536 return m_blockchain_storage.get_short_chain_history(ids);
1537 }
1538 //-----------------------------------------------------------------------------------------------
1539 bool core::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp, cryptonote_connection_context& context)
1540 {
1541 return m_blockchain_storage.handle_get_objects(arg, rsp);
1542 }
1543 //-----------------------------------------------------------------------------------------------
1544 crypto::hash core::get_block_id_by_height(uint64_t height) const
1545 {
1546 return m_blockchain_storage.get_block_id_by_height(height);
1547 }
1548 //-----------------------------------------------------------------------------------------------
1549 bool core::get_block_by_hash(const crypto::hash &h, block &blk, bool *orphan) const
1550 {
1551 return m_blockchain_storage.get_block_by_hash(h, blk, orphan);
1552 }
1553 //-----------------------------------------------------------------------------------------------
1554 std::string core::print_pool(bool short_format) const
1555 {
1556 return m_mempool.print_pool(short_format);
1557 }
1558 //-----------------------------------------------------------------------------------------------
1559 bool core::update_miner_block_template()
1560 {
1561 m_miner.on_block_chain_update();
1562 return true;
1563 }
1564 //-----------------------------------------------------------------------------------------------
1565 bool core::on_idle()
1566 {
1567 if(!m_starter_message_showed)
1568 {
1569 std::string main_message;
1570 if (m_offline)
1571 main_message = "The daemon is running offline and will not attempt to sync to the Monero network.";
1572 else
1573 main_message = "The daemon will start synchronizing with the network. This may take a long time to complete.";
1574 MGINFO_YELLOW(ENDL << "**********************************************************************" << ENDL
1575 << main_message << ENDL
1576 << ENDL
1577 << "You can set the level of process detailization through \"set_log <level|categories>\" command," << ENDL
1578 << "where <level> is between 0 (no details) and 4 (very verbose), or custom category based levels (eg, *:WARNING)." << ENDL
1579 << ENDL
1580 << "Use the \"help\" command to see the list of available commands." << ENDL
1581 << "Use \"help <command>\" to see a command's documentation." << ENDL
1582 << "**********************************************************************" << ENDL);
1583 m_starter_message_showed = true;
1584 }
1585
1586 relay_txpool_transactions(); // txpool handles periodic DB checking
1587 m_check_updates_interval.do_call(boost::bind(&core::check_updates, this));
1588 m_check_disk_space_interval.do_call(boost::bind(&core::check_disk_space, this));
1589 m_block_rate_interval.do_call(boost::bind(&core::check_block_rate, this));
1590 m_blockchain_pruning_interval.do_call(boost::bind(&core::update_blockchain_pruning, this));
1591 m_diff_recalc_interval.do_call(boost::bind(&core::recalculate_difficulties, this));
1592 m_miner.on_idle();
1593 m_mempool.on_idle();
1594 return true;
1595 }
1596 //-----------------------------------------------------------------------------------------------
1597 uint8_t core::get_ideal_hard_fork_version() const
1598 {
1599 return get_blockchain_storage().get_ideal_hard_fork_version();
1600 }
1601 //-----------------------------------------------------------------------------------------------
1602 uint8_t core::get_ideal_hard_fork_version(uint64_t height) const
1603 {
1604 return get_blockchain_storage().get_ideal_hard_fork_version(height);
1605 }
1606 //-----------------------------------------------------------------------------------------------
1607 uint8_t core::get_hard_fork_version(uint64_t height) const
1608 {
1609 return get_blockchain_storage().get_hard_fork_version(height);
1610 }
1611 //-----------------------------------------------------------------------------------------------
1612 uint64_t core::get_earliest_ideal_height_for_version(uint8_t version) const
1613 {
1614 return get_blockchain_storage().get_earliest_ideal_height_for_version(version);
1615 }
1616 //-----------------------------------------------------------------------------------------------
1617 bool core::check_updates()
1618 {
1619 static const char software[] = "monero";
1620 #ifdef BUILD_TAG
1621 static const char buildtag[] = BOOST_PP_STRINGIZE(BUILD_TAG);
1622 static const char subdir[] = "cli"; // because it can never be simple
1623 #else
1624 static const char buildtag[] = "source";
1625 static const char subdir[] = "source"; // because it can never be simple
1626 #endif
1627
1628 if (m_offline)
1629 return true;
1630
1631 if (check_updates_level == UPDATES_DISABLED)
1632 return true;
1633
1634 std::string version, hash;
1635 MCDEBUG("updates", "Checking for a new " << software << " version for " << buildtag);
1636 if (!tools::check_updates(software, buildtag, version, hash))
1637 return false;
1638
1639 if (tools::vercmp(version.c_str(), MONERO_VERSION) <= 0)
1640 {
1641 m_update_available = false;
1642 return true;
1643 }
1644
1645 std::string url = tools::get_update_url(software, subdir, buildtag, version, true);
1646 MCLOG_CYAN(el::Level::Info, "global", "Version " << version << " of " << software << " for " << buildtag << " is available: " << url << ", SHA256 hash " << hash);
1647 m_update_available = true;
1648
1649 if (check_updates_level == UPDATES_NOTIFY)
1650 return true;
1651
1652 url = tools::get_update_url(software, subdir, buildtag, version, false);
1653 std::string filename;
1654 const char *slash = strrchr(url.c_str(), '/');
1655 if (slash)
1656 filename = slash + 1;
1657 else
1658 filename = std::string(software) + "-update-" + version;
1659 boost::filesystem::path path(epee::string_tools::get_current_module_folder());
1660 path /= filename;
1661
1662 boost::unique_lock<boost::mutex> lock(m_update_mutex);
1663
1664 if (m_update_download != 0)
1665 {
1666 MCDEBUG("updates", "Already downloading update");
1667 return true;
1668 }
1669
1670 crypto::hash file_hash;
1671 if (!tools::sha256sum(path.string(), file_hash) || (hash != epee::string_tools::pod_to_hex(file_hash)))
1672 {
1673 MCDEBUG("updates", "We don't have that file already, downloading");
1674 const std::string tmppath = path.string() + ".tmp";
1675 if (epee::file_io_utils::is_file_exist(tmppath))
1676 {
1677 MCDEBUG("updates", "We have part of the file already, resuming download");
1678 }
1679 m_last_update_length = 0;
1680 m_update_download = tools::download_async(tmppath, url, [this, hash, path](const std::string &tmppath, const std::string &uri, bool success) {
1681 bool remove = false, good = true;
1682 if (success)
1683 {
1684 crypto::hash file_hash;
1685 if (!tools::sha256sum(tmppath, file_hash))
1686 {
1687 MCERROR("updates", "Failed to hash " << tmppath);
1688 remove = true;
1689 good = false;
1690 }
1691 else if (hash != epee::string_tools::pod_to_hex(file_hash))
1692 {
1693 MCERROR("updates", "Download from " << uri << " does not match the expected hash");
1694 remove = true;
1695 good = false;
1696 }
1697 }
1698 else
1699 {
1700 MCERROR("updates", "Failed to download " << uri);
1701 good = false;
1702 }
1703 boost::unique_lock<boost::mutex> lock(m_update_mutex);
1704 m_update_download = 0;
1705 if (success && !remove)
1706 {
1707 std::error_code e = tools::replace_file(tmppath, path.string());
1708 if (e)
1709 {
1710 MCERROR("updates", "Failed to rename downloaded file");
1711 good = false;
1712 }
1713 }
1714 else if (remove)
1715 {
1716 if (!boost::filesystem::remove(tmppath))
1717 {
1718 MCERROR("updates", "Failed to remove invalid downloaded file");
1719 good = false;
1720 }
1721 }
1722 if (good)
1723 MCLOG_CYAN(el::Level::Info, "updates", "New version downloaded to " << path.string());
1724 }, [this](const std::string &path, const std::string &uri, size_t length, ssize_t content_length) {
1725 if (length >= m_last_update_length + 1024 * 1024 * 10)
1726 {
1727 m_last_update_length = length;
1728 MCDEBUG("updates", "Downloaded " << length << "/" << (content_length ? std::to_string(content_length) : "unknown"));
1729 }
1730 return true;
1731 });
1732 }
1733 else
1734 {
1735 MCDEBUG("updates", "We already have " << path << " with expected hash");
1736 }
1737
1738 lock.unlock();
1739
1740 if (check_updates_level == UPDATES_DOWNLOAD)
1741 return true;
1742
1743 MCERROR("updates", "Download/update not implemented yet");
1744 return true;
1745 }
1746 //-----------------------------------------------------------------------------------------------
1747 bool core::check_disk_space()
1748 {
1749 uint64_t free_space = get_free_space();
1750 if (free_space < 1ull * 1024 * 1024 * 1024) // 1 GB
1751 {
1752 const el::Level level = el::Level::Warning;
1753 MCLOG_RED(level, "global", "Free space is below 1 GB on " << m_config_folder);
1754 }
1755 return true;
1756 }
1757 //-----------------------------------------------------------------------------------------------
1758 double factorial(unsigned int n)
1759 {
1760 if (n <= 1)
1761 return 1.0;
1762 double f = n;
1763 while (n-- > 1)
1764 f *= n;
1765 return f;
1766 }
1767 //-----------------------------------------------------------------------------------------------
1768 static double probability1(unsigned int blocks, unsigned int expected)
1769 {
1770 // https://www.umass.edu/wsp/resources/poisson/#computing
1771 return pow(expected, blocks) / (factorial(blocks) * exp(expected));
1772 }
1773 //-----------------------------------------------------------------------------------------------
1774 static double probability(unsigned int blocks, unsigned int expected)
1775 {
1776 double p = 0.0;
1777 if (blocks <= expected)
1778 {
1779 for (unsigned int b = 0; b <= blocks; ++b)
1780 p += probability1(b, expected);
1781 }
1782 else if (blocks > expected)
1783 {
1784 for (unsigned int b = blocks; b <= expected * 3 /* close enough */; ++b)
1785 p += probability1(b, expected);
1786 }
1787 return p;
1788 }
1789 //-----------------------------------------------------------------------------------------------
1790 bool core::check_block_rate()
1791 {
1792 if (m_offline || m_nettype == FAKECHAIN || m_target_blockchain_height > get_current_blockchain_height() || m_target_blockchain_height == 0)
1793 {
1794 MDEBUG("Not checking block rate, offline or syncing");
1795 return true;
1796 }
1797
1798 static constexpr double threshold = 1. / (864000 / DIFFICULTY_TARGET_V2); // one false positive every 10 days
1799 static constexpr unsigned int max_blocks_checked = 150;
1800
1801 const time_t now = time(NULL);
1802 const std::vector<time_t> timestamps = m_blockchain_storage.get_last_block_timestamps(max_blocks_checked);
1803
1804 static const unsigned int seconds[] = { 5400, 3600, 1800, 1200, 600 };
1805 for (size_t n = 0; n < sizeof(seconds)/sizeof(seconds[0]); ++n)
1806 {
1807 unsigned int b = 0;
1808 const time_t time_boundary = now - static_cast<time_t>(seconds[n]);
1809 for (time_t ts: timestamps) b += ts >= time_boundary;
1810 const double p = probability(b, seconds[n] / DIFFICULTY_TARGET_V2);
1811 MDEBUG("blocks in the last " << seconds[n] / 60 << " minutes: " << b << " (probability " << p << ")");
1812 if (p < threshold)
1813 {
1814 MWARNING("There were " << b << (b == max_blocks_checked ? " or more" : "") << " blocks in the last " << seconds[n] / 60 << " minutes, there might be large hash rate changes, or we might be partitioned, cut off from the Monero network or under attack, or your computer's time is off. Or it could be just sheer bad luck.");
1815
1816 std::shared_ptr<tools::Notify> block_rate_notify = m_block_rate_notify;
1817 if (block_rate_notify)
1818 {
1819 auto expected = seconds[n] / DIFFICULTY_TARGET_V2;
1820 block_rate_notify->notify("%t", std::to_string(seconds[n] / 60).c_str(), "%b", std::to_string(b).c_str(), "%e", std::to_string(expected).c_str(), NULL);
1821 }
1822
1823 break; // no need to look further
1824 }
1825 }
1826
1827 return true;
1828 }
1829 //-----------------------------------------------------------------------------------------------
1830 bool core::recalculate_difficulties()
1831 {
1832 m_blockchain_storage.recalculate_difficulties();
1833 return true;
1834 }
1835 //-----------------------------------------------------------------------------------------------
1836 void core::flush_invalid_blocks()
1837 {
1838 m_blockchain_storage.flush_invalid_blocks();
1839 }
1840 //-----------------------------------------------------------------------------------------------
1841 bool core::get_txpool_complement(const std::vector<crypto::hash> &hashes, std::vector<cryptonote::blobdata> &txes)
1842 {
1843 return m_mempool.get_complement(hashes, txes);
1844 }
1845 //-----------------------------------------------------------------------------------------------
1846 bool core::update_blockchain_pruning()
1847 {
1848 return m_blockchain_storage.update_blockchain_pruning();
1849 }
1850 //-----------------------------------------------------------------------------------------------
1851 bool core::check_blockchain_pruning()
1852 {
1853 return m_blockchain_storage.check_blockchain_pruning();
1854 }
1855 //-----------------------------------------------------------------------------------------------
1856 void core::set_target_blockchain_height(uint64_t target_blockchain_height)
1857 {
1858 m_target_blockchain_height = target_blockchain_height;
1859 }
1860 //-----------------------------------------------------------------------------------------------
1861 uint64_t core::get_target_blockchain_height() const
1862 {
1863 return m_target_blockchain_height;
1864 }
1865 //-----------------------------------------------------------------------------------------------
1866 uint64_t core::prevalidate_block_hashes(uint64_t height, const std::vector<crypto::hash> &hashes, const std::vector<uint64_t> &weights)
1867 {
1868 return get_blockchain_storage().prevalidate_block_hashes(height, hashes, weights);
1869 }
1870 //-----------------------------------------------------------------------------------------------
1871 uint64_t core::get_free_space() const
1872 {
1873 boost::filesystem::path path(m_config_folder);
1874 boost::filesystem::space_info si = boost::filesystem::space(path);
1875 return si.available;
1876 }
1877 //-----------------------------------------------------------------------------------------------
1878 uint32_t core::get_blockchain_pruning_seed() const
1879 {
1880 return get_blockchain_storage().get_blockchain_pruning_seed();
1881 }
1882 //-----------------------------------------------------------------------------------------------
1883 bool core::prune_blockchain(uint32_t pruning_seed)
1884 {
1885 return get_blockchain_storage().prune_blockchain(pruning_seed);
1886 }
1887 //-----------------------------------------------------------------------------------------------
1888 bool core::is_within_compiled_block_hash_area(uint64_t height) const
1889 {
1890 return get_blockchain_storage().is_within_compiled_block_hash_area(height);
1891 }
1892 //-----------------------------------------------------------------------------------------------
1893 bool core::has_block_weights(uint64_t height, uint64_t nblocks) const
1894 {
1895 return get_blockchain_storage().has_block_weights(height, nblocks);
1896 }
1897 //-----------------------------------------------------------------------------------------------
1898 std::time_t core::get_start_time() const
1899 {
1900 return start_time;
1901 }
1902 //-----------------------------------------------------------------------------------------------
1903 void core::graceful_exit()
1904 {
1905 raise(SIGTERM);
1906 }
1907 }