Debian Codegraph @

src/blockchain_utilities/bootstrap_file.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 "bootstrap_serialization.h"
30 #include "serialization/binary_utils.h" // dump_binary(), parse_binary()
31 #include "serialization/json_utils.h" // dump_json()
32
33 #include "bootstrap_file.h"
34
35 #undef MONERO_DEFAULT_LOG_CATEGORY
36 #define MONERO_DEFAULT_LOG_CATEGORY "bcutil"
37
38 namespace po = boost::program_options;
39
40 using namespace cryptonote;
41 using namespace epee;
42
43 namespace
44 {
45 // This number was picked by taking the leading 4 bytes from this output:
46 // echo Monero bootstrap file | sha1sum
47 const uint32_t blockchain_raw_magic = 0x28721586;
48 const uint32_t header_size = 1024;
49
50 std::string refresh_string = "\r \r";
51 }
52
53
54
55 bool BootstrapFile::open_writer(const boost::filesystem::path& file_path, uint64_t start_block, uint64_t stop_block)
56 {
57 const boost::filesystem::path dir_path = file_path.parent_path();
58 if (!dir_path.empty())
59 {
60 if (boost::filesystem::exists(dir_path))
61 {
62 if (!boost::filesystem::is_directory(dir_path))
63 {
64 MFATAL("export directory path is a file: " << dir_path);
65 return false;
66 }
67 }
68 else
69 {
70 if (!boost::filesystem::create_directory(dir_path))
71 {
72 MFATAL("Failed to create directory " << dir_path);
73 return false;
74 }
75 }
76 }
77
78 m_raw_data_file = new std::ofstream();
79
80 bool do_initialize_file = false;
81 uint64_t num_blocks = 0, block_first = 0;
82
83 if (! boost::filesystem::exists(file_path))
84 {
85 MDEBUG("creating file");
86 do_initialize_file = true;
87 num_blocks = 0;
88 }
89 else
90 {
91 std::streampos dummy_pos;
92 uint64_t dummy_height = 0;
93 num_blocks = count_blocks(file_path.string(), dummy_pos, dummy_height, block_first);
94 MDEBUG("appending to existing file with height: " << num_blocks+block_first-1 << " total blocks: " << num_blocks);
95 }
96 m_height = num_blocks+block_first;
97
98 if (do_initialize_file)
99 m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::trunc);
100 else
101 m_raw_data_file->open(file_path.string(), std::ios_base::binary | std::ios_base::out | std::ios::app | std::ios::ate);
102
103 if (m_raw_data_file->fail())
104 return false;
105
106 m_output_stream = new boost::iostreams::stream<boost::iostreams::back_insert_device<buffer_type>>(m_buffer);
107 if (m_output_stream == nullptr)
108 return false;
109
110 if (do_initialize_file)
111 initialize_file(start_block, stop_block);
112
113 return true;
114 }
115
116 bool BootstrapFile::initialize_file(uint64_t first_block, uint64_t last_block)
117 {
118 const uint32_t file_magic = blockchain_raw_magic;
119
120 std::string blob;
121 if (! ::serialization::dump_binary(file_magic, blob))
122 {
123 throw std::runtime_error("Error in serialization of file magic");
124 }
125 *m_raw_data_file << blob;
126
127 bootstrap::file_info bfi;
128 bfi.major_version = 1;
129 bfi.minor_version = 0;
130 bfi.header_size = header_size;
131
132 bootstrap::blocks_info bbi;
133 bbi.block_first = first_block;
134 bbi.block_last = last_block;
135 bbi.block_last_pos = 0;
136
137 buffer_type buffer2;
138 boost::iostreams::stream<boost::iostreams::back_insert_device<buffer_type>> output_stream_header(buffer2);
139
140 uint32_t bd_size = 0;
141
142 blobdata bd = t_serializable_object_to_blob(bfi);
143 MDEBUG("bootstrap::file_info size: " << bd.size());
144 bd_size = bd.size();
145
146 if (! ::serialization::dump_binary(bd_size, blob))
147 {
148 throw std::runtime_error("Error in serialization of bootstrap::file_info size");
149 }
150 output_stream_header << blob;
151 output_stream_header << bd;
152
153 bd = t_serializable_object_to_blob(bbi);
154 MDEBUG("bootstrap::blocks_info size: " << bd.size());
155 bd_size = bd.size();
156
157 if (! ::serialization::dump_binary(bd_size, blob))
158 {
159 throw std::runtime_error("Error in serialization of bootstrap::blocks_info size");
160 }
161 output_stream_header << blob;
162 output_stream_header << bd;
163
164 output_stream_header.flush();
165 output_stream_header << std::string(header_size-buffer2.size(), 0); // fill in rest with null bytes
166 output_stream_header.flush();
167 std::copy(buffer2.begin(), buffer2.end(), std::ostreambuf_iterator<char>(*m_raw_data_file));
168
169 return true;
170 }
171
172 void BootstrapFile::flush_chunk()
173 {
174 m_output_stream->flush();
175
176 uint32_t chunk_size = m_buffer.size();
177 // MTRACE("chunk_size " << chunk_size);
178 if (chunk_size > BUFFER_SIZE)
179 {
180 MWARNING("WARNING: chunk_size " << chunk_size << " > BUFFER_SIZE " << BUFFER_SIZE);
181 }
182
183 std::string blob;
184 if (! ::serialization::dump_binary(chunk_size, blob))
185 {
186 throw std::runtime_error("Error in serialization of chunk size");
187 }
188 *m_raw_data_file << blob;
189
190 if (m_max_chunk < chunk_size)
191 {
192 m_max_chunk = chunk_size;
193 }
194 long pos_before = m_raw_data_file->tellp();
195 std::copy(m_buffer.begin(), m_buffer.end(), std::ostreambuf_iterator<char>(*m_raw_data_file));
196 m_raw_data_file->flush();
197 long pos_after = m_raw_data_file->tellp();
198 long num_chars_written = pos_after - pos_before;
199 if (static_cast<unsigned long>(num_chars_written) != chunk_size)
200 {
201 MFATAL("Error writing chunk: height: " << m_cur_height << " chunk_size: " << chunk_size << " num chars written: " << num_chars_written);
202 throw std::runtime_error("Error writing chunk");
203 }
204
205 m_buffer.clear();
206 delete m_output_stream;
207 m_output_stream = new boost::iostreams::stream<boost::iostreams::back_insert_device<buffer_type>>(m_buffer);
208 MDEBUG("flushed chunk: chunk_size: " << chunk_size);
209 }
210
211 void BootstrapFile::write_block(block& block)
212 {
213 bootstrap::block_package bp;
214 bp.block = block;
215
216 std::vector<transaction> txs;
217
218 uint64_t block_height = boost::get<txin_gen>(block.miner_tx.vin.front()).height;
219
220
221 // now add all regular transactions
222 for (const auto& tx_id : block.tx_hashes)
223 {
224 if (tx_id == crypto::null_hash)
225 {
226 throw std::runtime_error("Aborting: tx == null_hash");
227 }
228 transaction tx = m_blockchain_storage->get_db().get_tx(tx_id);
229
230 txs.push_back(tx);
231 }
232
233 // these non-coinbase txs will be serialized using this structure
234 bp.txs = txs;
235
236 // These three attributes are currently necessary for a fast import that adds blocks without verification.
237 bool include_extra_block_data = true;
238 if (include_extra_block_data)
239 {
240 size_t block_weight = m_blockchain_storage->get_db().get_block_weight(block_height);
241 difficulty_type cumulative_difficulty = m_blockchain_storage->get_db().get_block_cumulative_difficulty(block_height);
242 uint64_t coins_generated = m_blockchain_storage->get_db().get_block_already_generated_coins(block_height);
243
244 bp.block_weight = block_weight;
245 bp.cumulative_difficulty = cumulative_difficulty;
246 bp.coins_generated = coins_generated;
247 }
248
249 blobdata bd = t_serializable_object_to_blob(bp);
250 m_output_stream->write((const char*)bd.data(), bd.size());
251 }
252
253 bool BootstrapFile::close()
254 {
255 if (m_raw_data_file->fail())
256 return false;
257
258 m_raw_data_file->flush();
259 delete m_output_stream;
260 delete m_raw_data_file;
261 return true;
262 }
263
264
265 bool BootstrapFile::store_blockchain_raw(Blockchain* _blockchain_storage, tx_memory_pool* _tx_pool, boost::filesystem::path& output_file, uint64_t start_block, uint64_t requested_block_stop)
266 {
267 uint64_t num_blocks_written = 0;
268 m_max_chunk = 0;
269 m_blockchain_storage = _blockchain_storage;
270 m_tx_pool = _tx_pool;
271 uint64_t progress_interval = 100;
272 MINFO("Storing blocks raw data...");
273 block b;
274
275 // block_start, block_stop use 0-based height. m_height uses 1-based height. So to resume export
276 // from last exported block, block_start doesn't need to add 1 here, as it's already at the next
277 // height.
278 uint64_t block_stop = 0;
279 MINFO("source blockchain height: " << m_blockchain_storage->get_current_blockchain_height()-1);
280 if ((requested_block_stop > 0) && (requested_block_stop < m_blockchain_storage->get_current_blockchain_height()))
281 {
282 MINFO("Using requested block height: " << requested_block_stop);
283 block_stop = requested_block_stop;
284 }
285 else
286 {
287 block_stop = m_blockchain_storage->get_current_blockchain_height() - 1;
288 MINFO("Using block height of source blockchain: " << block_stop);
289 }
290 if (!BootstrapFile::open_writer(output_file, start_block, block_stop))
291 {
292 MFATAL("failed to open raw file for write");
293 return false;
294 }
295 uint64_t block_start = m_height ? m_height : start_block;
296 MINFO("Starting block height: " << block_start);
297 for (m_cur_height = block_start; m_cur_height <= block_stop; ++m_cur_height)
298 {
299 // this method's height refers to 0-based height (genesis block = height 0)
300 crypto::hash hash = m_blockchain_storage->get_block_id_by_height(m_cur_height);
301 m_blockchain_storage->get_block_by_hash(hash, b);
302 write_block(b);
303 if (m_cur_height % NUM_BLOCKS_PER_CHUNK == 0) {
304 flush_chunk();
305 num_blocks_written += NUM_BLOCKS_PER_CHUNK;
306 }
307 if (m_cur_height % progress_interval == 0) {
308 std::cout << refresh_string;
309 std::cout << "block " << m_cur_height << "/" << block_stop << "\r" << std::flush;
310 }
311 }
312 // NOTE: use of NUM_BLOCKS_PER_CHUNK is a placeholder in case multi-block chunks are later supported.
313 if (m_cur_height % NUM_BLOCKS_PER_CHUNK != 0)
314 {
315 flush_chunk();
316 }
317 // print message for last block, which may not have been printed yet due to progress_interval
318 std::cout << refresh_string;
319 std::cout << "block " << m_cur_height-1 << "/" << block_stop << ENDL;
320
321 MINFO("Number of blocks exported: " << num_blocks_written);
322 if (num_blocks_written > 0)
323 MINFO("Largest chunk: " << m_max_chunk << " bytes");
324
325 return BootstrapFile::close();
326 }
327
328 uint64_t BootstrapFile::seek_to_first_chunk(std::ifstream& import_file, uint8_t &major_version, uint8_t &minor_version,
329 uint64_t &block_first, uint64_t &block_last)
330 {
331 uint32_t file_magic;
332
333 std::string str1;
334 char buf1[2048];
335 import_file.read(buf1, sizeof(file_magic));
336 if (! import_file)
337 throw std::runtime_error("Error reading expected number of bytes");
338 str1.assign(buf1, sizeof(file_magic));
339
340 if (! ::serialization::parse_binary(str1, file_magic))
341 throw std::runtime_error("Error in deserialization of file_magic");
342
343 if (file_magic != blockchain_raw_magic)
344 {
345 MFATAL("bootstrap file not recognized");
346 throw std::runtime_error("Aborting");
347 }
348 else
349 MINFO("bootstrap file recognized");
350
351 uint32_t buflen_file_info;
352
353 import_file.read(buf1, sizeof(buflen_file_info));
354 str1.assign(buf1, sizeof(buflen_file_info));
355 if (! import_file)
356 throw std::runtime_error("Error reading expected number of bytes");
357 if (! ::serialization::parse_binary(str1, buflen_file_info))
358 throw std::runtime_error("Error in deserialization of buflen_file_info");
359 MINFO("bootstrap::file_info size: " << buflen_file_info);
360
361 if (buflen_file_info > sizeof(buf1))
362 throw std::runtime_error("Error: bootstrap::file_info size exceeds buffer size");
363 import_file.read(buf1, buflen_file_info);
364 if (! import_file)
365 throw std::runtime_error("Error reading expected number of bytes");
366 str1.assign(buf1, buflen_file_info);
367 bootstrap::file_info bfi;
368 if (! ::serialization::parse_binary(str1, bfi))
369 throw std::runtime_error("Error in deserialization of bootstrap::file_info");
370 MINFO("bootstrap file v" << unsigned(bfi.major_version) << "." << unsigned(bfi.minor_version));
371 MINFO("bootstrap magic size: " << sizeof(file_magic));
372 MINFO("bootstrap header size: " << bfi.header_size);
373
374 uint32_t buflen_blocks_info;
375
376 import_file.read(buf1, sizeof(buflen_blocks_info));
377 str1.assign(buf1, sizeof(buflen_blocks_info));
378 if (! import_file)
379 throw std::runtime_error("Error reading expected number of bytes");
380 if (! ::serialization::parse_binary(str1, buflen_blocks_info))
381 throw std::runtime_error("Error in deserialization of buflen_blocks_info");
382 MINFO("bootstrap::blocks_info size: " << buflen_blocks_info);
383
384 if (buflen_blocks_info > sizeof(buf1))
385 throw std::runtime_error("Error: bootstrap::blocks_info size exceeds buffer size");
386 import_file.read(buf1, buflen_blocks_info);
387 if (! import_file)
388 throw std::runtime_error("Error reading expected number of bytes");
389 str1.assign(buf1, buflen_blocks_info);
390 bootstrap::blocks_info bbi;
391 if (! ::serialization::parse_binary(str1, bbi))
392 throw std::runtime_error("Error in deserialization of bootstrap::blocks_info");
393 MINFO("bootstrap first block:" << bbi.block_first);
394 MINFO("bootstrap last block:" << bbi.block_last);
395
396 uint64_t full_header_size = sizeof(file_magic) + bfi.header_size;
397 import_file.seekg(full_header_size);
398
399 major_version = bfi.major_version;
400 minor_version = bfi.minor_version;
401 block_first = bbi.block_first;
402 block_last = bbi.block_last;
403 return full_header_size;
404 }
405
406 uint64_t BootstrapFile::count_bytes(std::ifstream& import_file, uint64_t blocks, uint64_t& h, bool& quit)
407 {
408 uint64_t bytes_read = 0;
409 uint32_t chunk_size;
410 char buf1[sizeof(chunk_size)];
411 std::string str1;
412 h = 0;
413 while (1)
414 {
415 import_file.read(buf1, sizeof(chunk_size));
416 if (!import_file) {
417 std::cout << refresh_string;
418 MDEBUG("End of file reached");
419 quit = true;
420 break;
421 }
422 bytes_read += sizeof(chunk_size);
423 str1.assign(buf1, sizeof(chunk_size));
424 if (! ::serialization::parse_binary(str1, chunk_size))
425 throw std::runtime_error("Error in deserialization of chunk_size");
426 MDEBUG("chunk_size: " << chunk_size);
427
428 if (chunk_size > BUFFER_SIZE)
429 {
430 std::cout << refresh_string;
431 MWARNING("WARNING: chunk_size " << chunk_size << " > BUFFER_SIZE " << BUFFER_SIZE
432 << " height: " << h-1 << ", offset " << bytes_read);
433 throw std::runtime_error("Aborting: chunk size exceeds buffer size");
434 }
435 if (chunk_size > CHUNK_SIZE_WARNING_THRESHOLD)
436 {
437 std::cout << refresh_string;
438 MDEBUG("NOTE: chunk_size " << chunk_size << " > " << CHUNK_SIZE_WARNING_THRESHOLD << " << height: "
439 << h-1 << ", offset " << bytes_read);
440 }
441 else if (chunk_size <= 0) {
442 std::cout << refresh_string;
443 MDEBUG("ERROR: chunk_size " << chunk_size << " <= 0" << " height: " << h-1 << ", offset " << bytes_read);
444 throw std::runtime_error("Aborting");
445 }
446 // skip to next expected block size value
447 import_file.seekg(chunk_size, std::ios_base::cur);
448 if (! import_file) {
449 std::cout << refresh_string;
450 MFATAL("ERROR: unexpected end of file: bytes read before error: "
451 << import_file.gcount() << " of chunk_size " << chunk_size);
452 throw std::runtime_error("Aborting");
453 }
454 bytes_read += chunk_size;
455 h += NUM_BLOCKS_PER_CHUNK;
456 if (h >= blocks)
457 break;
458 }
459 return bytes_read;
460 }
461
462 uint64_t BootstrapFile::count_blocks(const std::string& import_file_path)
463 {
464 std::streampos dummy_pos;
465 uint64_t dummy_height = 0;
466 return count_blocks(import_file_path, dummy_pos, dummy_height, dummy_height);
467 }
468
469 // If seek_height is non-zero on entry, return a stream position <= this height when finished.
470 // And return the actual height corresponding to this position. Allows the caller to locate its
471 // starting position without having to reread the entire file again.
472 uint64_t BootstrapFile::count_blocks(const std::string& import_file_path, std::streampos &start_pos,
473 uint64_t& seek_height, uint64_t &block_first)
474 {
475 boost::filesystem::path raw_file_path(import_file_path);
476 boost::system::error_code ec;
477 if (!boost::filesystem::exists(raw_file_path, ec))
478 {
479 MFATAL("bootstrap file not found: " << raw_file_path);
480 throw std::runtime_error("Aborting");
481 }
482 std::ifstream import_file;
483 import_file.open(import_file_path, std::ios_base::binary | std::ifstream::in);
484
485 uint64_t start_height = seek_height;
486 uint64_t h = 0;
487 if (import_file.fail())
488 {
489 MFATAL("import_file.open() fail");
490 throw std::runtime_error("Aborting");
491 }
492
493 uint64_t full_header_size; // 4 byte magic + length of header structures
494 uint8_t major_version, minor_version;
495 uint64_t block_last;
496 full_header_size = seek_to_first_chunk(import_file, major_version, minor_version, block_first, block_last);
497
498 MINFO("Scanning blockchain from bootstrap file...");
499 bool quit = false;
500 uint64_t bytes_read = 0, blocks;
501 int progress_interval = 10;
502
503 while (! quit)
504 {
505 if (start_height && h + block_first + progress_interval >= start_height - 1)
506 {
507 start_height = 0;
508 start_pos = import_file.tellg();
509 seek_height = h + block_first;
510 }
511 bytes_read += count_bytes(import_file, progress_interval, blocks, quit);
512 h += blocks;
513 std::cout << "\r" << "block height: " << h-1 <<
514 " \r" <<
515 std::flush;
516
517 // std::cout << refresh_string;
518 MDEBUG("Number bytes scanned: " << bytes_read);
519 }
520
521 import_file.close();
522
523 std::cout << ENDL;
524 std::cout << "Done scanning bootstrap file" << ENDL;
525 std::cout << "Full header length: " << full_header_size << " bytes" << ENDL;
526 std::cout << "Scanned for blocks: " << bytes_read << " bytes" << ENDL;
527 std::cout << "Total: " << full_header_size + bytes_read << " bytes" << ENDL;
528 std::cout << "Number of blocks: " << h << ENDL;
529 std::cout << ENDL;
530
531 // NOTE: h is the number of blocks.
532 // Note that a block's stored height is zero-based, but parts of the code use
533 // one-based height.
534 return h;
535 }