/**
     * Initialized the MicroCore object.
     *
     * Create BlockchainLMDB on the heap.
     * Open database files located in blockchain_path.
     * Initialize m_blockchain_storage with the BlockchainLMDB object.
     */
    bool
    MicroCore::init(const string& blockchain_path)
    {
        int db_flags = 0;

        //db_flags |= MDB_RDONLY;
        //db_flags |= MDB_NOLOCK;
        db_flags |= MDB_NOSYNC;

        BlockchainDB* db = nullptr;
        db = new BlockchainLMDB();

        try
        {
            // try opening lmdb database files
            db->open(blockchain_path, db_flags);
        }
        catch (const std::exception& e)
        {
            cerr << "Error opening database: " << e.what();
            return false;
        }

        // check if the blockchain database
        // is successful opened
        if(!db->is_open())
        {
            return false;
        }

        // initialize Blockchain object to manage
        // the database.
        return m_blockchain_storage.init(db, false);
    }
예제 #2
0
int main(int argc, char* argv[])
{
  TRY_ENTRY();

  epee::string_tools::set_module_name_and_folder(argv[0]);

  std::string default_db_type = "lmdb";

  std::string available_dbs = cryptonote::blockchain_db_types(", ");
  available_dbs = "available: " + available_dbs;

  uint32_t log_level = 0;

  tools::on_startup();

  boost::filesystem::path output_file_path;

  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<std::string> arg_log_level  = {"log-level",  "0-4 or categories", ""};
  const command_line::arg_descriptor<std::string> arg_database = {
    "database", available_dbs.c_str(), default_db_type
  };
  const command_line::arg_descriptor<bool> arg_rct_only  = {"rct-only", "Only work on ringCT outputs", false};
  const command_line::arg_descriptor<std::string> arg_input = {"input", ""};

  command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_database);
  command_line::add_arg(desc_cmd_sett, arg_rct_only);
  command_line::add_arg(desc_cmd_sett, arg_input);
  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);

  po::positional_options_description positional_options;
  positional_options.add(arg_input.name, -1);

  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    auto parser = po::command_line_parser(argc, argv).options(desc_options).positional(positional_options);
    po::store(parser.run(), vm);
    po::notify(vm);
    return true;
  });
  if (! r)
    return 1;

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Aeon '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  mlog_configure(mlog_get_default_log_path("aeon-blockchain-usage.log"), true);
  if (!command_line::is_arg_defaulted(vm, arg_log_level))
    mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
  else
    mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());

  LOG_PRINT_L0("Starting...");

  bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
  bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
  network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
  bool opt_rct_only = command_line::get_arg(vm, arg_rct_only);

  std::string db_type = command_line::get_arg(vm, arg_database);
  if (!cryptonote::blockchain_valid_db_type(db_type))
  {
    std::cerr << "Invalid database type: " << db_type << std::endl;
    return 1;
  }

  // If we wanted to use the memory pool, we would set up a fake_core.

  // Use Blockchain instead of lower-level BlockchainDB for two reasons:
  // 1. Blockchain has the init() method for easy setup
  // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
  //
  // cannot match blockchain_storage setup above with just one line,
  // e.g.
  //   Blockchain* core_storage = new Blockchain(NULL);
  // because unlike blockchain_storage constructor, which takes a pointer to
  // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
  const std::string input = command_line::get_arg(vm, arg_input);
  std::unique_ptr<Blockchain> core_storage;
  tx_memory_pool m_mempool(*core_storage);
  core_storage.reset(new Blockchain(m_mempool));
  BlockchainDB* db = new_db(db_type);
  if (db == NULL)
  {
    LOG_ERROR("Attempted to use non-existent database type: " << db_type);
    throw std::runtime_error("Attempting to use non-existent database type");
  }
  LOG_PRINT_L0("database: " << db_type);

  const std::string filename = input;
  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");

  try
  {
    db->open(filename, DBF_RDONLY);
  }
  catch (const std::exception& e)
  {
    LOG_PRINT_L0("Error opening database: " << e.what());
    return 1;
  }
  r = core_storage->init(db, net_type);

  CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
  LOG_PRINT_L0("Source blockchain storage initialized OK");

  LOG_PRINT_L0("Building usage patterns...");

  size_t done = 0;
  std::unordered_map<output_data, std::list<reference>> outputs;
  std::unordered_map<uint64_t,uint64_t> indices;

  LOG_PRINT_L0("Reading blockchain from " << input);
  core_storage->for_all_transactions([&](const crypto::hash &hash, const cryptonote::transaction &tx)->bool
  {
    const bool coinbase = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
    const uint64_t height = core_storage->get_db().get_tx_block_height(hash);

    // create new outputs
    for (const auto &out: tx.vout)
    {
      if (opt_rct_only && out.amount)
        continue;
      uint64_t index = indices[out.amount]++;
      output_data od(out.amount, indices[out.amount], coinbase, height);
      auto itb = outputs.emplace(od, std::list<reference>());
      itb.first->first.info(coinbase, height);
    }

    for (const auto &in: tx.vin)
    {
      if (in.type() != typeid(txin_to_key))
        continue;
      const auto &txin = boost::get<txin_to_key>(in);
      if (opt_rct_only && txin.amount != 0)
        continue;

      const std::vector<uint64_t> absolute = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets);
      for (size_t n = 0; n < txin.key_offsets.size(); ++n)
      {
        output_data od(txin.amount, absolute[n], coinbase, height);
        outputs[od].push_back(reference(height, txin.key_offsets.size(), n));
      }
    }
    return true;
  });

  std::unordered_map<uint64_t, uint64_t> counts;
  size_t total = 0;
  for (const auto &out: outputs)
  {
    counts[out.second.size()]++;
    total++;
  }
  for (const auto &c: counts)
  {
    float percent = 100.f * c.second / total;
    MINFO(std::to_string(c.second) << " outputs used " << c.first << " times (" << percent << "%)");
  }

  LOG_PRINT_L0("Blockchain usage exported OK");
  return 0;

  CATCH_ENTRY("Export error", 1);
}
예제 #3
0
int main(int argc, char* argv[])
{
  uint32_t log_level = 0;
  uint64_t block_stop = 0;

  tools::sanitize_locale();

  boost::filesystem::path default_data_path {tools::get_default_data_dir()};
  boost::filesystem::path default_testnet_data_path {default_data_path / "testnet"};
  boost::filesystem::path output_file_path;

  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<std::string> arg_output_file = {"output-file", "Specify output file", "", true};
  const command_line::arg_descriptor<uint32_t> arg_log_level  = {"log-level",  "", log_level};
  const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop};
