Debian Codegraph @

src/blockchain_utilities/blockchain_import.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 #include <atomic>
30 #include <cstdio>
31 #include <algorithm>
32 #include <fstream>
33
34 #include <boost/filesystem.hpp>
35 #include <boost/algorithm/string.hpp>
36 #include <unistd.h>
37 #include "misc_log_ex.h"
38 #include "bootstrap_file.h"
39 #include "bootstrap_serialization.h"
40 #include "blocks/blocks.h"
41 #include "cryptonote_basic/cryptonote_format_utils.h"
42 #include "serialization/binary_utils.h" // dump_binary(), parse_binary()
43 #include "serialization/json_utils.h" // dump_json()
44 #include "include_base_utils.h"
45 #include "cryptonote_core/cryptonote_core.h"
46
47 #undef MONERO_DEFAULT_LOG_CATEGORY
48 #define MONERO_DEFAULT_LOG_CATEGORY "bcutil"
49
50 namespace
51 {
52 // CONFIG
53 bool opt_batch = true;
54 bool opt_verify = true; // use add_new_block, which does verification before calling add_block
55 bool opt_resume = true;
56 bool opt_testnet = true;
57 bool opt_stagenet = true;
58
59 // number of blocks per batch transaction
60 // adjustable through command-line argument according to available RAM
61 #if ARCH_WIDTH != 32
62 uint64_t db_batch_size = 20000;
63 #else
64 // set a lower default batch size, pending possible LMDB issue with large transaction size
65 uint64_t db_batch_size = 100;
66 #endif
67
68 // when verifying, use a smaller default batch size so progress is more
69 // frequently saved
70 uint64_t db_batch_size_verify = 5000;
71
72 std::string refresh_string = "\r \r";
73 }
74
75
76
77 namespace po = boost::program_options;
78
79 using namespace cryptonote;
80 using namespace epee;
81
82 // db_mode: safe, fast, fastest
83 int get_db_flags_from_mode(const std::string& db_mode)
84 {
85 int db_flags = 0;
86 if (db_mode == "safe")
87 db_flags = DBF_SAFE;
88 else if (db_mode == "fast")
89 db_flags = DBF_FAST;
90 else if (db_mode == "fastest")
91 db_flags = DBF_FASTEST;
92 return db_flags;
93 }
94
95 int pop_blocks(cryptonote::core& core, int num_blocks)
96 {
97 bool use_batch = opt_batch;
98
99 if (use_batch)
100 core.get_blockchain_storage().get_db().batch_start();
101
102 int quit = 0;
103 block popped_block;
104 std::vector<transaction> popped_txs;
105 for (int i=0; i < num_blocks; ++i)
106 {
107 // simple_core.m_storage.pop_block_from_blockchain() is private, so call directly through db
108 core.get_blockchain_storage().get_db().pop_block(popped_block, popped_txs);
109 quit = 1;
110 }
111
112
113 if (use_batch)
114 {
115 if (quit > 1)
116 {
117 // There was an error, so don't commit pending data.
118 // Destructor will abort write txn.
119 }
120 else
121 {
122 core.get_blockchain_storage().get_db().batch_stop();
123 }
124 core.get_blockchain_storage().get_db().show_stats();
125 }
126
127 return num_blocks;
128 }
129
130 int check_flush(cryptonote::core &core, std::vector<block_complete_entry> &blocks, bool force)
131 {
132 if (blocks.empty())
133 return 0;
134 if (!force && blocks.size() < db_batch_size)
135 return 0;
136
137 // wait till we can verify a full HOH without extra, for speed
138 uint64_t new_height = core.get_blockchain_storage().get_db().height() + blocks.size();
139 if (!force && new_height % HASH_OF_HASHES_STEP)
140 return 0;
141
142 std::vector<crypto::hash> hashes;
143 for (const auto &b: blocks)
144 {
145 cryptonote::block block;
146 if (!parse_and_validate_block_from_blob(b.block, block))
147 {
148 MERROR("Failed to parse block: "
149 << epee::string_tools::buff_to_hex_nodelimer(b.block));
150 core.cleanup_handle_incoming_blocks();
151 return 1;
152 }
153 hashes.push_back(cryptonote::get_block_hash(block));
154 }
155 core.prevalidate_block_hashes(core.get_blockchain_storage().get_db().height(), hashes, {});
156
157 std::vector<block> pblocks;
158 if (!core.prepare_handle_incoming_blocks(blocks, pblocks))
159 {
160 MERROR("Failed to prepare to add blocks");
161 return 1;
162 }
163 if (!pblocks.empty() && pblocks.size() != blocks.size())
164 {
165 MERROR("Unexpected parsed blocks size");
166 core.cleanup_handle_incoming_blocks();
167 return 1;
168 }
169
170 size_t blockidx = 0;
171 for(const block_complete_entry& block_entry: blocks)
172 {
173 // process transactions
174 for(auto& tx_blob: block_entry.txs)
175 {
176 tx_verification_context tvc = AUTO_VAL_INIT(tvc);
177 CHECK_AND_ASSERT_THROW_MES(tx_blob.prunable_hash == crypto::null_hash,
178 "block entry must not contain pruned txs");
179 core.handle_incoming_tx(tx_blob.blob, tvc, relay_method::block, true);
180 if(tvc.m_verifivation_failed)
181 {
182 cryptonote::transaction transaction;
183 if (cryptonote::parse_and_validate_tx_from_blob(tx_blob.blob, transaction))
184 MERROR("Transaction verification failed, tx_id = " << cryptonote::get_transaction_hash(transaction));
185 else
186 MERROR("Transaction verification failed, transaction is unparsable");
187 core.cleanup_handle_incoming_blocks();
188 return 1;
189 }
190 }
191
192 // process block
193
194 block_verification_context bvc = {};
195 pool_supplement ps{};
196
197 core.handle_incoming_block(block_entry.block, pblocks.empty() ? NULL : &pblocks[blockidx++], bvc, ps, false); // <--- process block
198
199 if(bvc.m_verifivation_failed)
200 {
201 cryptonote::block block;
202 if (cryptonote::parse_and_validate_block_from_blob(block_entry.block, block))
203 MERROR("Block verification failed, id = " << cryptonote::get_block_hash(block));
204 else
205 MERROR("Block verification failed, block is unparsable");
206 core.cleanup_handle_incoming_blocks();
207 return 1;
208 }
209 if(bvc.m_marked_as_orphaned)
210 {
211 MERROR("Block received at sync phase was marked as orphaned");
212 core.cleanup_handle_incoming_blocks();
213 return 1;
214 }
215
216 } // each download block
217 if (!core.cleanup_handle_incoming_blocks())
218 return 1;
219
220 blocks.clear();
221 return 0;
222 }
223
224 int import_from_file(cryptonote::core& core, const std::string& import_file_path, uint64_t block_stop=0)
225 {
226 // Reset stats, in case we're using newly created db, accumulating stats
227 // from addition of genesis block.
228 // This aligns internal db counts with importer counts.
229 core.get_blockchain_storage().get_db().reset_stats();
230
231 boost::filesystem::path fs_import_file_path(import_file_path);
232 boost::system::error_code ec;
233 if (!boost::filesystem::exists(fs_import_file_path, ec))
234 {
235 MFATAL("bootstrap file not found: " << fs_import_file_path);
236 return false;
237 }
238
239 uint64_t block_first;
240 uint64_t start_height = 1, seek_height;
241 if (opt_resume)
242 start_height = core.get_blockchain_storage().get_current_blockchain_height();
243
244 seek_height = start_height;
245 BootstrapFile bootstrap;
246 std::streampos pos;
247 // BootstrapFile bootstrap(import_file_path);
248 uint64_t total_source_blocks = bootstrap.count_blocks(import_file_path, pos, seek_height, block_first);
249 MINFO("bootstrap file last block number: " << total_source_blocks+block_first-1 << " (zero-based height) total blocks: " << total_source_blocks);
250
251 if (total_source_blocks+block_first-1 <= start_height)
252 {
253 return false;
254 }
255
256 std::cout << ENDL;
257 std::cout << "Preparing to read blocks..." << ENDL;
258 std::cout << ENDL;
259
260 std::ifstream import_file;
261 import_file.open(import_file_path, std::ios_base::binary | std::ifstream::in);
262
263 uint64_t h = 0;
264 uint64_t num_imported = 0;
265 if (import_file.fail())
266 {
267 MFATAL("import_file.open() fail");
268 return false;
269 }
270
271 // 4 byte magic + (currently) 1024 byte header structures
272 uint8_t major_version, minor_version;
273 uint64_t dummy;
274 bootstrap.seek_to_first_chunk(import_file, major_version, minor_version, dummy, dummy);
275
276 std::string str1;
277 char buffer1[1024];
278 char buffer_block[BUFFER_SIZE];
279 block b;
280 transaction tx;
281 int quit = 0;
282 uint64_t bytes_read;
283
284 // Note that a new blockchain will start with block number 0 (total blocks: 1)
285 // due to genesis block being added at initialization.
286
287 if (! block_stop)
288 {
289 block_stop = total_source_blocks+block_first - 1;
290 }
291
292 // These are what we'll try to use, and they don't have to be a determination
293 // from source and destination blockchains, but those are the defaults.
294 MINFO("start block: " << start_height << " stop block: " <<
295 block_stop);
296
297 bool use_batch = opt_batch && !opt_verify;
298
299 MINFO("Reading blockchain from bootstrap file...");
300 std::cout << ENDL;
301
302 std::vector<block_complete_entry> blocks;
303
304 // Skip to start_height before we start adding.
305 {
306 bool q2 = false;
307 import_file.seekg(pos);
308 bytes_read = bootstrap.count_bytes(import_file, start_height-seek_height, h, q2);
309 if (q2)
310 {
311 quit = 2;
312 goto quitting;
313 }
314 h = start_height;
315 }
316
317 if (use_batch)
318 {
319 uint64_t bytes, h2;
320 bool q2;
321 pos = import_file.tellg();
322 bytes = bootstrap.count_bytes(import_file, db_batch_size, h2, q2);
323 if (import_file.eof())
324 import_file.clear();
325 import_file.seekg(pos);
326 core.get_blockchain_storage().get_db().batch_start(db_batch_size, bytes);
327 }
328 while (! quit)
329 {
330 uint32_t chunk_size;
331 import_file.read(buffer1, sizeof(chunk_size));
332 // TODO: bootstrap.read_chunk();
333 if (! import_file) {
334 std::cout << refresh_string;
335 MINFO("End of file reached");
336 quit = 1;
337 break;
338 }
339 bytes_read += sizeof(chunk_size);
340
341 str1.assign(buffer1, sizeof(chunk_size));
342 if (! ::serialization::parse_binary(str1, chunk_size))
343 {
344 throw std::runtime_error("Error in deserialization of chunk size");
345 }
346 MDEBUG("chunk_size: " << chunk_size);
347
348 if (chunk_size > BUFFER_SIZE)
349 {
350 MWARNING("WARNING: chunk_size " << chunk_size << " > BUFFER_SIZE " << BUFFER_SIZE);
351 throw std::runtime_error("Aborting: chunk size exceeds buffer size");
352 }
353 if (chunk_size > CHUNK_SIZE_WARNING_THRESHOLD)
354 {
355 MINFO("NOTE: chunk_size " << chunk_size << " > " << CHUNK_SIZE_WARNING_THRESHOLD);
356 }
357 else if (chunk_size == 0) {
358 MFATAL("ERROR: chunk_size == 0");
359 return 2;
360 }
361 import_file.read(buffer_block, chunk_size);
362 if (! import_file) {
363 if (import_file.eof())
364 {
365 std::cout << refresh_string;
366 MINFO("End of file reached - file was truncated");
367 quit = 1;
368 break;
369 }
370 else
371 {
372 MFATAL("ERROR: unexpected end of file: bytes read before error: "
373 << import_file.gcount() << " of chunk_size " << chunk_size);
374 return 2;
375 }
376 }
377 bytes_read += chunk_size;
378 MDEBUG("Total bytes read: " << bytes_read);
379
380 if (h > block_stop)
381 {
382 std::cout << refresh_string << "block " << h-1
383 << " / " << block_stop
384 << "\r" << std::flush;
385 std::cout << ENDL << ENDL;
386 MINFO("Specified block number reached - stopping. block: " << h-1 << " total blocks: " << h);
387 quit = 1;
388 break;
389 }
390
391 try
392 {
393 str1.assign(buffer_block, chunk_size);
394 bootstrap::block_package bp;
395 bool res;
396 if (major_version == 0)
397 {
398 bootstrap::block_package_1 bp1;
399 res = ::serialization::parse_binary(str1, bp1);
400 if (res)
401 {
402 bp.block = std::move(bp1.block);
403 bp.txs = std::move(bp1.txs);
404 bp.block_weight = bp1.block_weight;
405 bp.cumulative_difficulty = bp1.cumulative_difficulty;
406 bp.coins_generated = bp1.coins_generated;
407 }
408 }
409 else
410 res = ::serialization::parse_binary(str1, bp);
411 if (!res)
412 throw std::runtime_error("Error in deserialization of chunk");
413
414 int display_interval = 1000;
415 int progress_interval = 10;
416 // NOTE: use of NUM_BLOCKS_PER_CHUNK is a placeholder in case multi-block chunks are later supported.
417 for (int chunk_ind = 0; chunk_ind < NUM_BLOCKS_PER_CHUNK; ++chunk_ind)
418 {
419 ++h;
420 if ((h-1) % display_interval == 0)
421 {
422 std::cout << refresh_string;
423 MDEBUG("loading block number " << h-1);
424 }
425 else
426 {
427 MDEBUG("loading block number " << h-1);
428 }
429 b = bp.block;
430 MDEBUG("block prev_id: " << b.prev_id << ENDL);
431
432 if ((h-1) % progress_interval == 0)
433 {
434 std::cout << refresh_string << "block " << h-1
435 << " / " << block_stop
436 << "\r" << std::flush;
437 }
438
439 if (opt_verify)
440 {
441 cryptonote::blobdata block;
442 cryptonote::block_to_blob(bp.block, block);
443 std::vector<tx_blob_entry> txs;
444 for (const auto &tx: bp.txs)
445 {
446 txs.push_back({cryptonote::blobdata(), crypto::null_hash});
447 cryptonote::tx_to_blob(tx, txs.back().blob);
448 }
449 block_complete_entry bce;
450 bce.pruned = false;
451 bce.block = std::move(block);
452 bce.txs = std::move(txs);
453 blocks.push_back(bce);
454 int ret = check_flush(core, blocks, false);
455 if (ret)
456 {
457 quit = 2; // make sure we don't commit partial block data
458 break;
459 }
460 }
461 else
462 {
463 std::vector<std::pair<transaction, blobdata>> txs;
464 std::vector<transaction> archived_txs;
465
466 archived_txs = bp.txs;
467
468 // tx number 1: coinbase tx
469 // tx number 2 onwards: archived_txs
470 for (const transaction &tx : archived_txs)
471 {
472 // add blocks with verification.
473 // for Blockchain and blockchain_storage add_new_block().
474 // for add_block() method, without (much) processing.
475 // don't add coinbase transaction to txs.
476 //
477 // because add_block() calls
478 // add_transaction(blk_hash, blk.miner_tx) first, and
479 // then a for loop for the transactions in txs.
480 txs.push_back(std::make_pair(tx, tx_to_blob(tx)));
481 }
482
483 size_t block_weight;
484 difficulty_type cumulative_difficulty;
485 uint64_t coins_generated;
486
487 block_weight = bp.block_weight;
488 cumulative_difficulty = bp.cumulative_difficulty;
489 coins_generated = bp.coins_generated;
490
491 try
492 {
493 uint64_t long_term_block_weight = core.get_blockchain_storage().get_next_long_term_block_weight(block_weight);
494 core.get_blockchain_storage().get_db().add_block(std::make_pair(b, block_to_blob(b)), block_weight, long_term_block_weight, cumulative_difficulty, coins_generated, txs);
495 }
496 catch (const std::exception& e)
497 {
498 std::cout << refresh_string;
499 MFATAL("Error adding block to blockchain: " << e.what());
500 quit = 2; // make sure we don't commit partial block data
501 break;
502 }
503
504 if (use_batch)
505 {
506 if ((h-1) % db_batch_size == 0)
507 {
508 uint64_t bytes, h2;
509 bool q2;
510 std::cout << refresh_string;
511 // zero-based height
512 std::cout << ENDL << "[- batch commit at height " << h-1 << " -]" << ENDL;
513 core.get_blockchain_storage().get_db().batch_stop();
514 pos = import_file.tellg();
515 bytes = bootstrap.count_bytes(import_file, db_batch_size, h2, q2);
516 import_file.seekg(pos);
517 core.get_blockchain_storage().get_db().batch_start(db_batch_size, bytes);
518 std::cout << ENDL;
519 core.get_blockchain_storage().get_db().show_stats();
520 }
521 }
522 }
523 ++num_imported;
524 }
525 }
526 catch (const std::exception& e)
527 {
528 std::cout << refresh_string;
529 MFATAL("exception while reading from file, height=" << h << ": " << e.what());
530 return 2;
531 }
532 } // while
533
534 quitting:
535 import_file.close();
536
537 if (opt_verify)
538 {
539 int ret = check_flush(core, blocks, true);
540 if (ret)
541 return ret;
542 }
543
544 if (use_batch)
545 {
546 if (quit > 1)
547 {
548 // There was an error, so don't commit pending data.
549 // Destructor will abort write txn.
550 }
551 else
552 {
553 core.get_blockchain_storage().get_db().batch_stop();
554 }
555 }
556
557 core.get_blockchain_storage().get_db().show_stats();
558 MINFO("Number of blocks imported: " << num_imported);
559 if (h > 0)
560 // TODO: if there was an error, the last added block is probably at zero-based height h-2
561 MINFO("Finished at block: " << h-1 << " total blocks: " << h);
562
563 std::cout << ENDL;
564 return 0;
565 }
566
567 int main(int argc, char* argv[])
568 {
569 TRY_ENTRY();
570
571 epee::string_tools::set_module_name_and_folder(argv[0]);
572
573 uint32_t log_level = 0;
574 uint64_t num_blocks = 0;
575 uint64_t block_stop = 0;
576 std::string m_config_folder;
577 std::string db_arg_str;
578
579 tools::on_startup();
580
581 std::string import_file_path;
582
583 po::options_description desc_cmd_only("Command line options");
584 po::options_description desc_cmd_sett("Command line options and settings options");
585 const command_line::arg_descriptor<std::string> arg_input_file = {"input-file", "Specify input file", "", true};
586 const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
587 const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop};
588 const command_line::arg_descriptor<uint64_t> arg_batch_size = {"batch-size", "", db_batch_size};
589 const command_line::arg_descriptor<uint64_t> arg_pop_blocks = {"pop-blocks", "Remove blocks from end of blockchain", num_blocks};
590 const command_line::arg_descriptor<bool> arg_drop_hf = {"drop-hard-fork", "Drop hard fork subdbs", false};
591 const command_line::arg_descriptor<bool> arg_count_blocks = {
592 "count-blocks"
593 , "Count blocks in bootstrap file and exit"
594 , false
595 };
596 const command_line::arg_descriptor<bool> arg_noverify = {"dangerous-unverified-import",
597 "Blindly trust the import file and use potentially malicious blocks and transactions during import (only enable if you exported the file yourself)", false};
598 const command_line::arg_descriptor<bool> arg_batch = {"batch",
599 "Batch transactions for faster import", true};
600 const command_line::arg_descriptor<bool> arg_resume = {"resume",
601 "Resume from current height if output database already exists", true};
602
603 command_line::add_arg(desc_cmd_sett, arg_input_file);
604 command_line::add_arg(desc_cmd_sett, arg_log_level);
605 command_line::add_arg(desc_cmd_sett, arg_batch_size);
606 command_line::add_arg(desc_cmd_sett, arg_block_stop);
607
608 command_line::add_arg(desc_cmd_only, arg_count_blocks);
609 command_line::add_arg(desc_cmd_only, arg_pop_blocks);
610 command_line::add_arg(desc_cmd_only, arg_drop_hf);
611 command_line::add_arg(desc_cmd_only, command_line::arg_help);
612
613 // call add_options() directly for these arguments since
614 // command_line helpers support only boolean switch, not boolean argument
615 desc_cmd_sett.add_options()
616 (arg_noverify.name, make_semantic(arg_noverify), arg_noverify.description)
617 (arg_batch.name, make_semantic(arg_batch), arg_batch.description)
618 (arg_resume.name, make_semantic(arg_resume), arg_resume.description)
619 ;
620
621 po::options_description desc_options("Allowed options");
622 desc_options.add(desc_cmd_only).add(desc_cmd_sett);
623 cryptonote::core::init_options(desc_options);
624
625 po::variables_map vm;
626 bool r = command_line::handle_error_helper(desc_options, [&]()
627 {
628 po::store(po::parse_command_line(argc, argv, desc_options), vm);
629 po::notify(vm);
630 return true;
631 });
632 if (! r)
633 return 1;
634
635 opt_verify = !command_line::get_arg(vm, arg_noverify);
636 opt_batch = command_line::get_arg(vm, arg_batch);
637 opt_resume = command_line::get_arg(vm, arg_resume);
638 block_stop = command_line::get_arg(vm, arg_block_stop);
639 db_batch_size = command_line::get_arg(vm, arg_batch_size);
640
641 if (command_line::get_arg(vm, command_line::arg_help))
642 {
643 std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
644 std::cout << desc_options << std::endl;
645 return 1;
646 }
647
648 if (! opt_batch && !command_line::is_arg_defaulted(vm, arg_batch_size))
649 {
650 std::cerr << "Error: batch-size set, but batch option not enabled" << ENDL;
651 return 1;
652 }
653 if (! db_batch_size)
654 {
655 std::cerr << "Error: batch-size must be > 0" << ENDL;
656 return 1;
657 }
658 if (opt_verify && command_line::is_arg_defaulted(vm, arg_batch_size))
659 {
660 // usually want batch size default lower if verify on, so progress can be
661 // frequently saved.
662 //
663 // currently, with Windows, default batch size is low, so ignore
664 // default db_batch_size_verify unless it's even lower
665 if (db_batch_size > db_batch_size_verify)
666 {
667 db_batch_size = db_batch_size_verify;
668 }
669 }
670
671 m_config_folder = command_line::get_arg(vm, cryptonote::arg_data_dir);
672
673 mlog_configure(mlog_get_default_log_path("monero-blockchain-import.log"), true);
674 if (!command_line::is_arg_defaulted(vm, arg_log_level))
675 mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
676 else
677 mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
678
679 MINFO("Starting...");
680
681 boost::filesystem::path fs_import_file_path;
682
683 if (command_line::has_arg(vm, arg_input_file))
684 fs_import_file_path = boost::filesystem::path(command_line::get_arg(vm, arg_input_file));
685 else
686 fs_import_file_path = boost::filesystem::path(m_config_folder) / "export" / BLOCKCHAIN_RAW;
687
688 import_file_path = fs_import_file_path.string();
689
690 if (command_line::has_arg(vm, arg_count_blocks))
691 {
692 BootstrapFile bootstrap;
693 bootstrap.count_blocks(import_file_path);
694 return 0;
695 }
696
697 MINFO("database: LMDB");
698 MINFO("verify: " << std::boolalpha << opt_verify << std::noboolalpha);
699 if (opt_batch)
700 {
701 MINFO("batch: " << std::boolalpha << opt_batch << std::noboolalpha
702 << " batch size: " << db_batch_size);
703 }
704 else
705 {
706 MINFO("batch: " << std::boolalpha << opt_batch << std::noboolalpha);
707 }
708 MINFO("resume: " << std::boolalpha << opt_resume << std::noboolalpha);
709 MINFO("nettype: " << (opt_testnet ? "testnet" : opt_stagenet ? "stagenet" : "mainnet"));
710
711 MINFO("bootstrap file path: " << import_file_path);
712 MINFO("database path: " << m_config_folder);
713
714 if (!opt_verify)
715 {
716 MCLOG_RED(el::Level::Warning, "global", "\n"
717 "Import is set to proceed WITHOUT VERIFICATION.\n"
718 "This is a DANGEROUS operation: if the file was tampered with in transit, or obtained from a malicious source,\n"
719 "you could end up with a compromised database. It is recommended to NOT use " << arg_noverify.name << ".\n"
720 "*****************************************************************************************\n"
721 "You have 90 seconds to press ^C or terminate this program before unverified import starts\n"
722 "*****************************************************************************************");
723 sleep(90);
724 }
725
726 cryptonote::cryptonote_protocol_stub pr; //TODO: stub only for this kind of test, make real validation of relayed objects
727 cryptonote::core core(&pr);
728
729 try
730 {
731
732 core.disable_dns_checkpoints(true);
733 #if defined(PER_BLOCK_CHECKPOINT)
734 const GetCheckpointsCallback& get_checkpoints = blocks::GetCheckpointsData;
735 #else
736 const GetCheckpointsCallback& get_checkpoints = nullptr;
737 #endif
738 if (!core.init(vm, nullptr, get_checkpoints))
739 {
740 std::cerr << "Failed to initialize core" << ENDL;
741 return 1;
742 }
743 core.get_blockchain_storage().get_db().set_batch_transactions(true);
744
745 if (!command_line::is_arg_defaulted(vm, arg_pop_blocks))
746 {
747 num_blocks = command_line::get_arg(vm, arg_pop_blocks);
748 MINFO("height: " << core.get_blockchain_storage().get_current_blockchain_height());
749 pop_blocks(core, num_blocks);
750 MINFO("height: " << core.get_blockchain_storage().get_current_blockchain_height());
751 return 0;
752 }
753
754 if (!command_line::is_arg_defaulted(vm, arg_drop_hf))
755 {
756 MINFO("Dropping hard fork tables...");
757 core.get_blockchain_storage().get_db().drop_hard_fork_info();
758 core.deinit();
759 return 0;
760 }
761
762 import_from_file(core, import_file_path, block_stop);
763
764 // ensure db closed
765 // - transactions properly checked and handled
766 // - disk sync if needed
767 //
768 core.deinit();
769 }
770 catch (const DB_ERROR& e)
771 {
772 std::cout << std::string("Error loading blockchain db: ") + e.what() + " -- shutting down now" << ENDL;
773 core.deinit();
774 return 1;
775 }
776
777 return 0;
778
779 CATCH_ENTRY("Import error", 1);
780 }