Debian Codegraph @

src/blockchain_utilities/blockchain_depth.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/filesystem/path.hpp>
31 #include <boost/algorithm/string.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 int main(int argc, char* argv[])
48 {
49 TRY_ENTRY();
50
51 epee::string_tools::set_module_name_and_folder(argv[0]);
52
53 uint32_t log_level = 0;
54
55 tools::on_startup();
56
57 boost::filesystem::path output_file_path;
58
59 po::options_description desc_cmd_only("Command line options");
60 po::options_description desc_cmd_sett("Command line options and settings options");
61 const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
62 const command_line::arg_descriptor<std::string> arg_txid = {"txid", "Get min depth for this txid", ""};
63 const command_line::arg_descriptor<uint64_t> arg_height = {"height", "Get min depth for all txes at this height", 0};
64 const command_line::arg_descriptor<bool> arg_include_coinbase = {"include-coinbase", "Include coinbase in the average", false};
65
66 command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir);
67 command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
68 command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
69 command_line::add_arg(desc_cmd_sett, cryptonote::arg_regtest_on);
70 command_line::add_arg(desc_cmd_sett, arg_log_level);
71 command_line::add_arg(desc_cmd_sett, arg_txid);
72 command_line::add_arg(desc_cmd_sett, arg_height);
73 command_line::add_arg(desc_cmd_sett, arg_include_coinbase);
74 command_line::add_arg(desc_cmd_only, command_line::arg_help);
75
76 po::options_description desc_options("Allowed options");
77 desc_options.add(desc_cmd_only).add(desc_cmd_sett);
78
79 po::variables_map vm;
80 bool r = command_line::handle_error_helper(desc_options, [&]()
81 {
82 auto parser = po::command_line_parser(argc, argv).options(desc_options);
83 po::store(parser.run(), vm);
84 po::notify(vm);
85 return true;
86 });
87 if (! r)
88 return 1;
89
90 if (command_line::get_arg(vm, command_line::arg_help))
91 {
92 std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
93 std::cout << desc_options << std::endl;
94 return 1;
95 }
96
97 mlog_configure(mlog_get_default_log_path("monero-blockchain-depth.log"), true);
98 if (!command_line::is_arg_defaulted(vm, arg_log_level))
99 mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
100 else
101 mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
102
103 LOG_PRINT_L0("Starting...");
104
105 std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
106 const network_type net_type = core::get_network_type_from_args(vm);
107 std::string opt_txid_string = command_line::get_arg(vm, arg_txid);
108 uint64_t opt_height = command_line::get_arg(vm, arg_height);
109 bool opt_include_coinbase = command_line::get_arg(vm, arg_include_coinbase);
110
111 if (!opt_txid_string.empty() && opt_height)
112 {
113 std::cerr << "txid and height cannot be given at the same time" << std::endl;
114 return 1;
115 }
116 crypto::hash opt_txid = crypto::null_hash;
117 if (!opt_txid_string.empty())
118 {
119 if (!epee::string_tools::hex_to_pod(opt_txid_string, opt_txid))
120 {
121 std::cerr << "Invalid txid" << std::endl;
122 return 1;
123 }
124 }
125
126 // If we wanted to use the memory pool, we would set up a fake_core.
127
128 // Use Blockchain instead of lower-level BlockchainDB for two reasons:
129 // 1. Blockchain has the init() method for easy setup
130 // 2. exporter needs to use get_current_blockchain_height(), get_block_id_by_height(), get_block_by_hash()
131 //
132 // cannot match blockchain_storage setup above with just one line,
133 // e.g.
134 // Blockchain* core_storage = new Blockchain(NULL);
135 // because unlike blockchain_storage constructor, which takes a pointer to
136 // tx_memory_pool, Blockchain's constructor takes tx_memory_pool object.
137 LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
138 std::unique_ptr<Blockchain> core_storage;
139 tx_memory_pool m_mempool(*core_storage);
140 core_storage.reset(new Blockchain(m_mempool));
141 BlockchainDB *db = new_db();
142 if (db == NULL)
143 {
144 LOG_ERROR("Failed to initialize a database");
145 throw std::runtime_error("Failed to initialize a database");
146 }
147 LOG_PRINT_L0("database: LMDB");
148
149 const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
150 LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
151
152 try
153 {
154 db->open(filename, DBF_RDONLY);
155 }
156 catch (const std::exception& e)
157 {
158 LOG_PRINT_L0("Error opening database: " << e.what());
159 return 1;
160 }
161 r = core_storage->init(db, net_type);
162
163 CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
164 LOG_PRINT_L0("Source blockchain storage initialized OK");
165
166 std::vector<crypto::hash> start_txids;
167 if (!opt_txid_string.empty())
168 {
169 start_txids.push_back(opt_txid);
170 }
171 else
172 {
173 const cryptonote::blobdata bd = db->get_block_blob_from_height(opt_height);
174 cryptonote::block b;
175 if (!cryptonote::parse_and_validate_block_from_blob(bd, b))
176 {
177 LOG_PRINT_L0("Bad block from db");
178 return 1;
179 }
180 for (const crypto::hash &txid: b.tx_hashes)
181 start_txids.push_back(txid);
182 if (opt_include_coinbase)
183 start_txids.push_back(cryptonote::get_transaction_hash(b.miner_tx));
184 }
185
186 if (start_txids.empty())
187 {
188 LOG_PRINT_L0("No transaction(s) to check");
189 return 1;
190 }
191
192 std::vector<uint64_t> depths;
193 for (const crypto::hash &start_txid: start_txids)
194 {
195 uint64_t depth = 0;
196 bool coinbase = false;
197
198 LOG_PRINT_L0("Checking depth for txid " << start_txid);
199 std::vector<crypto::hash> txids(1, start_txid);
200 while (!coinbase)
201 {
202 LOG_PRINT_L0("Considering "<< txids.size() << " transaction(s) at depth " << depth);
203 std::vector<crypto::hash> new_txids;
204 for (const crypto::hash &txid: txids)
205 {
206 cryptonote::blobdata bd;
207 if (!db->get_pruned_tx_blob(txid, bd))
208 {
209 LOG_PRINT_L0("Failed to get txid " << txid << " from db");
210 return 1;
211 }
212 cryptonote::transaction tx;
213 if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx))
214 {
215 LOG_PRINT_L0("Bad tx: " << txid);
216 return 1;
217 }
218 for (size_t ring = 0; ring < tx.vin.size(); ++ring)
219 {
220 if (tx.vin[ring].type() == typeid(cryptonote::txin_gen))
221 {
222 MDEBUG(txid << " is a coinbase transaction");
223 coinbase = true;
224 goto done;
225 }
226 if (tx.vin[ring].type() == typeid(cryptonote::txin_to_key))
227 {
228 const cryptonote::txin_to_key &txin = boost::get<cryptonote::txin_to_key>(tx.vin[ring]);
229 const uint64_t amount = txin.amount;
230 auto absolute_offsets = cryptonote::relative_output_offsets_to_absolute(txin.key_offsets);
231 for (uint64_t offset: absolute_offsets)
232 {
233 const output_data_t od = db->get_output_key(amount, offset);
234 const crypto::hash block_hash = db->get_block_hash_from_height(od.height);
235 bd = db->get_block_blob(block_hash);
236 cryptonote::block b;
237 if (!cryptonote::parse_and_validate_block_from_blob(bd, b))
238 {
239 LOG_PRINT_L0("Bad block from db");
240 return 1;
241 }
242 // find the tx which created this output
243 bool found = false;
244 for (size_t out = 0; out < b.miner_tx.vout.size(); ++out)
245 {
246 if (b.miner_tx.vout[out].target.type() == typeid(cryptonote::txout_to_key))
247 {
248 const auto &txout = boost::get<cryptonote::txout_to_key>(b.miner_tx.vout[out].target);
249 if (txout.key == od.pubkey)
250 {
251 found = true;
252 new_txids.push_back(cryptonote::get_transaction_hash(b.miner_tx));
253 MDEBUG("adding txid: " << cryptonote::get_transaction_hash(b.miner_tx));
254 break;
255 }
256 }
257 else
258 {
259 LOG_PRINT_L0("Bad vout type in txid " << cryptonote::get_transaction_hash(b.miner_tx));
260 return 1;
261 }
262 }
263 for (const crypto::hash &block_txid: b.tx_hashes)
264 {
265 if (found)
266 break;
267 if (!db->get_pruned_tx_blob(block_txid, bd))
268 {
269 LOG_PRINT_L0("Failed to get txid " << block_txid << " from db");
270 return 1;
271 }
272 cryptonote::transaction tx2;
273 if (!cryptonote::parse_and_validate_tx_base_from_blob(bd, tx2))
274 {
275 LOG_PRINT_L0("Bad tx: " << block_txid);
276 return 1;
277 }
278 for (size_t out = 0; out < tx2.vout.size(); ++out)
279 {
280 if (tx2.vout[out].target.type() == typeid(cryptonote::txout_to_key))
281 {
282 const auto &txout = boost::get<cryptonote::txout_to_key>(tx2.vout[out].target);
283 if (txout.key == od.pubkey)
284 {
285 found = true;
286 new_txids.push_back(block_txid);
287 MDEBUG("adding txid: " << block_txid);
288 break;
289 }
290 }
291 else
292 {
293 LOG_PRINT_L0("Bad vout type in txid " << block_txid);
294 return 1;
295 }
296 }
297 }
298 if (!found)
299 {
300 LOG_PRINT_L0("Output originating transaction not found");
301 return 1;
302 }
303 }
304 }
305 else
306 {
307 LOG_PRINT_L0("Bad vin type in txid " << txid);
308 return 1;
309 }
310 }
311 }
312 if (!coinbase)
313 {
314 std::swap(txids, new_txids);
315 ++depth;
316 }
317 }
318 done:
319 LOG_PRINT_L0("Min depth for txid " << start_txid << ": " << depth);
320 depths.push_back(depth);
321 }
322
323 uint64_t cumulative_depth = 0;
324 for (uint64_t depth: depths)
325 cumulative_depth += depth;
326 LOG_PRINT_L0("Average min depth for " << start_txids.size() << " transaction(s): " << cumulative_depth/(float)depths.size());
327 LOG_PRINT_L0("Median min depth for " << start_txids.size() << " transaction(s): " << epee::misc_utils::median(depths));
328
329 core_storage->deinit();
330 return 0;
331
332 CATCH_ENTRY("Depth query error", 1);
333 }