#if SOURCE_DB != DB_MEMORY
  const command_line::arg_descriptor<std::string> arg_db_type = {
    "db-type"
  , "Specify database type"
  , DEFAULT_DB_TYPE
  };
  const command_line::arg_descriptor<bool>     arg_include_db_only_data = {
    "include-db-only-data"
      , "Include data that is only in a database version."
      , false
  };
#endif
  const command_line::arg_descriptor<bool>     arg_testnet_on = {
    "testnet"
      , "Run on testnet."
      , false
  };


  command_line::add_arg(desc_cmd_sett, command_line::arg_data_dir, default_data_path.string());
  command_line::add_arg(desc_cmd_sett, command_line::arg_testnet_data_dir, default_testnet_data_path.string());
  command_line::add_arg(desc_cmd_sett, arg_output_file);
#if SOURCE_DB != DB_MEMORY
  command_line::add_arg(desc_cmd_sett, arg_db_type);
  command_line::add_arg(desc_cmd_sett, arg_include_db_only_data);
#endif
  command_line::add_arg(desc_cmd_sett, arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_block_stop);

  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);

  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    po::store(po::parse_command_line(argc, argv, desc_options), vm);
    po::notify(vm);
    return true;
  });
  if (! r)
    return 1;

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  log_level    = command_line::get_arg(vm, arg_log_level);
  block_stop = command_line::get_arg(vm, arg_block_stop);

  log_space::get_set_log_detalisation_level(true, log_level);
  log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
  LOG_PRINT_L0("Starting...");
  LOG_PRINT_L0("Setting log level = " << log_level);

  bool opt_testnet = command_line::get_arg(vm, arg_testnet_on);
#if SOURCE_DB != DB_MEMORY
  bool opt_include_db_only_data = command_line::get_arg(vm, arg_include_db_only_data);
#endif

  std::string m_config_folder;

  auto data_dir_arg = opt_testnet ? command_line::arg_testnet_data_dir : command_line::arg_data_dir;
  m_config_folder = command_line::get_arg(vm, data_dir_arg);

  if (command_line::has_arg(vm, arg_output_file))
    output_file_path = boost::filesystem::path(command_line::get_arg(vm, arg_output_file));
  else
    output_file_path = boost::filesystem::path(m_config_folder) / "dump" / "blockchain.json";
  LOG_PRINT_L0("Export output file: " << output_file_path.string());

  const boost::filesystem::path dir_path = output_file_path.parent_path();
  if (!dir_path.empty())
  {
    if (boost::filesystem::exists(dir_path))
    {
      if (!boost::filesystem::is_directory(dir_path))
      {
        LOG_PRINT_RED_L0("dump directory path is a file: " << dir_path);
        return 1;
      }
    }
    else
    {
      if (!boost::filesystem::create_directory(dir_path))
      {
        LOG_PRINT_RED_L0("Failed to create directory " << dir_path);
        return 1;
      }
    }
  }

  std::ofstream raw_data_file;
  raw_data_file.open(output_file_path.string(), std::ios_base::out | std::ios::trunc);
  if (raw_data_file.fail())
    return 1;


  // If we wanted to use the memory pool, we would set up a fake_core.

#if SOURCE_DB == DB_MEMORY
  // blockchain_storage* core_storage = NULL;
  // tx_memory_pool m_mempool(*core_storage); // is this fake anyway? just passing in NULL! so m_mempool can't be used anyway, right?
  // core_storage = new blockchain_storage(&m_mempool);

  blockchain_storage* core_storage = new blockchain_storage(NULL);
  LOG_PRINT_L0("Initializing source blockchain (in-memory database)");
  r = core_storage->init(m_config_folder, opt_testnet);
#else
  // Use Blockchain instead of lower-level BlockchainDB for two reasons:
  // 1. Blockchain has the init() method for easy setup
  // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
  //
  // cannot match blockchain_storage setup above with just one line,
  // e.g.
  //   Blockchain* core_storage = new Blockchain(NULL);
  // because unlike blockchain_storage constructor, which takes a pointer to
  // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
  Blockchain *core_storage = NULL;
  tx_memory_pool m_mempool(*core_storage);
  core_storage = new Blockchain(m_mempool);

  BlockchainDB* db;
  int mdb_flags = 0;
  std::string db_type = command_line::get_arg(vm, arg_db_type);
  if (db_type.empty() || db_type == "lmdb")
  {
    db = new BlockchainLMDB();
    mdb_flags |= MDB_RDONLY;
  }
#ifdef BERKELEY_DB
  else if (db_type == "berkeley")
  {
    db = new BlockchainBDB();
    // can't open readonly due to the way flags are split in db_bdb.cpp
  }
#endif
  else
  {
    LOG_PRINT_L0("Invalid db type: " << db_type);
    return 1;
  }
  boost::filesystem::path folder(m_config_folder);
  folder /= db->get_db_name();
  const std::string filename = folder.string();
  uint64_t base_idx = db->get_indexing_base();

  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
  try
  {
    db->open(filename, mdb_flags);
  }
  catch (const std::exception& e)
  {
    LOG_PRINT_L0("Error opening database: " << e.what());
    return 1;
  }
  r = core_storage->init(db, opt_testnet);
