Debian Codegraph @

src/blockchain_utilities/blockchain_prune_known_spent_data.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/algorithm/string.hpp>
30 #include <boost/filesystem.hpp>
31 #include "common/command_line.h"
32 #include "serialization/crypto.h"
33 #include "cryptonote_core/tx_pool.h"
34 #include "cryptonote_core/cryptonote_core.h"
35 #include "cryptonote_core/blockchain.h"
36 #include "blockchain_db/blockchain_db.h"
37 #include "version.h"
38
39 #undef MONERO_DEFAULT_LOG_CATEGORY
40 #define MONERO_DEFAULT_LOG_CATEGORY "bcutil"
41
42 namespace po = boost::program_options;
43 using namespace epee;
44 using namespace cryptonote;
45
46 static std::map<uint64_t, uint64_t> load_outputs(const std::string &filename)
47 {
48 std::map<uint64_t, uint64_t> outputs;
49 uint64_t amount = std::numeric_limits<uint64_t>::max();
50 FILE *f;
51
52 f = fopen(filename.c_str(), "r");
53 if (!f)
54 {
55 MERROR("Failed to load outputs from " << filename << ": " << strerror(errno));
56 return {};
57 }
58 while (1)
59 {
60 char s[256];
61 if (!fgets(s, sizeof(s), f))
62 break;
63 if (feof(f))
64 break;
65 const size_t len = strlen(s);
66 if (len > 0 && s[len - 1] == '\n')
67 s[len - 1] = 0;
68 if (!s[0])
69 continue;
70 uint64_t offset, num_offsets;
71 if (sscanf(s, "@%" PRIu64, &amount) == 1)
72 {
73 continue;
74 }
75 if (amount == std::numeric_limits<uint64_t>::max())
76 {
77 MERROR("Bad format in " << filename);
78 continue;
79 }
80 if (sscanf(s, "%" PRIu64 "*%" PRIu64, &offset, &num_offsets) == 2 && num_offsets < std::numeric_limits<uint64_t>::max() - offset)
81 {
82 outputs[amount] += num_offsets;
83 }
84 else if (sscanf(s, "%" PRIu64, &offset) == 1)
85 {
86 outputs[amount] += 1;
87 }
88 else
89 {
90 MERROR("Bad format in " << filename);
91 continue;
92 }
93 }
94 fclose(f);
95 return outputs;
96 }
97
98 int main(int argc, char* argv[])
99 {
100 TRY_ENTRY();
101
102 epee::string_tools::set_module_name_and_folder(argv[0]);
103
104 uint32_t log_level = 0;
105
106 tools::on_startup();
107
108 po::options_description desc_cmd_only("Command line options");
109 po::options_description desc_cmd_sett("Command line options and settings options");
110 const command_line::arg_descriptor<std::string> arg_log_level = {"log-level", "0-4 or categories", ""};
111 const command_line::arg_descriptor<bool> arg_verbose = {"verbose", "Verbose output", false};
112 const command_line::arg_descriptor<bool> arg_dry_run = {"dry-run", "Do not actually prune", false};
113 const command_line::arg_descriptor<std::string> arg_input = {"input", "Path to the known spent outputs file"};
114
115 command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir);
116 command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
117 command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
118 command_line::add_arg(desc_cmd_sett, cryptonote::arg_regtest_on);
119 command_line::add_arg(desc_cmd_sett, arg_log_level);
120 command_line::add_arg(desc_cmd_sett, arg_verbose);
121 command_line::add_arg(desc_cmd_sett, arg_dry_run);
122 command_line::add_arg(desc_cmd_sett, arg_input);
123 command_line::add_arg(desc_cmd_only, command_line::arg_help);
124
125 po::options_description desc_options("Allowed options");
126 desc_options.add(desc_cmd_only).add(desc_cmd_sett);
127
128 po::variables_map vm;
129 bool r = command_line::handle_error_helper(desc_options, [&]()
130 {
131 auto parser = po::command_line_parser(argc, argv).options(desc_options);
132 po::store(parser.run(), vm);
133 po::notify(vm);
134 return true;
135 });
136 if (! r)
137 return 1;
138
139 if (command_line::get_arg(vm, command_line::arg_help))
140 {
141 std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
142 std::cout << desc_options << std::endl;
143 return 1;
144 }
145
146 mlog_configure(mlog_get_default_log_path("monero-blockchain-prune-known-spent-data.log"), true);
147 if (!command_line::is_arg_defaulted(vm, arg_log_level))
148 mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
149 else
150 mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
151
152 LOG_PRINT_L0("Starting...");
153
154 std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
155 const network_type net_type = core::get_network_type_from_args(vm);
156 bool opt_verbose = command_line::get_arg(vm, arg_verbose);
157 bool opt_dry_run = command_line::get_arg(vm, arg_dry_run);
158
159 const std::string input = command_line::get_arg(vm, arg_input);
160
161 LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
162 std::unique_ptr<Blockchain> core_storage;
163 tx_memory_pool m_mempool(*core_storage);
164 core_storage.reset(new Blockchain(m_mempool));
165 BlockchainDB *db = new_db();
166 if (db == NULL)
167 {
168 LOG_ERROR("Failed to initialize a database");
169 throw std::runtime_error("Failed to initialize a database");
170 }
171
172 const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
173 LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
174
175 try
176 {
177 db->open(filename, 0);
178 }
179 catch (const std::exception& e)
180 {
181 LOG_PRINT_L0("Error opening database: " << e.what());
182 return 1;
183 }
184 r = core_storage->init(db, net_type);
185
186 CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
187 LOG_PRINT_L0("Source blockchain storage initialized OK");
188
189 std::map<uint64_t, uint64_t> known_spent_outputs;
190 if (input.empty())
191 {
192 std::map<uint64_t, std::pair<uint64_t, uint64_t>> outputs;
193
194 LOG_PRINT_L0("Scanning for known spent data...");
195 db->for_all_transactions([&](const crypto::hash &txid, const cryptonote::transaction &tx){
196 const bool miner_tx = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
197 for (const auto &in: tx.vin)
198 {
199 if (in.type() != typeid(txin_to_key))
200 continue;
201 const auto &txin = boost::get<txin_to_key>(in);
202 if (txin.amount == 0)
203 continue;
204
205 outputs[txin.amount].second++;
206 }
207
208 for (const auto &out: tx.vout)
209 {
210 uint64_t amount = out.amount;
211 if (miner_tx && tx.version >= 2)
212 amount = 0;
213 if (amount == 0)
214 continue;
215 if (out.target.type() != typeid(txout_to_key))
216 continue;
217
218 outputs[amount].first++;
219 }
220 return true;
221 }, true);
222
223 for (const auto &i: outputs)
224 {
225 known_spent_outputs[i.first] = i.second.second;
226 }
227 }
228 else
229 {
230 LOG_PRINT_L0("Loading known spent data...");
231 known_spent_outputs = load_outputs(input);
232 }
233
234 LOG_PRINT_L0("Pruning known spent data...");
235
236 bool stop_requested = false;
237 tools::signal_handler::install([&stop_requested](int type) {
238 stop_requested = true;
239 });
240
241 db->batch_start();
242
243 size_t num_total_outputs = 0, num_prunable_outputs = 0, num_known_spent_outputs = 0, num_eligible_outputs = 0, num_eligible_known_spent_outputs = 0;
244 for (auto i = known_spent_outputs.begin(); i != known_spent_outputs.end(); ++i)
245 {
246 uint64_t num_outputs = db->get_num_outputs(i->first);
247 num_total_outputs += num_outputs;
248 num_known_spent_outputs += i->second;
249 if (i->first == 0 || is_valid_decomposed_amount(i->first))
250 {
251 if (opt_verbose)
252 MINFO("Ignoring output value " << i->first << ", with " << num_outputs << " outputs");
253 continue;
254 }
255 num_eligible_outputs += num_outputs;
256 num_eligible_known_spent_outputs += i->second;
257 if (opt_verbose)
258 MINFO(i->first << ": " << i->second << "/" << num_outputs);
259 if (num_outputs > i->second)
260 continue;
261 if (num_outputs && num_outputs < i->second)
262 {
263 MERROR("More outputs are spent than known for amount " << i->first << ", not touching");
264 continue;
265 }
266 if (opt_verbose)
267 MINFO("Pruning data for " << num_outputs << " outputs");
268 if (!opt_dry_run)
269 db->prune_outputs(i->first);
270 num_prunable_outputs += i->second;
271 }
272
273 db->batch_stop();
274
275 MINFO("Total outputs: " << num_total_outputs);
276 MINFO("Known spent outputs: " << num_known_spent_outputs);
277 MINFO("Eligible outputs: " << num_eligible_outputs);
278 MINFO("Eligible known spent outputs: " << num_eligible_known_spent_outputs);
279 MINFO("Prunable outputs: " << num_prunable_outputs);
280
281 LOG_PRINT_L0("Blockchain known spent data pruned OK");
282 core_storage->deinit();
283 return 0;
284
285 CATCH_ENTRY("Error", 1);
286 }