Debian Codegraph @

monero/src/blockchain_utilities/blockchain_usage.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 <boost/range/adaptor/transformed.hpp>
30 #include <boost/algorithm/string.hpp>
31 #include <boost/filesystem/path.hpp>
32 #include "common/command_line.h"
33 #include "common/varint.h"
34 #include "cryptonote_core/tx_pool.h"
35 #include "cryptonote_core/cryptonote_core.h"
36 #include "cryptonote_core/blockchain.h"
37 #include "blockchain_db/blockchain_db.h"
38 #include "version.h"
39
40 #undef MONERO_DEFAULT_LOG_CATEGORY
41 #define MONERO_DEFAULT_LOG_CATEGORY "bcutil"
42
43 namespace po = boost::program_options;
44 using namespace epee;
45 using namespace cryptonote;
46
47 struct output_data
48 {
49 uint64_t amount;
50 uint64_t index;
51 mutable bool coinbase;
52 mutable uint64_t height;
53 output_data(uint64_t a, uint64_t i, bool cb, uint64_t h): amount(a), index(i), coinbase(cb), height(h) {}
54 bool operator==(const output_data &other) const { return other.amount == amount && other.index == index; }
55 void info(bool c, uint64_t h) const { coinbase = c; height =h; }
56 };
57 namespace std
58 {
59 template<> struct hash<output_data>
60 {
61 size_t operator()(const output_data &od) const
62 {
63 const uint64_t data[2] = {od.amount, od.index};
64 crypto::hash h;
65 crypto::cn_fast_hash(data, 2 * sizeof(uint64_t), h);
66 return reinterpret_cast<const std::size_t &>(h);
67 }
68 };
69 }
70
71 struct reference
72 {
73 uint64_t height;
74 uint64_t ring_size;
75 uint64_t position;
76 reference(uint64_t h, uint64_t rs, uint64_t p): height(h), ring_size(rs), position(p) {}
77 };
78
79 int main(int argc, char* argv[])
80 {
81 TRY_ENTRY();
82
83 epee::string_tools::set_module_name_and_folder(argv[0]);
84
85 uint32_t log_level = 0;
86
87 tools::on_startup();
88
89 boost::filesystem::path output_file_path;
90
91 po::options_description desc_cmd_only("Command line options");
92 po::options_description desc_cmd_sett("Command line options and settings options");
93 const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
94 const command_line::arg_descriptor<bool> arg_rct_only = {"rct-only", "Only work on ringCT outputs", false};
95 const command_line::arg_descriptor<std::string> arg_input = {"input", ""};
96
97 command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
98 command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
99 command_line::add_arg(desc_cmd_sett, arg_log_level);
100 command_line::add_arg(desc_cmd_sett, arg_rct_only);
101 command_line::add_arg(desc_cmd_sett, arg_input);
102 command_line::add_arg(desc_cmd_only, command_line::arg_help);
103
104 po::options_description desc_options("Allowed options");
105 desc_options.add(desc_cmd_only).add(desc_cmd_sett);
106
107 po::positional_options_description positional_options;
108 positional_options.add(arg_input.name, -1);
109
110 po::variables_map vm;
111 bool r = command_line::handle_error_helper(desc_options, [&]()
112 {
113 auto parser = po::command_line_parser(argc, argv).options(desc_options).positional(positional_options);
114 po::store(parser.run(), vm);
115 po::notify(vm);
116 return true;
117 });
118 if (! r)
119 return 1;
120
121 if (command_line::get_arg(vm, command_line::arg_help))
122 {
123 std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
124 std::cout << desc_options << std::endl;
125 return 1;
126 }
127
128 mlog_configure(mlog_get_default_log_path("monero-blockchain-usage.log"), true);
129 if (!command_line::is_arg_defaulted(vm, arg_log_level))
130 mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
131 else
132 mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
133
134 LOG_PRINT_L0("Starting...");
135
136 bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
137 bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
138 network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
139 bool opt_rct_only = command_line::get_arg(vm, arg_rct_only);
140
141 // If we wanted to use the memory pool, we would set up a fake_core.
142
143 // Use Blockchain instead of lower-level BlockchainDB for two reasons:
144 // 1. Blockchain has the init() method for easy setup
145 // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
146 //
147 // cannot match blockchain_storage setup above with just one line,
148 // e.g.
149 // Blockchain* core_storage = new Blockchain(NULL);
150 // because unlike blockchain_storage constructor, which takes a pointer to
151 // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
152 LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
153 const std::string input = command_line::get_arg(vm, arg_input);
154 std::unique_ptr<Blockchain> core_storage;
155 tx_memory_pool m_mempool(*core_storage);
156 core_storage.reset(new Blockchain(m_mempool));
157 BlockchainDB* db = new_db();
158 if (db == NULL)
159 {
160 LOG_ERROR("Failed to initialize a database");
161 throw std::runtime_error("Failed to initialize a database");
162 }
163 LOG_PRINT_L0("database: LMDB");
164
165 const std::string filename = input;
166 LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
167
168 try
169 {
170 db->open(filename, DBF_RDONLY);
171 }
172 catch (const std::exception& e)
173 {
174 LOG_PRINT_L0("Error opening database: " << e.what());
175 return 1;
176 }
177 r = core_storage->init(db, net_type);
178
179 CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
180 LOG_PRINT_L0("Source blockchain storage initialized OK");
181
182 LOG_PRINT_L0("Building usage patterns...");
183
184 std::unordered_map<output_data, std::list<reference>> outputs;
185 std::unordered_map<uint64_t,uint64_t> indices;
186
187 LOG_PRINT_L0("Reading blockchain from " << input);
188 core_storage->for_all_transactions([&](const crypto::hash &hash, const cryptonote::transaction &tx)->bool
189 {
190 const bool coinbase = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
191 const uint64_t height = core_storage->get_db().get_tx_block_height(hash);
192
193 // create new outputs
194 for (const auto &out: tx.vout)
195 {
196 if (opt_rct_only && out.amount)
197 continue;
198 indices[out.amount]++;
199 output_data od(out.amount, indices[out.amount], coinbase, height);
200 auto itb = outputs.emplace(od, std::list<reference>());
201 itb.first->first.info(coinbase, height);
202 }
203
204 for (const auto &in: tx.vin)
205 {
206 if (in.type() != typeid(txin_to_key))
207 continue;
208 const auto &txin = boost::get<txin_to_key>(in);
209 if (opt_rct_only && txin.amount != 0)
210 continue;
211
212 const std::vector<uint64_t> absolute = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets);
213 for (size_t n = 0; n < txin.key_offsets.size(); ++n)
214 {
215 output_data od(txin.amount, absolute[n], coinbase, height);
216 outputs[od].push_back(reference(height, txin.key_offsets.size(), n));
217 }
218 }
219 return true;
220 }, true);
221
222 std::unordered_map<uint64_t, uint64_t> counts;
223 size_t total = 0;
224 for (const auto &out: outputs)
225 {
226 counts[out.second.size()]++;
227 total++;
228 }
229 if (total > 0)
230 {
231 for (const auto &c: counts)
232 {
233 float percent = 100.f * c.second / total;
234 MINFO(std::to_string(c.second) << " outputs used " << c.first << " times (" << percent << "%)");
235 }
236 }
237 else
238 {
239 MINFO("No outputs to process");
240 }
241
242 LOG_PRINT_L0("Blockchain usage exported OK");
243 return 0;
244
245 CATCH_ENTRY("Export error", 1);
246 }