#endif

  CHECK_AND_ASSERT_MES(r, false, "Failed to initialize source blockchain storage");
  LOG_PRINT_L0("Source blockchain storage initialized OK");
  LOG_PRINT_L0("Dumping blockchain...");

  DumpContext d(raw_data_file);

  start_struct(d,"blockchain");
    uint64_t height = core_storage->get_current_blockchain_height();
    write_pod(d, "height", height);
    start_array(d,"blockids", true);
      for (uint64_t h = 0; h < height; ++h)
        write_pod(d,core_storage->get_block_id_by_height(h));
    end_compound(d);
    start_array(d,"txids", true);
    {
      std::vector<crypto::hash> txids;
      core_storage->for_all_transactions([&txids](const crypto::hash &hash, const cryptonote::transaction &tx)->bool{txids.push_back(hash); return true;});
      std::sort(txids.begin(), txids.end(),
        [](const crypto::hash &txid0, const crypto::hash &txid1) {return memcmp(txid0.data, txid1.data, sizeof(crypto::hash::data)) < 0;});
      for (size_t n = 0; n < txids.size(); ++n)
        write_pod(d, txids[n]);
    }
    end_compound(d);
    start_struct(d,"transactions", true);
    {
      for (uint64_t h = 0; h < height; ++h)
      {
        start_array(d, boost::lexical_cast<std::string>(h));
          std::list<cryptonote::block> blocks;
          std::list<cryptonote::transaction> transactions, miner_tx;
          core_storage->get_blocks(h, 1, blocks, transactions);
          if (blocks.size() != 1)
            throw std::string("Expected 1 block at height ") + boost::lexical_cast<std::string>(h);
          crypto::hash txid = cryptonote::get_transaction_hash(blocks.front().miner_tx);
          write_pod(d, string_tools::pod_to_hex(txid).c_str(), obj_to_json_str(blocks.front().miner_tx));
          std::vector<std::pair<crypto::hash, cryptonote::transaction>> txes;
          for (std::list<cryptonote::transaction>::iterator i = transactions.begin(); i != transactions.end(); ++i)
            txes.push_back(std::make_pair(cryptonote::get_transaction_hash(*i), *i));
          std::sort(txes.begin(), txes.end(),
            [](const std::pair<crypto::hash, cryptonote::transaction> &tx0, const std::pair<crypto::hash, cryptonote::transaction> &tx1) {return memcmp(tx0.first.data, tx1.first.data, sizeof(crypto::key_image::data)) < 0;});
          for (std::vector<std::pair<crypto::hash, cryptonote::transaction>>::iterator i = txes.begin(); i != txes.end(); ++i)
          {
            write_pod(d, string_tools::pod_to_hex((*i).first).c_str(), obj_to_json_str((*i).second));
          }
        end_compound(d);
      }
    }
    end_compound(d);
    start_struct(d,"blocks", true);
    {
      std::vector<crypto::hash> blockids;
      core_storage->for_all_blocks([&](uint64_t height, const crypto::hash &hash, const cryptonote::block &b)->bool{
         start_struct(d, boost::lexical_cast<std::string>(height));
           write_pod(d, "hash", string_tools::pod_to_hex(hash));
           cryptonote::block block = b;
           write_pod(d, "block", obj_to_json_str(block));
         end_compound(d);
         return true;
      });
    }
    end_compound(d);
    start_array(d,"key_images", true);
    {
      std::vector<crypto::key_image> key_images;
      core_storage->for_all_key_images([&key_images](const crypto::key_image &k_image)->bool{key_images.push_back(k_image); return true;});
      std::sort(key_images.begin(), key_images.end(),
        [](const crypto::key_image &k0, const crypto::key_image &k1) {return memcmp(k0.data, k1.data, sizeof(crypto::key_image::data)) < 0;});
      for (size_t n = 0; n < key_images.size(); ++n)
        write_pod(d,key_images[n]);
    }
    end_compound(d);
#if SOURCE_DB != DB_MEMORY
    if (opt_include_db_only_data)
    {
      start_struct(d, "block_timestamps", true);
        for (uint64_t h = 0; h < height; ++h)
          write_pod(d,boost::lexical_cast<std::string>(h),db->get_block_timestamp(h));
      end_compound(d);
      start_struct(d, "block_difficulties", true);
        for (uint64_t h = 0; h < height; ++h)
          write_pod(d,boost::lexical_cast<std::string>(h),db->get_block_cumulative_difficulty(h));
      end_compound(d);
      start_struct(d, "block_sizes", true);
        for (uint64_t h = 0; h < height; ++h)
          write_pod(d,boost::lexical_cast<std::string>(h),db->get_block_size(h));
      end_compound(d);
      start_struct(d, "block_coins", true);
        for (uint64_t h = 0; h < height; ++h)
          write_pod(d,boost::lexical_cast<std::string>(h),db->get_block_already_generated_coins(h));
      end_compound(d);
      start_struct(d, "block_heights", true);
        for (uint64_t h = 0; h < height; ++h)
        {
          const crypto::hash hash = core_storage->get_block_id_by_height(h);
          write_pod(d,boost::lexical_cast<std::string>(h),db->get_block_height(hash));
        }
      end_compound(d);
      {
        std::vector<crypto::hash> txids;
        core_storage->for_all_transactions([&txids](const crypto::hash &hash, const cryptonote::transaction &tx)->bool{txids.push_back(hash); return true;});
        std::sort(txids.begin(), txids.end(),
          [](const crypto::hash &txid0, const crypto::hash &txid1) {return memcmp(txid0.data, txid1.data, sizeof(crypto::hash::data)) < 0;});
        start_struct(d, "transaction_unlock_times", true);
          for (size_t n = 0; n < txids.size(); ++n)
            write_pod(d,string_tools::pod_to_hex(txids[n]),db->get_tx_unlock_time(txids[n]));
        end_compound(d);
        start_struct(d, "transaction_block_heights", true);
          for (size_t n = 0; n < txids.size(); ++n)
            write_pod(d,string_tools::pod_to_hex(txids[n]),db->get_tx_block_height(txids[n]));
        end_compound(d);
      }
      start_array(d, "tx_and_index_from_global", true);
        for (uint64_t idx = 0; ; ++idx)
        {
          try
          {
            tx_out_index toi = db->get_output_tx_and_index_from_global(idx + base_idx);
            start_struct(d, boost::lexical_cast<std::string>(idx));
              write_pod(d, "tx_hash", string_tools::pod_to_hex(toi.first));
              write_pod(d, "tx_index", string_tools::pod_to_hex(toi.second));
            end_compound(d);
          }
          catch (const OUTPUT_DNE &) { break; }
        }
      end_compound(d);
      start_struct(d, "outputs_amounts", true);
        for (uint64_t base = 1; base <= (uint64_t)10000000000000000000ul; base *= 10) for (uint64_t digit = 1; digit <= 9; ++digit) {
          uint64_t amount = digit * base;
          write_pod(d, boost::lexical_cast<std::string>(amount), db->get_num_outputs(amount));
        }
      end_compound(d);
      start_array(d, "output_keys", true);
        for (uint64_t idx = 0; ; ++idx)
        {
          try
          {
            output_data_t od = db->get_output_key(idx + base_idx);
            start_struct(d, boost::lexical_cast<std::string>(idx));
              write_pod(d, "pubkey", string_tools::pod_to_hex(od.pubkey));
              write_pod(d, "unlock_time", od.unlock_time);
              write_pod(d, "height", od.height);
            end_compound(d);
          }
          catch (const OUTPUT_DNE &) { break; }
        }
      end_compound(d);
      start_struct(d, "hf_versions", true);
        for (uint64_t h = 0; h < height; ++h)
          write_pod(d, boost::lexical_cast<std::string>(h), (unsigned int)db->get_hard_fork_version(h));
      end_compound(d);
      start_struct(d, "hf_starting_heights", true);
        for (unsigned int v = 0; v <= 255; ++v)
          write_pod(d, boost::lexical_cast<std::string>(v), db->get_hard_fork_starting_height(v));
      end_compound(d);
    }
