Debian Codegraph @

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