Electroneum
blockchain_ancestry.cpp File Reference
#include <unordered_map>
#include <unordered_set>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/archive/portable_binary_iarchive.hpp>
#include <boost/archive/portable_binary_oarchive.hpp>
#include "common/unordered_containers_boost_serialization.h"
#include "common/command_line.h"
#include "common/varint.h"
#include "cryptonote_basic/cryptonote_boost_serialization.h"
#include "cryptonote_core/tx_pool.h"
#include "cryptonote_core/cryptonote_core.h"
#include "cryptonote_core/blockchain.h"
#include "blockchain_db/blockchain_db.h"
#include "blockchain_db/db_types.h"
#include "version.h"
Include dependency graph for blockchain_ancestry.cpp:

Go to the source code of this file.

Classes

struct  ancestor
 
struct  std::hash< ancestor >
 
struct  tx_data_t
 
struct  ancestry_state_t
 

Macros

#define ELECTRONEUM_DEFAULT_LOG_CATEGORY   "bcutil"
 

Functions

int main (int argc, char *argv[])
 

Macro Definition Documentation

◆ ELECTRONEUM_DEFAULT_LOG_CATEGORY

#define ELECTRONEUM_DEFAULT_LOG_CATEGORY   "bcutil"

Definition at line 47 of file blockchain_ancestry.cpp.

Function Documentation

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 333 of file blockchain_ancestry.cpp.

