Debian Codegraph @

monero/src/blockchain_utilities/blockchain_ancestry.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 <unordered_map>
30 #include <unordered_set>
31 #include <boost/range/adaptor/transformed.hpp>
32 #include <boost/algorithm/string.hpp>
33 #include <boost/archive/portable_binary_iarchive.hpp>
34 #include <boost/archive/portable_binary_oarchive.hpp>
35 #include <boost/filesystem/path.hpp>
36 #include "common/unordered_containers_boost_serialization.h"
37 #include "common/command_line.h"
38 #include "common/varint.h"
39 #include "cryptonote_basic/cryptonote_boost_serialization.h"
40 #include "cryptonote_core/tx_pool.h"
41 #include "cryptonote_core/cryptonote_core.h"
42 #include "cryptonote_core/blockchain.h"
43 #include "blockchain_db/blockchain_db.h"
44 #include "version.h"
45
46 #undef MONERO_DEFAULT_LOG_CATEGORY
47 #define MONERO_DEFAULT_LOG_CATEGORY "bcutil"
48
49 namespace po = boost::program_options;
50 using namespace epee;
51 using namespace cryptonote;
52
53 static bool stop_requested = false;
54 static uint64_t cached_txes = 0, cached_blocks = 0, cached_outputs = 0, total_txes = 0, total_blocks = 0, total_outputs = 0;
55 static bool opt_cache_outputs = false, opt_cache_txes = false, opt_cache_blocks = false;
56
57 struct ancestor
58 {
59 uint64_t amount;
60 uint64_t offset;
61
62 bool operator==(const ancestor &other) const { return amount == other.amount && offset == other.offset; }
63
64 template <typename t_archive> void serialize(t_archive &a, const unsigned int ver)
65 {
66 a & amount;
67 a & offset;
68 }
69 };
70 BOOST_CLASS_VERSION(ancestor, 0)
71
72 namespace std
73 {
74 template<> struct hash<ancestor>
75 {
76 size_t operator()(const ancestor &a) const
77 {
78 return a.amount ^ a.offset; // not that bad, since amount almost always have a high bit set, and offset doesn't
79 }
80 };
81 }
82
83 struct tx_data_t
84 {
85 std::vector<std::pair<uint64_t, std::vector<uint64_t>>> vin;
86 std::vector<crypto::public_key> vout;
87 bool coinbase;
88
89 tx_data_t(): coinbase(false) {}
90 tx_data_t(const cryptonote::transaction &tx)
91 {
92 coinbase = tx.vin.size() == 1 && tx.vin[0].type() == typeid(cryptonote::txin_gen);
93 if (!coinbase)
94 {
95 vin.reserve(tx.vin.size());
96 for (size_t ring = 0; ring < tx.vin.size(); ++ring)
97 {
98 if (tx.vin[ring].type() == typeid(cryptonote::txin_to_key))
99 {
100 const cryptonote::txin_to_key &txin = boost::get<cryptonote::txin_to_key>(tx.vin[ring]);
101 vin.push_back(std::make_pair(txin.amount, cryptonote::relative_output_offsets_to_absolute(txin.key_offsets)));
102 }
103 else
104 {
105 LOG_PRINT_L0("Bad vin type in txid " << get_transaction_hash(tx));
106 throw std::runtime_error("Bad vin type");
107 }
108 }
109 }
110 vout.reserve(tx.vout.size());
111 for (size_t out = 0; out < tx.vout.size(); ++out)
112 {
113 if (tx.vout[out].target.type() == typeid(cryptonote::txout_to_key))
114 {
115 const auto &txout = boost::get<cryptonote::txout_to_key>(tx.vout[out].target);
116 vout.push_back(txout.key);
117 }
118 else
119 {
120 LOG_PRINT_L0("Bad vout type in txid " << get_transaction_hash(tx));
121 throw std::runtime_error("Bad vout type");
122 }
123 }
124 }
125
126 template <typename t_archive> void serialize(t_archive &a, const unsigned int ver)
127 {
128 a & coinbase;
129 a & vin;
130 a & vout;
131 }
132 };
133
134 struct ancestry_state_t
135 {
136 uint64_t height;
137 std::unordered_map<crypto::hash, std::unordered_set<ancestor>> ancestry;
138 std::unordered_map<ancestor, crypto::hash> output_cache;
139 std::unordered_map<crypto::hash, ::tx_data_t> tx_cache;
140 std::vector<cryptonote::block> block_cache;
141
142 ancestry_state_t(): height(0) {}
143
144 template <typename t_archive> void serialize(t_archive &a, const unsigned int ver)
145 {
146 a & height;
147 a & ancestry;
148 a & output_cache;
149 if (ver < 1)
150 {
151 std::unordered_map<crypto::hash, cryptonote::transaction> old_tx_cache;
152 a & old_tx_cache;
153 for (const auto& i: old_tx_cache)
154 tx_cache.insert(std::make_pair(i.first, ::tx_data_t(i.second)));
155 }
156 else
157 {
158 a & tx_cache;
159 }
160 if (ver < 2)
161 {
162 std::unordered_map<uint64_t, cryptonote::block> old_block_cache;
163 a & old_block_cache;
164 block_cache.resize(old_block_cache.size());
165 for (const auto& i: old_block_cache)
166 block_cache[i.first] = i.second;
167 }
168 else
169 {
170 a & block_cache;
171 }
172 }
173 };
174 BOOST_CLASS_VERSION(ancestry_state_t, 2)
175
176 static void add_ancestor(std::unordered_map<ancestor, unsigned int> &ancestry, uint64_t amount, uint64_t offset)
177 {
178 std::pair<std::unordered_map<ancestor, unsigned int>::iterator, bool> p = ancestry.insert(std::make_pair(ancestor{amount, offset}, 1));
179 if (!p.second)
180 {
181 ++p.first->second;
182 }
183 }
184
185 static size_t get_full_ancestry(const std::unordered_map<ancestor, unsigned int> &ancestry)
186 {
187 size_t count = 0;
188 for (const auto &i: ancestry)
189 count += i.second;
190 return count;
191 }
192
193 static size_t get_deduplicated_ancestry(const std::unordered_map<ancestor, unsigned int> &ancestry)
194 {
195 return ancestry.size();
196 }
197
198 static void add_ancestry(std::unordered_map<crypto::hash, std::unordered_set<ancestor>> &ancestry, const crypto::hash &txid, const std::unordered_set<ancestor> &ancestors)
199 {
200 std::pair<std::unordered_map<crypto::hash, std::unordered_set<ancestor>>::iterator, bool> p = ancestry.insert(std::make_pair(txid, ancestors));
201 if (!p.second)
202 {
203 for (const auto &e: ancestors)
204 p.first->second.insert(e);
205 }
206 }
207
208 static void add_ancestry(std::unordered_map<crypto::hash, std::unordered_set<ancestor>> &ancestry, const crypto::hash &txid, const ancestor &new_ancestor)
209 {
210 std::pair<std::unordered_map<crypto::hash, std::unordered_set<ancestor>>::iterator, bool> p = ancestry.insert(std::make_pair(txid, std::unordered_set<ancestor>()));
211 p.first->second.insert(new_ancestor);
212 }
213
214 static std::unordered_set<ancestor> get_ancestry(const std::unordered_map<crypto::hash, std::unordered_set<ancestor>> &ancestry, const crypto::hash &txid)
215 {
216 std::unordered_map<crypto::hash, std::unordered_set<ancestor>>::const_iterator i = ancestry.find(txid);
217 if (i == ancestry.end())
218 {
219 //MERROR("txid ancestry not found: " << txid);
220 //throw std::runtime_error("txid ancestry not found");
221 return std::unordered_set<ancestor>();
222 }
223 return i->second;
224 }
225
226 static bool get_block_from_height(ancestry_state_t &state, BlockchainDB *db, uint64_t height, cryptonote::block &b)
227 {
228 ++total_blocks;
229 if (state.block_cache.size() > height && !state.block_cache[height].miner_tx.vin.empty())
230 {
231 ++cached_blocks;
232 b = state.block_cache[height];
233 return true;
234 }
235 cryptonote::blobdata bd = db->get_block_blob_from_height(height);
236 if (!cryptonote::parse_and_validate_block_from_blob(bd, b))
237 {
238 LOG_PRINT_L0("Bad block from db");
239 return false;
240 }
241 if (opt_cache_blocks)
242 {
243 state.block_cache.resize(height + 1);
244 state.block_cache[height] = b;
245 }
246 return true;
247 }
248
249 static bool get_transaction(ancestry_state_t &state, BlockchainDB *db, const crypto::hash &txid, ::tx_data_t &tx_data)
250 {
251 std::unordered_map<crypto::hash, ::tx_data_t>::const_iterator i = state.tx_cache.find(txid);
252 ++total_txes;
253 if (i != state.tx_cache.end())
254 {
255 ++cached_txes;
256 tx_data = i->second;
257 return true;
258 }
259
260 cryptonote::blobdata bd;
261 if (!db->get_pruned_tx_blob(txid, bd))
262 {
263 LOG_PRINT_L0("Failed to get txid " << txid << " from db");
264 return false;
265 }
266 cryptonote::transaction tx;
267 if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx))
268 {
269 LOG_PRINT_L0("Bad tx: " << txid);
270 return false;
271 }
272 tx_data = ::tx_data_t(tx);
273 if (opt_cache_txes)
274 state.tx_cache.insert(std::make_pair(txid, tx_data));
275 return true;
276 }
277
278 static bool get_output_txid(ancestry_state_t &state, BlockchainDB *db, uint64_t amount, uint64_t offset, crypto::hash &txid)
279 {
280 ++total_outputs;
281 std::unordered_map<ancestor, crypto::hash>::const_iterator i = state.output_cache.find({amount, offset});
282 if (i != state.output_cache.end())
283 {
284 ++cached_outputs;
285 txid = i->second;
286 return true;
287 }
288
289 const output_data_t od = db->get_output_key(amount, offset, false);
290 cryptonote::block b;
291 if (!get_block_from_height(state, db, od.height, b))
292 return false;
293
294 for (size_t out = 0; out < b.miner_tx.vout.size(); ++out)
295 {
296 if (b.miner_tx.vout[out].target.type() == typeid(cryptonote::txout_to_key))
297 {
298 const auto &txout = boost::get<cryptonote::txout_to_key>(b.miner_tx.vout[out].target);
299 if (txout.key == od.pubkey)
300 {
301 txid = cryptonote::get_transaction_hash(b.miner_tx);
302 if (opt_cache_outputs)
303 state.output_cache.insert(std::make_pair(ancestor{amount, offset}, txid));
304 return true;
305 }
306 }
307 else
308 {
309 LOG_PRINT_L0("Bad vout type in txid " << cryptonote::get_transaction_hash(b.miner_tx));
310 return false;
311 }
312 }
313 for (const crypto::hash &block_txid: b.tx_hashes)
314 {
315 ::tx_data_t tx_data3;
316 if (!get_transaction(state, db, block_txid, tx_data3))
317 return false;
318
319 for (size_t out = 0; out < tx_data3.vout.size(); ++out)
320 {
321 if (tx_data3.vout[out] == od.pubkey)
322 {
323 txid = block_txid;
324 if (opt_cache_outputs)
325 state.output_cache.insert(std::make_pair(ancestor{amount, offset}, txid));
326 return true;
327 }
328 }
329 }
330 return false;
331 }
332
333 int main(int argc, char* argv[])
334 {
335 TRY_ENTRY();
336
337 epee::string_tools::set_module_name_and_folder(argv[0]);
338
339 uint32_t log_level = 0;
340
341 tools::on_startup();
342
343 boost::filesystem::path output_file_path;
344
345 po::options_description desc_cmd_only("Command line options");
346 po::options_description desc_cmd_sett("Command line options and settings options");
347 const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
348 const command_line::arg_descriptor<std::string> arg_txid = {"txid", "Get ancestry for this txid", ""};
349 const command_line::arg_descriptor<std::string> arg_output = {"output", "Get ancestry for this output (amount/offset format)", ""};
350 const command_line::arg_descriptor<uint64_t> arg_height = {"height", "Get ancestry for all txes at this height", 0};
351 const command_line::arg_descriptor<bool> arg_refresh = {"refresh", "Refresh the whole chain first", false};
352 const command_line::arg_descriptor<bool> arg_cache_outputs = {"cache-outputs", "Cache outputs (memory hungry)", false};
353 const command_line::arg_descriptor<bool> arg_cache_txes = {"cache-txes", "Cache txes (memory hungry)", false};
354 const command_line::arg_descriptor<bool> arg_cache_blocks = {"cache-blocks", "Cache blocks (memory hungry)", false};
355 const command_line::arg_descriptor<bool> arg_include_coinbase = {"include-coinbase", "Including coinbase tx in per height average", false};
356 const command_line::arg_descriptor<bool> arg_show_cache_stats = {"show-cache-stats", "Show cache statistics", false};
357
358 command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir);
359 command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
360 command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
361 command_line::add_arg(desc_cmd_sett, arg_log_level);
362 command_line::add_arg(desc_cmd_sett, arg_txid);
363 command_line::add_arg(desc_cmd_sett, arg_output);
364 command_line::add_arg(desc_cmd_sett, arg_height);
365 command_line::add_arg(desc_cmd_sett, arg_refresh);
366 command_line::add_arg(desc_cmd_sett, arg_cache_outputs);
367 command_line::add_arg(desc_cmd_sett, arg_cache_txes);
368 command_line::add_arg(desc_cmd_sett, arg_cache_blocks);
369 command_line::add_arg(desc_cmd_sett, arg_include_coinbase);
370 command_line::add_arg(desc_cmd_sett, arg_show_cache_stats);
371 command_line::add_arg(desc_cmd_only, command_line::arg_help);
372
373 po::options_description desc_options("Allowed options");
374 desc_options.add(desc_cmd_only).add(desc_cmd_sett);
375
376 po::variables_map vm;
377 bool r = command_line::handle_error_helper(desc_options, [&]()
378 {
379 auto parser = po::command_line_parser(argc, argv).options(desc_options);
380 po::store(parser.run(), vm);
381 po::notify(vm);
382 return true;
383 });
384 if (! r)
385 return 1;
386
387 if (command_line::get_arg(vm, command_line::arg_help))
388 {
389 std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
390 std::cout << desc_options << std::endl;
391 return 1;
392 }
393
394 mlog_configure(mlog_get_default_log_path("monero-blockchain-ancestry.log"), true);
395 if (!command_line::is_arg_defaulted(vm, arg_log_level))
396 mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
397 else
398 mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
399
400 LOG_PRINT_L0("Starting...");
401
402 std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
403 bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
404 bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
405 network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
406 std::string opt_txid_string = command_line::get_arg(vm, arg_txid);
407 std::string opt_output_string = command_line::get_arg(vm, arg_output);
408 uint64_t opt_height = command_line::get_arg(vm, arg_height);
409 bool opt_refresh = command_line::get_arg(vm, arg_refresh);
410 opt_cache_outputs = command_line::get_arg(vm, arg_cache_outputs);
411 opt_cache_txes = command_line::get_arg(vm, arg_cache_txes);
412 opt_cache_blocks = command_line::get_arg(vm, arg_cache_blocks);
413 bool opt_include_coinbase = command_line::get_arg(vm, arg_include_coinbase);
414 bool opt_show_cache_stats = command_line::get_arg(vm, arg_show_cache_stats);
415
416 if ((!opt_txid_string.empty()) + !!opt_height + !opt_output_string.empty() > 1)
417 {
418 std::cerr << "Only one of --txid, --height, --output can be given" << std::endl;
419 return 1;
420 }
421 crypto::hash opt_txid = crypto::null_hash;
422 uint64_t output_amount = 0, output_offset = 0;
423 if (!opt_txid_string.empty())
424 {
425 if (!epee::string_tools::hex_to_pod(opt_txid_string, opt_txid))
426 {
427 std::cerr << "Invalid txid" << std::endl;
428 return 1;
429 }
430 }
431 else if (!opt_output_string.empty())
432 {
433 if (sscanf(opt_output_string.c_str(), "%" SCNu64 "/%" SCNu64, &output_amount, &output_offset) != 2)
434 {
435 std::cerr << "Invalid output" << std::endl;
436 return 1;
437 }
438 }
439
440 // If we wanted to use the memory pool, we would set up a fake_core.
441
442 // Use Blockchain instead of lower-level BlockchainDB for two reasons:
443 // 1. Blockchain has the init() method for easy setup
444 // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
445 //
446 // cannot match blockchain_storage setup above with just one line,
447 // e.g.
448 // Blockchain* core_storage = new Blockchain(NULL);
449 // because unlike blockchain_storage constructor, which takes a pointer to
450 // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
451 LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
452 std::unique_ptr<Blockchain> core_storage;
453 tx_memory_pool m_mempool(*core_storage);
454 core_storage.reset(new Blockchain(m_mempool));
455 BlockchainDB *db = new_db();
456 if (db == NULL)
457 {
458 LOG_ERROR("Failed to initialize a database");
459 throw std::runtime_error("Failed to initialize a database");
460 }
461 LOG_PRINT_L0("database: LMDB");
462
463 const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
464 LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
465
466 try
467 {
468 db->open(filename, DBF_RDONLY);
469 }
470 catch (const std::exception& e)
471 {
472 LOG_PRINT_L0("Error opening database: " << e.what());
473 return 1;
474 }
475 r = core_storage->init(db, net_type);
476
477 CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
478 LOG_PRINT_L0("Source blockchain storage initialized OK");
479
480 std::vector<crypto::hash> start_txids;
481
482 ancestry_state_t state;
483
484 const std::string state_file_path = (boost::filesystem::path(opt_data_dir) / "ancestry-state.bin").string();
485 LOG_PRINT_L0("Loading state data from " << state_file_path);
486 std::ifstream state_data_in;
487 state_data_in.open(state_file_path, std::ios_base::binary | std::ios_base::in);
488 if (!state_data_in.fail())
489 {
490 try
491 {
492 boost::archive::portable_binary_iarchive a(state_data_in);
493 a >> state;
494 }
495 catch (const std::exception &e)
496 {
497 MERROR("Failed to load state data from " << state_file_path << ", restarting from scratch");
498 state = ancestry_state_t();
499 }
500 state_data_in.close();
501 }
502
503 tools::signal_handler::install([](int type) {
504 stop_requested = true;
505 });
506
507 // forward method
508 const uint64_t db_height = db->height();
509 if (opt_refresh)
510 {
511 MINFO("Starting from height " << state.height);
512 state.block_cache.reserve(db_height);
513 for (uint64_t h = state.height; h < db_height; ++h)
514 {
515 size_t block_ancestry_size = 0;
516 const cryptonote::blobdata bd = db->get_block_blob_from_height(h);
517 ++total_blocks;
518 cryptonote::block b;
519 if (!cryptonote::parse_and_validate_block_from_blob(bd, b))
520 {
521 LOG_PRINT_L0("Bad block from db");
522 return 1;
523 }
524 if (opt_cache_blocks)
525 {
526 state.block_cache.resize(h + 1);
527 state.block_cache[h] = b;
528 }
529 std::vector<crypto::hash> txids;
530 txids.reserve(1 + b.tx_hashes.size());
531 if (opt_include_coinbase)
532 txids.push_back(cryptonote::get_transaction_hash(b.miner_tx));
533 for (const auto &h: b.tx_hashes)
534 txids.push_back(h);
535 for (const crypto::hash &txid: txids)
536 {
537 printf("%lu/%lu \r", (unsigned long)h, (unsigned long)db_height);
538 fflush(stdout);
539 ::tx_data_t tx_data;
540 std::unordered_map<crypto::hash, ::tx_data_t>::const_iterator i = state.tx_cache.find(txid);
541 ++total_txes;
542 if (i != state.tx_cache.end())
543 {
544 ++cached_txes;
545 tx_data = i->second;
546 }
547 else
548 {
549 cryptonote::blobdata bd;
550 if (!db->get_pruned_tx_blob(txid, bd))
551 {
552 LOG_PRINT_L0("Failed to get txid " << txid << " from db");
553 return 1;
554 }
555 cryptonote::transaction tx;
556 if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx))
557 {
558 LOG_PRINT_L0("Bad tx: " << txid);
559 return 1;
560 }
561 tx_data = ::tx_data_t(tx);
562 if (opt_cache_txes)
563 state.tx_cache.insert(std::make_pair(txid, tx_data));
564 }
565 if (tx_data.coinbase)
566 {
567 add_ancestry(state.ancestry, txid, std::unordered_set<ancestor>());
568 }
569 else
570 {
571 for (size_t ring = 0; ring < tx_data.vin.size(); ++ring)
572 {
573 const uint64_t amount = tx_data.vin[ring].first;
574 const std::vector<uint64_t> &absolute_offsets = tx_data.vin[ring].second;
575 for (uint64_t offset: absolute_offsets)
576 {
577 add_ancestry(state.ancestry, txid, ancestor{amount, offset});
578 // find the tx which created this output
579 crypto::hash output_txid;
580 if (!get_output_txid(state, db, amount, offset, output_txid))
581 {
582 LOG_PRINT_L0("Output originating transaction not found");
583 return 1;
584 }
585 add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid));
586 }
587 }
588 }
589 const size_t ancestry_size = get_ancestry(state.ancestry, txid).size();
590 block_ancestry_size += ancestry_size;
591 MINFO(txid << ": " << ancestry_size);
592 }
593 if (!txids.empty())
594 {
595 std::string stats_msg;
596 MINFO("Height " << h << ": " << (block_ancestry_size / txids.size()) << " average over " << txids.size() << stats_msg);
597 }
598 state.height = h;
599 if (stop_requested)
600 break;
601 }
602
603 LOG_PRINT_L0("Saving state data to " << state_file_path);
604 std::ofstream state_data_out;
605 state_data_out.open(state_file_path, std::ios_base::binary | std::ios_base::out | std::ios::trunc);
606 if (!state_data_out.fail())
607 {
608 try
609 {
610 boost::archive::portable_binary_oarchive a(state_data_out);
611 a << state;
612 }
613 catch (const std::exception &e)
614 {
615 MERROR("Failed to save state data to " << state_file_path);
616 }
617 state_data_out.close();
618 }
619 }
620 else
621 {
622 if (state.height < db_height)
623 {
624 MWARNING("The state file is only built up to height " << state.height << ", but the blockchain reached height " << db_height);
625 MWARNING("You may want to run with --refresh if you want to get ancestry for newer data");
626 }
627 }
628
629 if (!opt_txid_string.empty())
630 {
631 start_txids.push_back(opt_txid);
632 }
633 else if (!opt_output_string.empty())
634 {
635 crypto::hash txid;
636 if (!get_output_txid(state, db, output_amount, output_offset, txid))
637 {
638 LOG_PRINT_L0("Output not found in db");
639 return 1;
640 }
641 start_txids.push_back(txid);
642 }
643 else
644 {
645 const cryptonote::blobdata bd = db->get_block_blob_from_height(opt_height);
646 cryptonote::block b;
647 if (!cryptonote::parse_and_validate_block_from_blob(bd, b))
648 {
649 LOG_PRINT_L0("Bad block from db");
650 return 1;
651 }
652 for (const crypto::hash &txid: b.tx_hashes)
653 start_txids.push_back(txid);
654 }
655
656 if (start_txids.empty())
657 {
658 LOG_PRINT_L0("No transaction(s) to check");
659 return 1;
660 }
661
662 for (const crypto::hash &start_txid: start_txids)
663 {
664 LOG_PRINT_L0("Checking ancestry for txid " << start_txid);
665
666 std::unordered_map<ancestor, unsigned int> ancestry;
667
668 std::list<crypto::hash> txids;
669 txids.push_back(start_txid);
670 while (!txids.empty())
671 {
672 const crypto::hash txid = txids.front();
673 txids.pop_front();
674
675 if (stop_requested)
676 goto done;
677
678 ::tx_data_t tx_data2;
679 if (!get_transaction(state, db, txid, tx_data2))
680 return 1;
681
682 const bool coinbase = tx_data2.coinbase;
683 if (coinbase)
684 continue;
685
686 for (size_t ring = 0; ring < tx_data2.vin.size(); ++ring)
687 {
688 {
689 const uint64_t amount = tx_data2.vin[ring].first;
690 auto absolute_offsets = tx_data2.vin[ring].second;
691 for (uint64_t offset: absolute_offsets)
692 {
693 add_ancestor(ancestry, amount, offset);
694
695 // find the tx which created this output
696 crypto::hash output_txid;
697 if (!get_output_txid(state, db, amount, offset, output_txid))
698 {
699 LOG_PRINT_L0("Output originating transaction not found");
700 return 1;
701 }
702
703 add_ancestry(state.ancestry, txid, get_ancestry(state.ancestry, output_txid));
704 txids.push_back(output_txid);
705 MDEBUG("adding txid: " << output_txid);
706 }
707 }
708 }
709 }
710
711 MINFO("Ancestry for " << start_txid << ": " << get_deduplicated_ancestry(ancestry) << " / " << get_full_ancestry(ancestry));
712 for (const auto &i: ancestry)
713 {
714 MINFO(cryptonote::print_money(i.first.amount) << "/" << i.first.offset << ": " << i.second);
715 }
716 }
717
718 done:
719 core_storage->deinit();
720
721 if (opt_show_cache_stats)
722 MINFO("cache: txes " << std::to_string(cached_txes*100./total_txes)
723 << "%, blocks " << std::to_string(cached_blocks*100./total_blocks)
724 << "%, outputs " << std::to_string(cached_outputs*100./total_outputs)
725 << "%");
726
727 return 0;
728
729 CATCH_ENTRY("Depth query error", 1);
730 }