#endif
  end_compound(d);

  CHECK_AND_ASSERT_MES(r, false, "Failed to dump blockchain");

  if (raw_data_file.fail())
    return 1;
  raw_data_file.flush();

  LOG_PRINT_L0("Blockchain dump OK");

  return 0;
}
예제 #4
0
int main(int argc, char* argv[])
{
  uint32_t log_level = 0;
  uint64_t block_stop = 0;
  bool blocks_dat = false;

  tools::sanitize_locale();

  boost::filesystem::path default_data_path {tools::get_default_data_dir()};
  boost::filesystem::path default_testnet_data_path {default_data_path / "testnet"};
  boost::filesystem::path output_file_path;

  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<std::string> arg_output_file = {"output-file", "Specify output file", "", true};
  const command_line::arg_descriptor<uint32_t> arg_log_level  = {"log-level",  "", log_level};
  const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop};
  const command_line::arg_descriptor<bool>     arg_testnet_on = {
    "testnet"
      , "Run on testnet."
      , false
  };
  const command_line::arg_descriptor<bool> arg_blocks_dat = {"blocksdat", "Output in blocks.dat format", blocks_dat};


  command_line::add_arg(desc_cmd_sett, command_line::arg_data_dir, default_data_path.string());
  command_line::add_arg(desc_cmd_sett, command_line::arg_testnet_data_dir, default_testnet_data_path.string());
  command_line::add_arg(desc_cmd_sett, arg_output_file);
  command_line::add_arg(desc_cmd_sett, arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_block_stop);
  command_line::add_arg(desc_cmd_sett, arg_blocks_dat);

  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);

  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    po::store(po::parse_command_line(argc, argv, desc_options), vm);
    po::notify(vm);
    return true;
  });
  if (! r)
    return 1;

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << CRYPTONOTE_NAME << " v" << MONERO_VERSION_FULL << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  log_level    = command_line::get_arg(vm, arg_log_level);
  block_stop = command_line::get_arg(vm, arg_block_stop);

  log_space::get_set_log_detalisation_level(true, log_level);
  log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
  LOG_PRINT_L0("Starting...");
  LOG_PRINT_L0("Setting log level = " << log_level);

  bool opt_testnet = command_line::get_arg(vm, arg_testnet_on);
  bool opt_blocks_dat = command_line::get_arg(vm, arg_blocks_dat);

  std::string m_config_folder;

  auto data_dir_arg = opt_testnet ? command_line::arg_testnet_data_dir : command_line::arg_data_dir;
  m_config_folder = command_line::get_arg(vm, data_dir_arg);

  if (command_line::has_arg(vm, arg_output_file))
    output_file_path = boost::filesystem::path(command_line::get_arg(vm, arg_output_file));
  else
    output_file_path = boost::filesystem::path(m_config_folder) / "export" / BLOCKCHAIN_RAW;
  LOG_PRINT_L0("Export output file: " << output_file_path.string());

  // If we wanted to use the memory pool, we would set up a fake_core.

#if SOURCE_DB == DB_MEMORY
  // blockchain_storage* core_storage = NULL;
  // tx_memory_pool m_mempool(*core_storage); // is this fake anyway? just passing in NULL! so m_mempool can't be used anyway, right?
  // core_storage = new blockchain_storage(&m_mempool);

  blockchain_storage* core_storage = new blockchain_storage(NULL);
  LOG_PRINT_L0("Initializing source blockchain (in-memory database)");
  r = core_storage->init(m_config_folder, opt_testnet);
#else
  // Use Blockchain instead of lower-level BlockchainDB for two reasons:
  // 1. Blockchain has the init() method for easy setup
  // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
  //
  // cannot match blockchain_storage setup above with just one line,
  // e.g.
  //   Blockchain* core_storage = new Blockchain(NULL);
  // because unlike blockchain_storage constructor, which takes a pointer to
  // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
  Blockchain* core_storage = NULL;
  tx_memory_pool m_mempool(*core_storage);
  core_storage = new Blockchain(m_mempool);

  BlockchainDB* db = new BlockchainLMDB();
  boost::filesystem::path folder(m_config_folder);
  folder /= db->get_db_name();
  int lmdb_flags = 0;
  lmdb_flags |= MDB_RDONLY;
  const std::string filename = folder.string();

  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
  try
  {
    db->open(filename, lmdb_flags);
  }
  catch (const std::exception& e)
  {
    LOG_PRINT_L0("Error opening database: " << e.what());
    return 1;
  }
  r = core_storage->init(db, opt_testnet);