334 {
335  TRY_ENTRY();
336 
338 
339  std::string default_db_type = "lmdb";
340 
341  std::string available_dbs = cryptonote::blockchain_db_types(", ");
342  available_dbs = "available: " + available_dbs;
343 
344  uint32_t log_level = 0;
345 
347 
348  boost::filesystem::path output_file_path;
349 
350  po::options_description desc_cmd_only("Command line options");
351  po::options_description desc_cmd_sett("Command line options and settings options");
352  const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
353  const command_line::arg_descriptor<std::string> arg_database = {
354  "database", available_dbs.c_str(), default_db_type
355  };
356  const command_line::arg_descriptor<std::string> arg_txid = {"txid", "Get ancestry for this txid", ""};
357  const command_line::arg_descriptor<std::string> arg_output = {"output", "Get ancestry for this output (amount/offset format)", ""};
358  const command_line::arg_descriptor<uint64_t> arg_height = {"height", "Get ancestry for all txes at this height", 0};
359  const command_line::arg_descriptor<bool> arg_refresh = {"refresh", "Refresh the whole chain first", false};
360  const command_line::arg_descriptor<bool> arg_cache_outputs = {"cache-outputs", "Cache outputs (memory hungry)", false};
361  const command_line::arg_descriptor<bool> arg_cache_txes = {"cache-txes", "Cache txes (memory hungry)", false};
362  const command_line::arg_descriptor<bool> arg_cache_blocks = {"cache-blocks", "Cache blocks (memory hungry)", false};
363  const command_line::arg_descriptor<bool> arg_include_coinbase = {"include-coinbase", "Including coinbase tx in per height average", false};
364  const command_line::arg_descriptor<bool> arg_show_cache_stats = {"show-cache-stats", "Show cache statistics", false};
365 
369  command_line::add_arg(desc_cmd_sett, arg_log_level);
370  command_line::add_arg(desc_cmd_sett, arg_database);
371  command_line::add_arg(desc_cmd_sett, arg_txid);
372  command_line::add_arg(desc_cmd_sett, arg_output);
373  command_line::add_arg(desc_cmd_sett, arg_height);
374  command_line::add_arg(desc_cmd_sett, arg_refresh);
375  command_line::add_arg(desc_cmd_sett, arg_cache_outputs);
376  command_line::add_arg(desc_cmd_sett, arg_cache_txes);
377  command_line::add_arg(desc_cmd_sett, arg_cache_blocks);
378  command_line::add_arg(desc_cmd_sett, arg_include_coinbase);
379  command_line::add_arg(desc_cmd_sett, arg_show_cache_stats);
381 
382  po::options_description desc_options("Allowed options");
383  desc_options.add(desc_cmd_only).add(desc_cmd_sett);
384 
385  po::variables_map vm;
386  bool r = command_line::handle_error_helper(desc_options, [&]()
387  {
388  auto parser = po::command_line_parser(argc, argv).options(desc_options);
389  po::store(parser.run(), vm);
390  po::notify(vm);
391  return true;
392  });
393  if (! r)
394  return 1;
395 
397  {
398  std::cout << "Electroneum '" << ELECTRONEUM_RELEASE_NAME << "' (v" << ELECTRONEUM_VERSION_FULL << ")" << ENDL << ENDL;
399  std::cout << desc_options << std::endl;
400  return 1;
401  }
402 
403  mlog_configure(mlog_get_default_log_path("electroneum-blockchain-ancestry.log"), true);
406  else
407  mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
408 
409  LOG_PRINT_L0("Starting...");
410 
412  bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
413  bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
414  network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
415  std::string opt_txid_string = command_line::get_arg(vm, arg_txid);
416  std::string opt_output_string = command_line::get_arg(vm, arg_output);
417  uint64_t opt_height = command_line::get_arg(vm, arg_height);
418  bool opt_refresh = command_line::get_arg(vm, arg_refresh);
419  opt_cache_outputs = command_line::get_arg(vm, arg_cache_outputs);
420  opt_cache_txes = command_line::get_arg(vm, arg_cache_txes);
421  opt_cache_blocks = command_line::get_arg(vm, arg_cache_blocks);
422  bool opt_include_coinbase = command_line::get_arg(vm, arg_include_coinbase);
423  bool opt_show_cache_stats = command_line::get_arg(vm, arg_show_cache_stats);
424 
425  if ((!opt_txid_string.empty()) + !!opt_height + !opt_output_string.empty() > 1)
426  {
427  std::cerr << "Only one of --txid, --height, --output can be given" << std::endl;
428  return 1;
429  }
430  crypto::hash opt_txid = crypto::null_hash;
431  uint64_t output_amount = 0, output_offset = 0;
432  if (!opt_txid_string.empty())
433  {
434  if (!epee::string_tools::hex_to_pod(opt_txid_string, opt_txid))
435  {
436  std::cerr << "Invalid txid" << std::endl;
437  return 1;
438  }
439  }
440  else if (!opt_output_string.empty())
441  {
442  if (sscanf(opt_output_string.c_str(), "%" SCNu64 "/%" SCNu64, &output_amount, &output_offset) != 2)
443  {
444  std::cerr << "Invalid output" << std::endl;
445  return 1;
446  }
447  }
448 
449  std::string db_type = command_line::get_arg(vm, arg_database);
451  {
452  std::cerr << "Invalid database type: " << db_type << std::endl;
453  return 1;
454  }
455 
456  // If we wanted to use the memory pool, we would set up a fake_core.
457 
458  // Use Blockchain instead of lower-level BlockchainDB for two reasons:
459  // 1. Blockchain has the init() method for easy setup
460  // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
461  //
462  // cannot match blockchain_storage setup above with just one line,
463  // e.g.
464  // Blockchain* core_storage = new Blockchain(NULL);
465  // because unlike blockchain_storage constructor, which takes a pointer to
466  // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
467  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
468  std::unique_ptr<Blockchain> core_storage;
469  tx_memory_pool m_mempool(*core_storage);
470  core_storage.reset(new Blockchain(m_mempool));
471  BlockchainDB *db = new_db(db_type);
472  if (db == NULL)
473  {
474  LOG_ERROR("Attempted to use non-existent database type: " << db_type);
475  throw std::runtime_error("Attempting to use non-existent database type");
476  }
477  LOG_PRINT_L0("database: " << db_type);
478 
479  const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
480  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
481 
482  try
483  {
484  db->open(filename, DBF_RDONLY);
485  }
486  catch (const std::exception& e)
487  {
488  LOG_PRINT_L0("Error opening database: " << e.what());
489  return 1;
490  }
491  r = core_storage->init(db, net_type);
492 
493  CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
494  LOG_PRINT_L0("Source blockchain storage initialized OK");
495 
496  std::vector<crypto::hash> start_txids;
497 
499 
500  const std::string state_file_path = (boost::filesystem::path(opt_data_dir) / "ancestry-state.bin").string();
501  LOG_PRINT_L0("Loading state data from " << state_file_path);
502  std::ifstream state_data_in;
503  state_data_in.open(state_file_path, std::ios_base::binary | std::ios_base::in);
504  if (!state_data_in.fail())
505  {
506  try
507  {
509  a >> state;
510  }
511  catch (const std::exception &e)
512  {
513  MERROR("Failed to load state data from " << state_file_path << ", restarting from scratch");
515  }
516  state_data_in.close();
517  }
518 
519  tools::signal_handler::install([](int type) {
520  stop_requested = true;
521  });
522 
523  // forward method
524  const uint64_t db_height = db->height();
525  if (opt_refresh)
526  {
527  MINFO("Starting from height " << state.height);
528  state.block_cache.reserve(db_height);
529  for (uint64_t h = state.height; h < db_height; ++h)
530  {
531  size_t block_ancestry_size = 0;
533  ++total_blocks;
536  {
537  LOG_PRINT_L0("Bad block from db");
538  return 1;
539  }
540  if (opt_cache_blocks)
541  {
542  state.block_cache.resize(h + 1);
543  state.block_cache[h] = b;
544  }
545  std::vector<crypto::hash> txids;
546  txids.reserve(1 + b.tx_hashes.size());
547  if (opt_include_coinbase)
548  txids.push_back(cryptonote::get_transaction_hash(b.miner_tx));
549  for (const auto &h: b.tx_hashes)
550  txids.push_back(h);
551  for (const crypto::hash &txid: txids)
552  {
553  printf("%lu/%lu \r", (unsigned long)h, (unsigned long)db_height);
554  fflush(stdout);
555  ::tx_data_t tx_data;
556  std::unordered_map<crypto::hash, ::tx_data_t>::const_iterator i = state.tx_cache.find(txid);
557  ++total_txes;
558  if (i != state.tx_cache.end())
559  {
560  ++cached_txes;
561  tx_data = i->second;
562  }
563  else
564  {
566  if (!db->get_pruned_tx_blob(txid, bd))
567  {
568  LOG_PRINT_L0("Failed to get txid " << txid << " from db");
569  return 1;
570  }
573  {
574  LOG_PRINT_L0("Bad tx: " << txid);
575  return 1;
576  }
577  tx_data = ::tx_data_t(tx);
578  if (opt_cache_txes)
579  state.tx_cache.insert(std::make_pair(txid, tx_data));
580  }
581  if (tx_data.coinbase)
582  {
583  add_ancestry(state.ancestry, txid, std::unordered_set<ancestor>());
584  }
585  else
586  {
587  for (size_t ring = 0; ring < tx_data.vin.size(); ++ring)
588  {
589  const uint64_t amount = tx_data.vin[ring].first;
590  const std::vector<uint64_t> &absolute_offsets = tx_data.vin[ring].second;
591  for (uint64_t offset: absolute_offsets)
592  {
593  add_ancestry(state.ancestry, txid, ancestor{amount, offset});
594  // find the tx which created this output
595  bool found = false;
596  crypto::hash output_txid;
597  if (!get_output_txid(state, db, amount, offset, output_txid))
598  {
599  LOG_PRINT_L0("Output originating transaction not found");
600  return 1;
601  }
602  add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid));
603  }
604  }
605  }
606  const size_t ancestry_size = get_ancestry(state.ancestry, txid).size();
607  block_ancestry_size += ancestry_size;
608  MINFO(txid << ": " << ancestry_size);
609  }
610  if (!txids.empty())
611  {
612  std::string stats_msg;
613  MINFO("Height " << h << ": " << (block_ancestry_size / txids.size()) << " average over " << txids.size() << stats_msg);
614  }
615  state.height = h;
616  if (stop_requested)
617  break;
618  }
619 
620  LOG_PRINT_L0("Saving state data to " << state_file_path);
621  std::ofstream state_data_out;
622  state_data_out.open(state_file_path, std::ios_base::binary | std::ios_base::out | std::ios::trunc);
623  if (!state_data_out.fail())
624  {
625  try
626  {
628  a << state;
629  }
630  catch (const std::exception &e)
631  {
632  MERROR("Failed to save state data to " << state_file_path);
633  }
634  state_data_out.close();
635  }
636  }
637  else
638  {
639  if (state.height < db_height)
640  {
641  MWARNING("The state file is only built up to height " << state.height << ", but the blockchain reached height " << db_height);
642  MWARNING("You may want to run with --refresh if you want to get ancestry for newer data");
643  }
644  }
645 
646  if (!opt_txid_string.empty())
647  {
648  start_txids.push_back(opt_txid);
649  }
650  else if (!opt_output_string.empty())
651  {
652  crypto::hash txid;
653  if (!get_output_txid(state, db, output_amount, output_offset, txid))
654  {
655  LOG_PRINT_L0("Output not found in db");
656  return 1;
657  }
658  start_txids.push_back(txid);
659  }
660  else
661  {
662  const cryptonote::blobdata bd = db->get_block_blob_from_height(opt_height);
665  {
666  LOG_PRINT_L0("Bad block from db");
667  return 1;
668  }
669  for (const crypto::hash &txid: b.tx_hashes)
670  start_txids.push_back(txid);
671  }
672 
673  if (start_txids.empty())
674  {
675  LOG_PRINT_L0("No transaction(s) to check");
676  return 1;
677  }
678 
679  for (const crypto::hash &start_txid: start_txids)
680  {
681  LOG_PRINT_L0("Checking ancestry for txid " << start_txid);
682 
683  std::unordered_map<ancestor, unsigned int> ancestry;
684 
685  std::list<crypto::hash> txids;
686  txids.push_back(start_txid);
687  while (!txids.empty())
688  {
689  const crypto::hash txid = txids.front();
690  txids.pop_front();
691 
692  if (stop_requested)
693  goto done;
694 
695  ::tx_data_t tx_data2;
696  if (!get_transaction(state, db, txid, tx_data2))
697  return 1;
698 
699  const bool coinbase = tx_data2.coinbase;
700  if (coinbase)
701  continue;
702 
703  for (size_t ring = 0; ring < tx_data2.vin.size(); ++ring)
704  {
705  {
706  const uint64_t amount = tx_data2.vin[ring].first;
707  auto absolute_offsets = tx_data2.vin[ring].second;
708  for (uint64_t offset: absolute_offsets)
709  {
710  add_ancestor(ancestry, amount, offset);
711 
712  // find the tx which created this output
713  bool found = false;
714  crypto::hash output_txid;
715  if (!get_output_txid(state, db, amount, offset, output_txid))
716  {
717  LOG_PRINT_L0("Output originating transaction not found");
718  return 1;
719  }
720 
721  add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid));
722  txids.push_back(output_txid);
723  MDEBUG("adding txid: " << output_txid);
724  }
725  }
726  }
727  }
728 
729  MINFO("Ancestry for " << start_txid << ": " << get_deduplicated_ancestry(ancestry) << " / " << get_full_ancestry(ancestry));
730  for (const auto &i: ancestry)
731  {
732  MINFO(cryptonote::print_etn(i.first.amount) << "/" << i.first.offset << ": " << i.second);
733  }
734  }
735 
736 done:
737  core_storage->deinit();
738 
739  if (opt_show_cache_stats)
740  MINFO("cache: txes " << std::to_string(cached_txes*100./total_txes)
741  << "%, blocks " << std::to_string(cached_blocks*100./total_blocks)
742  << "%, outputs " << std::to_string(cached_outputs*100./total_outputs)
743  << "%");
744 
745  return 0;
746 
747  CATCH_ENTRY("Depth query error", 1);
748 }
const char *const ELECTRONEUM_RELEASE_NAME
#define MERROR(x)
Definition: misc_log_ex.h:73
std::vector< crypto::hash > tx_hashes
virtual std::string get_db_name() const =0
gets the name of the folder the BlockchainDB&#39;s file(s) should be in
#define DBF_RDONLY
#define MINFO(x)
Definition: misc_log_ex.h:75
virtual cryptonote::blobdata get_block_blob_from_height(const uint64_t &height) const =0
fetch a block blob by height
#define SCNu64
Definition: inttypes.h:245
bool set_module_name_and_folder(const std::string &path_to_process_)
Definition: string_tools.h:249
::std::string string
Definition: gtest-port.h:1097
std::string print_etn(uint64_t amount, unsigned int decimal_point)
#define CHECK_AND_ASSERT_MES(expr, fail_ret_val, message)
Definition: misc_log_ex.h:181
void mlog_set_log(const char *log)
Definition: mlog.cpp:288
#define CATCH_ENTRY(location, return_val)
Definition: misc_log_ex.h:152
std::string mlog_get_default_log_path(const char *default_filename)
Definition: mlog.cpp:72
void mlog_configure(const std::string &filename_base, bool console, const std::size_t max_log_file_size=MAX_LOG_FILE_SIZE, const std::size_t max_log_files=MAX_LOG_FILES)
Definition: mlog.cpp:148
#define LOG_PRINT_L0(x)
Definition: misc_log_ex.h:99
const command_line::arg_descriptor< bool, false > arg_stagenet_on
const arg_descriptor< bool > arg_help
std::string blockchain_db_types(const std::string &sep)
virtual void open(const std::string &filename, const int db_flags=0)=0
open a db, or create it if necessary.
virtual bool get_pruned_tx_blob(const crypto::hash &h, cryptonote::blobdata &tx) const =0
fetches the pruned transaction blob with the given hash
#define MDEBUG(x)
Definition: misc_log_ex.h:76
bool on_startup()
Definition: util.cpp:778
const char *const ELECTRONEUM_VERSION_FULL
bool blockchain_valid_db_type(const std::string &db_type)
const command_line::arg_descriptor< bool, false > arg_testnet_on
BlockchainDB * new_db(const std::string &db_type)
bool handle_error_helper(const boost::program_options::options_description &desc, F parser)
Definition: command_line.h:237
#define TRY_ENTRY()
Definition: misc_log_ex.h:151
unsigned int uint32_t
Definition: stdint.h:126
const command_line::arg_descriptor< std::string > arg_log_level
unsigned __int64 uint64_t
Definition: stdint.h:136
const command_line::arg_descriptor< std::string, false, true, 2 > arg_data_dir
virtual uint64_t height() const =0
fetch the current blockchain height
bool hex_to_pod(const std::string &hex_str, t_pod_type &s)
Definition: string_tools.h:324
bool parse_and_validate_tx_base_from_blob(const blobdata &tx_blob, transaction &tx)
#define MWARNING(x)
Definition: misc_log_ex.h:74
void add_arg(boost::program_options::options_description &description, const arg_descriptor< T, required, dependent, NUM_DEPS > &arg, bool unique=true)
Definition: command_line.h:188
static bool install(T t)
installs a signal handler
Definition: util.h:164
const GenericPointer< typename T::ValueType > T2 T::AllocatorType & a
Definition: pointer.h:1124
Transaction pool, handles transactions which are not part of a block.
Definition: tx_pool.h:94
std::string blobdata
Definition: blobdatatype.h:39
The BlockchainDB backing store interface declaration/contract.
#define LOG_ERROR(x)
Definition: misc_log_ex.h:98
#define ENDL
Definition: misc_log_ex.h:149
Definition: blake256.h:37
crypto::hash get_transaction_hash(const transaction &t)
T get_arg(const boost::program_options::variables_map &vm, const arg_descriptor< T, false, true > &arg)
Definition: command_line.h:271
bool init(BlockchainDB *db, const network_type nettype=MAINNET, bool offline=false, const cryptonote::test_options *test_options=NULL, difficulty_type fixed_difficulty=0, const GetCheckpointsCallback &get_checkpoints=nullptr, bool ignore_bsig=false, bool fallback_to_pow=false)
Initialize the Blockchain state.
Definition: blockchain.cpp:334
POD_CLASS hash
Definition: hash.h:50
std::string to_string(t_connection_type type)
bool is_arg_defaulted(const boost::program_options::variables_map &vm, const arg_descriptor< T, required, dependent, NUM_DEPS > &arg)
Definition: command_line.h:265
bool deinit()
Uninitializes the blockchain state.
Definition: blockchain.cpp:660
bool parse_and_validate_block_from_blob(const blobdata &b_blob, block &b, crypto::hash *block_hash)
Here is the call graph for this function: