Debian Codegraph @

monero/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, arg_log_level);
119 command_line::add_arg(desc_cmd_sett, arg_verbose);
120 command_line::add_arg(desc_cmd_sett, arg_dry_run);
121 command_line::add_arg(desc_cmd_sett, arg_input);
122 command_line::add_arg(desc_cmd_only, command_line::arg_help);
123
124 po::options_description desc_options("Allowed options");
125 desc_options.add(desc_cmd_only).add(desc_cmd_sett);
126
127 po::variables_map vm;
128 bool r = command_line::handle_error_helper(desc_options, [&]()
129 {
130 auto parser = po::command_line_parser(argc, argv).options(desc_options);
131 po::store(parser.run(), vm);
132 po::notify(vm);
133 return true;
134 });
135 if (! r)
136 return 1;
137
138 if (command_line::get_arg(vm, command_line::arg_help))
139 {
140 std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
141 std::cout << desc_options << std::endl;
142 return 1;
143 }
144
145 mlog_configure(mlog_get_default_log_path("monero-blockchain-prune-known-spent-data.log"), true);
146 if (!command_line::is_arg_defaulted(vm, arg_log_level))
147 mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
148 else
149 mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());
150
151 LOG_PRINT_L0("Starting...");
152
153 std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
154 bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
155 bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
156 network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
157 bool opt_verbose = command_line::get_arg(vm, arg_verbose);
158 bool opt_dry_run = command_line::get_arg(vm, arg_dry_run);
159
160 const std::string input = command_line::get_arg(vm, arg_input);
161
162 LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
163 std::unique_ptr<Blockchain> core_storage;
164 tx_memory_pool m_mempool(*core_storage);
165 core_storage.reset(new Blockchain(m_mempool));
166 BlockchainDB *db = new_db();
167 if (db == NULL)
168 {
169 LOG_ERROR("Failed to initialize a database");
170 throw std::runtime_error("Failed to initialize a database");
171 }
172
173 const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
174 LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");
175
176 try
177 {
178 db->open(filename, 0);
179 }
180 catch (const std::exception& e)
181 {
182 LOG_PRINT_L0("Error opening database: " << e.what());
183 return 1;
184 }
185 r = core_storage->init(db, net_type);
186
187 CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
188 LOG_PRINT_L0("Source blockchain storage initialized OK");
189
190 std::map<uint64_t, uint64_t> known_spent_outputs;
191 if (input.empty())
192 {
193 std::map<uint64_t, std::pair<uint64_t, uint64_t>> outputs;
194
195 LOG_PRINT_L0("Scanning for known spent data...");
196 db->for_all_transactions([&](const crypto::hash &txid, const cryptonote::transaction &tx){
197 const bool miner_tx = tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
198 for (const auto &in: tx.vin)
199 {
200 if (in.type() != typeid(txin_to_key))
201 continue;
202 const auto &txin = boost::get<txin_to_key>(in);
203 if (txin.amount == 0)
204 continue;
205
206 outputs[txin.amount].second++;
207 }
208
209 for (const auto &out: tx.vout)
210 {
211 uint64_t amount = out.amount;
212 if (miner_tx && tx.version >= 2)
213 amount = 0;
214 if (amount == 0)
215 continue;
216 if (out.target.type() != typeid(txout_to_key))
217 continue;
218
219 outputs[amount].first++;
220 }
221 return true;
222 }, true);
223
224 for (const auto &i: outputs)
225 {
226 known_spent_outputs[i.first] = i.second.second;
227 }
228 }
229 else
230 {
231 LOG_PRINT_L0("Loading known spent data...");
232 known_spent_outputs = load_outputs(input);
233 }
234
235 LOG_PRINT_L0("Pruning known spent data...");
236
237 bool stop_requested = false;
238 tools::signal_handler::install([&stop_requested](int type) {
239 stop_requested = true;
240 });
241
242 db->batch_start();
243
244 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;
245 for (auto i = known_spent_outputs.begin(); i != known_spent_outputs.end(); ++i)
246 {
247 uint64_t num_outputs = db->get_num_outputs(i->first);
248 num_total_outputs += num_outputs;
249 num_known_spent_outputs += i->second;
250 if (i->first == 0 || is_valid_decomposed_amount(i->first))
251 {
252 if (opt_verbose)
253 MINFO("Ignoring output value " << i->first << ", with " << num_outputs << " outputs");
254 continue;
255 }
256 num_eligible_outputs += num_outputs;
257 num_eligible_known_spent_outputs += i->second;
258 if (opt_verbose)
259 MINFO(i->first << ": " << i->second << "/" << num_outputs);
260 if (num_outputs > i->second)
261 continue;
262 if (num_outputs && num_outputs < i->second)
263 {
264 MERROR("More outputs are spent than known for amount " << i->first << ", not touching");
265 continue;
266 }
267 if (opt_verbose)
268 MINFO("Pruning data for " << num_outputs << " outputs");
269 if (!opt_dry_run)
270 db->prune_outputs(i->first);
271 num_prunable_outputs += i->second;
272 }
273
274 db->batch_stop();
275
276 MINFO("Total outputs: " << num_total_outputs);
277 MINFO("Known spent outputs: " << num_known_spent_outputs);
278 MINFO("Eligible outputs: " << num_eligible_outputs);
279 MINFO("Eligible known spent outputs: " << num_eligible_known_spent_outputs);
280 MINFO("Prunable outputs: " << num_prunable_outputs);
281
282 LOG_PRINT_L0("Blockchain known spent data pruned OK");
283 core_storage->deinit();
284 return 0;
285
286 CATCH_ENTRY("Error", 1);
287 }