#endif

  CHECK_AND_ASSERT_MES(r, false, "Failed to initialize source blockchain storage");
  LOG_PRINT_L0("Source blockchain storage initialized OK");
  LOG_PRINT_L0("Exporting blockchain raw data...");

  if (opt_blocks_dat)
  {
    BlocksdatFile blocksdat;
    r = blocksdat.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop);
  }
  else
  {
    BootstrapFile bootstrap;
    r = bootstrap.store_blockchain_raw(core_storage, NULL, output_file_path, block_stop);
  }
  CHECK_AND_ASSERT_MES(r, false, "Failed to export blockchain raw data");
  LOG_PRINT_L0("Blockchain raw data exported OK");
}
예제 #5
0
int main(int argc, char* argv[])
{
  TRY_ENTRY();

  epee::string_tools::set_module_name_and_folder(argv[0]);

  std::string default_db_type = "lmdb";

  std::string available_dbs = cryptonote::blockchain_db_types(", ");
  available_dbs = "available: " + available_dbs;

  uint32_t log_level = 0;
  uint64_t block_start = 0;
  uint64_t block_stop = 0;

  tools::on_startup();

  boost::filesystem::path output_file_path;

  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<std::string> arg_log_level  = {"log-level",  "0-4 or categories", ""};
  const command_line::arg_descriptor<std::string> arg_database = {
    "database", available_dbs.c_str(), default_db_type
  };
  const command_line::arg_descriptor<uint64_t> arg_block_start  = {"block-start", "start at block number", block_start};
  const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop};
  const command_line::arg_descriptor<bool> arg_inputs  = {"with-inputs", "with input stats", false};
  const command_line::arg_descriptor<bool> arg_outputs  = {"with-outputs", "with output stats", false};
  const command_line::arg_descriptor<bool> arg_ringsize  = {"with-ringsize", "with ringsize stats", false};
  const command_line::arg_descriptor<bool> arg_hours  = {"with-hours", "with txns per hour", false};

  command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_database);
  command_line::add_arg(desc_cmd_sett, arg_block_start);
  command_line::add_arg(desc_cmd_sett, arg_block_stop);
  command_line::add_arg(desc_cmd_sett, arg_inputs);
  command_line::add_arg(desc_cmd_sett, arg_outputs);
  command_line::add_arg(desc_cmd_sett, arg_ringsize);
  command_line::add_arg(desc_cmd_sett, arg_hours);
  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);

  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    auto parser = po::command_line_parser(argc, argv).options(desc_options);
    po::store(parser.run(), vm);
    po::notify(vm);
    return true;
  });
  if (! r)
    return 1;

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  mlog_configure(mlog_get_default_log_path("monero-blockchain-stats.log"), true);
  if (!command_line::is_arg_defaulted(vm, arg_log_level))
    mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
  else
    mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());

  LOG_PRINT_L0("Starting...");

  std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
  bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
  bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
  network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
  block_start = command_line::get_arg(vm, arg_block_start);
  block_stop = command_line::get_arg(vm, arg_block_stop);
  bool do_inputs = command_line::get_arg(vm, arg_inputs);
  bool do_outputs = command_line::get_arg(vm, arg_outputs);
  bool do_ringsize = command_line::get_arg(vm, arg_ringsize);
  bool do_hours = command_line::get_arg(vm, arg_hours);

  std::string db_type = command_line::get_arg(vm, arg_database);
  if (!cryptonote::blockchain_valid_db_type(db_type))
  {
    std::cerr << "Invalid database type: " << db_type << std::endl;
    return 1;
  }

  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
  std::unique_ptr<Blockchain> core_storage;
  tx_memory_pool m_mempool(*core_storage);
  core_storage.reset(new Blockchain(m_mempool));
  BlockchainDB *db = new_db(db_type);
  if (db == NULL)
  {
    LOG_ERROR("Attempted to use non-existent database type: " << db_type);
    throw std::runtime_error("Attempting to use non-existent database type");
  }
  LOG_PRINT_L0("database: " << db_type);

  const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");

  try
  {
    db->open(filename, DBF_RDONLY);
  }
  catch (const std::exception& e)
  {
    LOG_PRINT_L0("Error opening database: " << e.what());
    return 1;
  }
  r = core_storage->init(db, net_type);

  CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
  LOG_PRINT_L0("Source blockchain storage initialized OK");

  tools::signal_handler::install([](int type) {
    stop_requested = true;
  });

  const uint64_t db_height = db->height();
  if (!block_stop)
      block_stop = db_height;
  MINFO("Starting from height " << block_start << ", stopping at height " << block_stop);

/*
 * The default output can be plotted with GnuPlot using these commands:
set key autotitle columnhead
set title "Monero Blockchain Growth"
set timefmt "%Y-%m-%d"
set xdata time
set xrange ["2014-04-17":*]
set format x "%Y-%m-%d"
set yrange [0:*]
set y2range [0:*]
set ylabel "Txs/Day"
set y2label "Bytes"
set y2tics nomirror
plot 'stats.csv' index "DATA" using (timecolumn(1,"%Y-%m-%d")):4 with lines, '' using (timecolumn(1,"%Y-%m-%d")):7 axes x1y2 with lines
 */

  // spit out a comment that GnuPlot can use as an index
  std::cout << ENDL << "# DATA" << ENDL;
  std::cout << "Date\tBlocks/day\tBlocks\tTxs/Day\tTxs\tBytes/Day\tBytes";
  if (do_inputs)
    std::cout << "\tInMin\tInMax\tInAvg";
  if (do_outputs)
    std::cout << "\tOutMin\tOutMax\tOutAvg";
  if (do_ringsize)
    std::cout << "\tRingMin\tRingMax\tRingAvg";
  if (do_hours) {
    char buf[8];
    unsigned int i;
    for (i=0; i<24; i++) {
      sprintf(buf, "\t%02u:00", i);
      std::cout << buf;
    }
  }
  std::cout << ENDL;

  struct tm prevtm = {0}, currtm;
  uint64_t prevsz = 0, currsz = 0;
  uint64_t prevtxs = 0, currtxs = 0;
  uint64_t currblks = 0;
  uint64_t totins = 0, totouts = 0, totrings = 0;
  uint32_t minins = 10, maxins = 0;
  uint32_t minouts = 10, maxouts = 0;
  uint32_t minrings = 50, maxrings = 0;
  uint32_t io, tottxs = 0;
  uint32_t txhr[24] = {0};
  unsigned int i;

  for (uint64_t h = block_start; h < block_stop; ++h)
  {
    cryptonote::blobdata bd = db->get_block_blob_from_height(h);
    cryptonote::block blk;
    if (!cryptonote::parse_and_validate_block_from_blob(bd, blk))
    {
      LOG_PRINT_L0("Bad block from db");
      return 1;
    }
    time_t tt = blk.timestamp;
    char timebuf[64];
    epee::misc_utils::get_gmt_time(tt, currtm);
    if (!prevtm.tm_year)
      prevtm = currtm;
    // catch change of day
    if (currtm.tm_mday > prevtm.tm_mday || (currtm.tm_mday == 1 && prevtm.tm_mday > 27))
    {
      // check for timestamp fudging around month ends
      if (prevtm.tm_mday == 1 && currtm.tm_mday > 27)
        goto skip;
      strftime(timebuf, sizeof(timebuf), "%Y-%m-%d", &prevtm);
      prevtm = currtm;
      std::cout << timebuf << "\t" << currblks << "\t" << h << "\t" << currtxs << "\t" << prevtxs + currtxs << "\t" << currsz << "\t" << prevsz + currsz;
      prevsz += currsz;
      currsz = 0;
      currblks = 0;
      prevtxs += currtxs;
      currtxs = 0;
      if (!tottxs)
        tottxs = 1;
      if (do_inputs) {
        std::cout << "\t" << (maxins ? minins : 0) << "\t" << maxins << "\t" << totins / tottxs;
        minins = 10; maxins = 0; totins = 0;
      }
      if (do_outputs) {
        std::cout << "\t" << (maxouts ? minouts : 0) << "\t" << maxouts << "\t" << totouts / tottxs;
        minouts = 10; maxouts = 0; totouts = 0;
      }
      if (do_ringsize) {
        std::cout << "\t" << (maxrings ? minrings : 0) << "\t" << maxrings << "\t" << totrings / tottxs;
        minrings = 50; maxrings = 0; totrings = 0;
      }
      tottxs = 0;
      if (do_hours) {
        for (i=0; i<24; i++) {
          std::cout << "\t" << txhr[i];
          txhr[i] = 0;
        }
      }
      std::cout << ENDL;
    }
skip:
    currsz += bd.size();
    for (const auto& tx_id : blk.tx_hashes)
    {
      if (tx_id == crypto::null_hash)
      {
        throw std::runtime_error("Aborting: tx == null_hash");
      }
      if (!db->get_tx_blob(tx_id, bd))
      {
        throw std::runtime_error("Aborting: tx not found");
      }
      transaction tx;
      if (!parse_and_validate_tx_from_blob(bd, tx))
      {
        LOG_PRINT_L0("Bad txn from db");
        return 1;
      }
      currsz += bd.size();
      currtxs++;
      if (do_hours)
        txhr[currtm.tm_hour]++;
      if (do_inputs) {
        io = tx.vin.size();
        if (io < minins)
          minins = io;
        else if (io > maxins)
          maxins = io;
        totins += io;
      }
      if (do_ringsize) {
        const cryptonote::txin_to_key& tx_in_to_key
                       = boost::get<cryptonote::txin_to_key>(tx.vin[0]);
        io = tx_in_to_key.key_offsets.size();
        if (io < minrings)
          minrings = io;
        else if (io > maxrings)
          maxrings = io;
        totrings += io;
      }
      if (do_outputs) {
        io = tx.vout.size();
        if (io < minouts)
          minouts = io;
        else if (io > maxouts)
          maxouts = io;
        totouts += io;
      }
      tottxs++;
    }
    currblks++;

    if (stop_requested)
      break;
  }

  core_storage->deinit();
  return 0;

  CATCH_ENTRY("Stats reporting error", 1);
}
예제 #6
0
  //-----------------------------------------------------------------------------------------------
  bool core::init(const boost::program_options::variables_map& vm)
  {
    bool r = handle_command_line(vm);

    r = m_mempool.init(m_fakechain ? std::string() : m_config_folder);
    CHECK_AND_ASSERT_MES(r, false, "Failed to initialize memory pool");

#if BLOCKCHAIN_DB == DB_LMDB
    std::string db_type = command_line::get_arg(vm, command_line::arg_db_type);
    std::string db_sync_mode = command_line::get_arg(vm, command_line::arg_db_sync_mode);
    bool fast_sync = command_line::get_arg(vm, command_line::arg_fast_block_sync) != 0;
    uint64_t blocks_threads = command_line::get_arg(vm, command_line::arg_prep_blocks_threads);

    boost::filesystem::path folder(m_config_folder);
    if (m_fakechain)
      folder /= "fake";
    //
    // check for blockchain.bin
    try
    {
      const boost::filesystem::path old_files = folder;
      if (boost::filesystem::exists(old_files / "blockchain.bin"))
      {
        LOG_PRINT_RED_L0("Found old-style blockchain.bin in " << old_files.string());
        LOG_PRINT_RED_L0("Monero now uses a new format. You can either remove blockchain.bin to start syncing");
        LOG_PRINT_RED_L0("the blockchain anew, or use blockchain_export and blockchain_import to convert your");
        LOG_PRINT_RED_L0("existing blockchain.bin to the new format. See README.md for instructions.");
        return false;
      }
    }
    // folder might not be a directory, etc, etc
    catch (...) { }

    BlockchainDB* db = nullptr;
    uint64_t BDB_FAST_MODE = 0;
    uint64_t BDB_FASTEST_MODE = 0;
    uint64_t BDB_SAFE_MODE = 0;
    if (db_type == "lmdb")
    {
      db = new BlockchainLMDB();
    }
    else if (db_type == "berkeley")
    {
#if defined(BERKELEY_DB)
      db = new BlockchainBDB();
      BDB_FAST_MODE = DB_TXN_WRITE_NOSYNC;
      BDB_FASTEST_MODE = DB_TXN_NOSYNC;
      BDB_SAFE_MODE = DB_TXN_SYNC;
#else
      LOG_ERROR("BerkeleyDB support disabled.");
      return false;
#endif
    }
    else
    {
      LOG_ERROR("Attempted to use non-existant database type");
      return false;
    }

    folder /= db->get_db_name();
    LOG_PRINT_L0("Loading blockchain from folder " << folder.string() << " ...");

    const std::string filename = folder.string();
    // temporarily default to fastest:async:1000
    blockchain_db_sync_mode sync_mode = db_async;
    uint64_t blocks_per_sync = 1000;

    try
    {
      uint64_t db_flags = 0;
      bool islmdb = db_type == "lmdb";

      std::vector<std::string> options;
      boost::trim(db_sync_mode);
      boost::split(options, db_sync_mode, boost::is_any_of(" :"));

      for(const auto &option : options)
        LOG_PRINT_L0("option: " << option);

      // temporarily default to fastest:async:1000
      uint64_t DEFAULT_FLAGS = islmdb ? MDB_WRITEMAP | MDB_MAPASYNC | MDB_NORDAHEAD | MDB_NOMETASYNC | MDB_NOSYNC :
          BDB_FASTEST_MODE;

      if(options.size() == 0)
      {
        // temporarily default to fastest:async:1000
        db_flags = DEFAULT_FLAGS;
      }

      bool safemode = false;
      if(options.size() >= 1)
      {
        if(options[0] == "safe")
        {
          safemode = true;
          db_flags = islmdb ? MDB_NORDAHEAD : BDB_SAFE_MODE;
          sync_mode = db_nosync;
        }
        else if(options[0] == "fast")
          db_flags = islmdb ? MDB_NOMETASYNC | MDB_NOSYNC | MDB_NORDAHEAD : BDB_FAST_MODE;
        else if(options[0] == "fastest")
          db_flags = islmdb ? MDB_WRITEMAP | MDB_MAPASYNC | MDB_NORDAHEAD | MDB_NOMETASYNC | MDB_NOSYNC : BDB_FASTEST_MODE;
        else
          db_flags = DEFAULT_FLAGS;
      }

      if(options.size() >= 2 && !safemode)
      {
        if(options[1] == "sync")
          sync_mode = db_sync;
        else if(options[1] == "async")
          sync_mode = db_async;
      }

      if(options.size() >= 3 && !safemode)
      {
        blocks_per_sync = atoll(options[2].c_str());
        if(blocks_per_sync > 5000)
          blocks_per_sync = 5000;
        if(blocks_per_sync == 0)
          blocks_per_sync = 1;
      }

      bool auto_remove_logs = command_line::get_arg(vm, command_line::arg_db_auto_remove_logs) != 0;
      db->set_auto_remove_logs(auto_remove_logs);
      db->open(filename, db_flags);
      if(!db->m_open)
        return false;
    }
    catch (const DB_ERROR& e)
    {
      LOG_PRINT_L0("Error opening database: " << e.what());
      return false;
    }

    m_blockchain_storage.set_user_options(blocks_threads,
        blocks_per_sync, sync_mode, fast_sync);

    r = m_blockchain_storage.init(db, m_testnet, m_fakechain);

    bool show_time_stats = command_line::get_arg(vm, command_line::arg_show_time_stats) != 0;
    m_blockchain_storage.set_show_time_stats(show_time_stats);
#else
    r = m_blockchain_storage.init(m_config_folder, m_testnet);
#endif
    CHECK_AND_ASSERT_MES(r, false, "Failed to initialize blockchain storage");

    // load json & DNS checkpoints, and verify them
    // with respect to what blocks we already have
    CHECK_AND_ASSERT_MES(update_checkpoints(), false, "One or more checkpoints loaded from json or dns conflicted with existing checkpoints.");

    r = m_miner.init(vm, m_testnet);
    CHECK_AND_ASSERT_MES(r, false, "Failed to initialize blockchain storage");

    return load_state_data();
  }
예제 #7
0
int main(int argc, char* argv[])
{
  uint64_t height = 0;
  uint64_t start_block = 0;
  uint64_t end_block = 0;
  uint64_t num_blocks = 0;

  boost::filesystem::path default_data_path {tools::get_default_data_dir()};
  boost::filesystem::path default_testnet_data_path {default_data_path / "testnet"};


  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<uint32_t> arg_log_level   =  {"log-level", "", LOG_LEVEL_0};
  const command_line::arg_descriptor<uint64_t> arg_batch_size  =  {"batch-size", "", db_batch_size};
  const command_line::arg_descriptor<bool>     arg_testnet_on  = {
    "testnet"
      , "Run on testnet."
      , opt_testnet
  };
  const command_line::arg_descriptor<uint64_t> arg_block_number =
  {"block-number", "Number of blocks (default: use entire source blockchain)",
    0};

  command_line::add_arg(desc_cmd_sett, command_line::arg_data_dir, default_data_path.string());
  command_line::add_arg(desc_cmd_sett, command_line::arg_testnet_data_dir, default_testnet_data_path.string());
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_batch_size);
  command_line::add_arg(desc_cmd_sett, arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, arg_block_number);

  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  const command_line::arg_descriptor<bool> arg_batch  =  {"batch",
    "Batch transactions for faster import", true};
  const command_line::arg_descriptor<bool> arg_resume =  {"resume",
        "Resume from current height if output database already exists", true};

  // call add_options() directly for these arguments since command_line helpers
  // support only boolean switch, not boolean argument
  desc_cmd_sett.add_options()
    (arg_batch.name,  make_semantic(arg_batch),  arg_batch.description)
    (arg_resume.name, make_semantic(arg_resume), arg_resume.description)
    ;

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);


  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    po::store(po::parse_command_line(argc, argv, desc_options), vm);
    po::notify(vm);

    return true;
  });
  if (!r)
    return 1;

  int log_level = command_line::get_arg(vm, arg_log_level);
  opt_batch     = command_line::get_arg(vm, arg_batch);
  opt_resume    = command_line::get_arg(vm, arg_resume);
  db_batch_size = command_line::get_arg(vm, arg_batch_size);

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  if (! opt_batch && ! vm["batch-size"].defaulted())
  {
    std::cerr << "Error: batch-size set, but batch option not enabled" << ENDL;
    return 1;
  }
  if (! db_batch_size)
  {
    std::cerr << "Error: batch-size must be > 0" << ENDL;
    return 1;
  }

  log_space::get_set_log_detalisation_level(true, log_level);
  log_space::log_singletone::add_logger(LOGGER_CONSOLE, NULL, NULL);
  LOG_PRINT_L0("Starting...");

  std::string src_folder;
  opt_testnet = command_line::get_arg(vm, arg_testnet_on);
  auto data_dir_arg = opt_testnet ? command_line::arg_testnet_data_dir : command_line::arg_data_dir;
  src_folder = command_line::get_arg(vm, data_dir_arg);
  boost::filesystem::path dest_folder(src_folder);

  num_blocks = command_line::get_arg(vm, arg_block_number);

  if (opt_batch)
  {
    LOG_PRINT_L0("batch:   " << std::boolalpha << opt_batch << std::noboolalpha
        << "  batch size: " << db_batch_size);
  }
  else
  {
    LOG_PRINT_L0("batch:   " << std::boolalpha << opt_batch << std::noboolalpha);
  }
  LOG_PRINT_L0("resume:  " << std::boolalpha << opt_resume  << std::noboolalpha);
  LOG_PRINT_L0("testnet: " << std::boolalpha << opt_testnet << std::noboolalpha);

  fake_core c(src_folder, opt_testnet);

  height = c.m_storage.get_current_blockchain_height();

  BlockchainDB *blockchain;
  blockchain = new BlockchainLMDB(opt_batch);
  dest_folder /= blockchain->get_db_name();
  LOG_PRINT_L0("Source blockchain: " << src_folder);
  LOG_PRINT_L0("Dest blockchain:   " << dest_folder.string());
  LOG_PRINT_L0("Opening dest blockchain (BlockchainDB " << blockchain->get_db_name() << ")");
  blockchain->open(dest_folder.string());
  LOG_PRINT_L0("Source blockchain height: " << height);
  LOG_PRINT_L0("Dest blockchain height:   " << blockchain->height());

  if (opt_resume)
    // next block number to add is same as current height
    start_block = blockchain->height();

  if (! num_blocks || (start_block + num_blocks > height))
    end_block = height - 1;
  else
    end_block = start_block + num_blocks - 1;

  LOG_PRINT_L0("start height: " << start_block+1 << "  stop height: " <<
            end_block+1);

  if (start_block > end_block)
  {
    LOG_PRINT_L0("Finished: no blocks to add");
    delete blockchain;
    return 0;
  }

  if (opt_batch)
    blockchain->batch_start(db_batch_size);
  uint64_t i = 0;
  for (i = start_block; i < end_block + 1; ++i)
  {
    // block: i  height: i+1  end height: end_block + 1
    if ((i+1) % 10 == 0)
    {
      std::cout << "\r                   \r" << "height " << i+1 << "/" <<
        end_block+1 << " (" << (i+1)*100/(end_block+1)<< "%)" << std::flush;
    }
    // for debugging:
    // std::cout << "height " << i+1 << "/" << end_block+1
    //   << " ((" << i+1 << ")*100/(end_block+1))" << "%)" << ENDL;

    block b = c.m_storage.get_block(i);
    size_t bsize = c.m_storage.get_block_size(i);
    difficulty_type bdiff = c.m_storage.get_block_cumulative_difficulty(i);
    uint64_t bcoins = c.m_storage.get_block_coins_generated(i);
    std::vector<transaction> txs;
    std::vector<crypto::hash> missed;

    c.m_storage.get_transactions(b.tx_hashes, txs, missed);
    if (missed.size())
    {
      std::cout << ENDL;
      std::cerr << "Missed transaction(s) for block at height " << i + 1 << ", exiting" << ENDL;
      delete blockchain;
      return 1;
    }

    try
    {
      blockchain->add_block(b, bsize, bdiff, bcoins, txs);

      if (opt_batch)
      {
        if ((i < end_block) && ((i + 1) % db_batch_size == 0))
        {
          std::cout << "\r                   \r";
          std::cout << "[- batch commit at height " << i + 1 << " -]" << ENDL;
          blockchain->batch_stop();
          blockchain->batch_start(db_batch_size);
          std::cout << ENDL;
          blockchain->show_stats();
        }
      }
    }
    catch (const std::exception& e)
    {
      std::cout << ENDL;
      std::cerr << "Error adding block " << i << " to new blockchain: " << e.what() << ENDL;
      delete blockchain;
      return 2;
    }
  }
  if (opt_batch)
  {
    std::cout << "\r                   \r" << "height " << i << "/" <<
      end_block+1 << " (" << (i)*100/(end_block+1)<< "%)" << std::flush;
    std::cout << ENDL;
    std::cout << "[- batch commit at height " << i << " -]" << ENDL;
    blockchain->batch_stop();
  }
  std::cout << ENDL;
  blockchain->show_stats();
  std::cout << "Finished at height: " << i << "  block: " << i-1 << ENDL;

  delete blockchain;
  return 0;
}