Debian Codegraph @

src/blockchain_db/lmdb/db_lmdb.cpp

raw symbols SCIP
1 // Copyright (c) 2014-2022, The Monero Project
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without modification, are
5 // permitted provided that the following conditions are met:
6 //
7 // 1. Redistributions of source code must retain the above copyright notice, this list of
8 // conditions and the following disclaimer.
9 //
10 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
11 // of conditions and the following disclaimer in the documentation and/or other
12 // materials provided with the distribution.
13 //
14 // 3. Neither the name of the copyright holder nor the names of its contributors may be
15 // used to endorse or promote products derived from this software without specific
16 // prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
19 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
26 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 #include "db_lmdb.h"
29
30 #include <boost/filesystem.hpp>
31 #include <boost/filesystem/fstream.hpp>
32 #include <boost/format.hpp>
33 #include <boost/circular_buffer.hpp>
34 #include <memory> // std::unique_ptr
35 #include <cstring> // memcpy
36
37 #ifdef WIN32
38 #include <winioctl.h>
39 #endif
40
41 #include "string_tools.h"
42 #include "common/util.h"
43 #include "common/pruning.h"
44 #include "cryptonote_basic/cryptonote_format_utils.h"
45 #include "crypto/crypto.h"
46 #include "profile_tools.h"
47 #include "ringct/rctOps.h"
48
49 #undef MONERO_DEFAULT_LOG_CATEGORY
50 #define MONERO_DEFAULT_LOG_CATEGORY "blockchain.db.lmdb"
51
52
53 #if defined(__i386) || defined(__x86_64)
54 #define MISALIGNED_OK 1
55 #endif
56
57 using epee::string_tools::pod_to_hex;
58 using namespace crypto;
59
60 // Increase when the DB structure changes
61 #define VERSION 5
62
63 namespace
64 {
65
66 #pragma pack(push, 1)
67 // This MUST be identical to output_data_t, without the extra rct data at the end
68 struct pre_rct_output_data_t
69 {
70 crypto::public_key pubkey; //!< the output's public key (for spend verification)
71 uint64_t unlock_time; //!< the output's unlock time (or height)
72 uint64_t height; //!< the height of the block which created the output
73 };
74 #pragma pack(pop)
75
76 template <typename T>
77 inline void throw0(const T &e)
78 {
79 LOG_PRINT_L0(e.what());
80 throw e;
81 }
82
83 template <typename T>
84 inline void throw1(const T &e)
85 {
86 LOG_PRINT_L1(e.what());
87 throw e;
88 }
89
90 #define MDB_val_set(var, val) MDB_val var = {sizeof(val), (void *)&val}
91
92 #define MDB_val_sized(var, val) MDB_val var = {val.size(), (void *)val.data()}
93
94 #define MDB_val_str(var, val) MDB_val var = {strlen(val) + 1, (void *)val}
95
96 template<typename T>
97 struct MDB_val_copy: public MDB_val
98 {
99 MDB_val_copy(const T &t) :
100 t_copy(t)
101 {
102 mv_size = sizeof (T);
103 mv_data = &t_copy;
104 }
105 private:
106 T t_copy;
107 };
108
109 template<>
110 struct MDB_val_copy<cryptonote::blobdata>: public MDB_val
111 {
112 MDB_val_copy(const cryptonote::blobdata &bd) :
113 data(new char[bd.size()])
114 {
115 memcpy(data.get(), bd.data(), bd.size());
116 mv_size = bd.size();
117 mv_data = data.get();
118 }
119 private:
120 std::unique_ptr<char[]> data;
121 };
122
123 template<>
124 struct MDB_val_copy<const char*>: public MDB_val
125 {
126 MDB_val_copy(const char *s):
127 size(strlen(s)+1), // include the NUL, makes it easier for compares
128 data(new char[size])
129 {
130 mv_size = size;
131 mv_data = data.get();
132 memcpy(mv_data, s, size);
133 }
134 private:
135 size_t size;
136 std::unique_ptr<char[]> data;
137 };
138
139 }
140
141 namespace cryptonote
142 {
143
144 int BlockchainLMDB::compare_uint64(const MDB_val *a, const MDB_val *b)
145 {
146 uint64_t va, vb;
147 memcpy(&va, a->mv_data, sizeof(va));
148 memcpy(&vb, b->mv_data, sizeof(vb));
149 return (va < vb) ? -1 : va > vb;
150 }
151
152 int BlockchainLMDB::compare_hash32(const MDB_val *a, const MDB_val *b)
153 {
154 uint32_t *va = (uint32_t*) a->mv_data;
155 uint32_t *vb = (uint32_t*) b->mv_data;
156 for (int n = 7; n >= 0; n--)
157 {
158 if (va[n] == vb[n])
159 continue;
160 return va[n] < vb[n] ? -1 : 1;
161 }
162
163 return 0;
164 }
165
166 int BlockchainLMDB::compare_string(const MDB_val *a, const MDB_val *b)
167 {
168 const char *va = (const char*) a->mv_data;
169 const char *vb = (const char*) b->mv_data;
170 const size_t sz = std::min(a->mv_size, b->mv_size);
171 int ret = strncmp(va, vb, sz);
172 if (ret)
173 return ret;
174 if (a->mv_size < b->mv_size)
175 return -1;
176 if (a->mv_size > b->mv_size)
177 return 1;
178 return 0;
179 }
180
181 }
182
183 namespace
184 {
185
186 /* DB schema:
187 *
188 * Table Key Data
189 * ----- --- ----
190 * blocks block ID block blob
191 * block_heights block hash block height
192 * block_info block ID {block metadata}
193 *
194 * txs_pruned txn ID pruned txn blob
195 * txs_prunable txn ID prunable txn blob
196 * txs_prunable_hash txn ID prunable txn hash
197 * txs_prunable_tip txn ID height
198 * tx_indices txn hash {txn ID, metadata}
199 * tx_outputs txn ID [txn amount output indices]
200 *
201 * output_txs output ID {txn hash, local index}
202 * output_amounts amount [{amount output index, metadata}...]
203 *
204 * spent_keys input hash -
205 *
206 * txpool_meta txn hash txn metadata
207 * txpool_blob txn hash txn blob
208 *
209 * alt_blocks block hash {block data, block blob}
210 *
211 * Note: where the data items are of uniform size, DUPFIXED tables have
212 * been used to save space. In most of these cases, a dummy "zerokval"
213 * key is used when accessing the table; the Key listed above will be
214 * attached as a prefix on the Data to serve as the DUPSORT key.
215 * (DUPFIXED saves 8 bytes per record.)
216 *
217 * The output_amounts table doesn't use a dummy key, but uses DUPSORT.
218 */
219 const char* const LMDB_BLOCKS = "blocks";
220 const char* const LMDB_BLOCK_HEIGHTS = "block_heights";
221 const char* const LMDB_BLOCK_INFO = "block_info";
222
223 const char* const LMDB_TXS = "txs";
224 const char* const LMDB_TXS_PRUNED = "txs_pruned";
225 const char* const LMDB_TXS_PRUNABLE = "txs_prunable";
226 const char* const LMDB_TXS_PRUNABLE_HASH = "txs_prunable_hash";
227 const char* const LMDB_TXS_PRUNABLE_TIP = "txs_prunable_tip";
228 const char* const LMDB_TX_INDICES = "tx_indices";
229 const char* const LMDB_TX_OUTPUTS = "tx_outputs";
230
231 const char* const LMDB_OUTPUT_TXS = "output_txs";
232 const char* const LMDB_OUTPUT_AMOUNTS = "output_amounts";
233 const char* const LMDB_SPENT_KEYS = "spent_keys";
234
235 const char* const LMDB_TXPOOL_META = "txpool_meta";
236 const char* const LMDB_TXPOOL_BLOB = "txpool_blob";
237
238 const char* const LMDB_ALT_BLOCKS = "alt_blocks";
239
240 const char* const LMDB_HF_STARTING_HEIGHTS = "hf_starting_heights";
241 const char* const LMDB_HF_VERSIONS = "hf_versions";
242
243 const char* const LMDB_PROPERTIES = "properties";
244
245 const char zerokey[8] = {0};
246 const MDB_val zerokval = { sizeof(zerokey), (void *)zerokey };
247
248 const std::string lmdb_error(const std::string& error_string, int mdb_res)
249 {
250 const std::string full_string = error_string + mdb_strerror(mdb_res);
251 return full_string;
252 }
253
254 inline void lmdb_db_open(MDB_txn* txn, const char* name, int flags, MDB_dbi& dbi, const std::string& error_string)
255 {
256 if (auto res = mdb_dbi_open(txn, name, flags, &dbi))
257 throw0(cryptonote::DB_OPEN_FAILURE((lmdb_error(error_string + " : ", res) + std::string(" - you may want to start with --db-salvage")).c_str()));
258 }
259
260
261 } // anonymous namespace
262
263 #define CURSOR(name) \
264 if (!m_cur_ ## name) { \
265 int result = mdb_cursor_open(*m_write_txn, m_ ## name, &m_cur_ ## name); \
266 if (result) \
267 throw0(DB_ERROR(lmdb_error("Failed to open cursor: ", result).c_str())); \
268 }
269
270 #define RCURSOR(name) \
271 if (!m_cur_ ## name) { \
272 int result = mdb_cursor_open(m_txn, m_ ## name, (MDB_cursor **)&m_cur_ ## name); \
273 if (result) \
274 throw0(DB_ERROR(lmdb_error("Failed to open cursor: ", result).c_str())); \
275 if (m_cursors != &m_wcursors) \
276 m_tinfo->m_ti_rflags.m_rf_ ## name = true; \
277 } else if (m_cursors != &m_wcursors && !m_tinfo->m_ti_rflags.m_rf_ ## name) { \
278 int result = mdb_cursor_renew(m_txn, m_cur_ ## name); \
279 if (result) \
280 throw0(DB_ERROR(lmdb_error("Failed to renew cursor: ", result).c_str())); \
281 m_tinfo->m_ti_rflags.m_rf_ ## name = true; \
282 }
283
284 namespace cryptonote
285 {
286
287 typedef struct mdb_block_info_1
288 {
289 uint64_t bi_height;
290 uint64_t bi_timestamp;
291 uint64_t bi_coins;
292 uint64_t bi_weight; // a size_t really but we need 32-bit compat
293 uint64_t bi_diff;
294 crypto::hash bi_hash;
295 } mdb_block_info_1;
296
297 typedef struct mdb_block_info_2
298 {
299 uint64_t bi_height;
300 uint64_t bi_timestamp;
301 uint64_t bi_coins;
302 uint64_t bi_weight; // a size_t really but we need 32-bit compat
303 uint64_t bi_diff;
304 crypto::hash bi_hash;
305 uint64_t bi_cum_rct;
306 } mdb_block_info_2;
307
308 typedef struct mdb_block_info_3
309 {
310 uint64_t bi_height;
311 uint64_t bi_timestamp;
312 uint64_t bi_coins;
313 uint64_t bi_weight; // a size_t really but we need 32-bit compat
314 uint64_t bi_diff;
315 crypto::hash bi_hash;
316 uint64_t bi_cum_rct;
317 uint64_t bi_long_term_block_weight;
318 } mdb_block_info_3;
319
320 typedef struct mdb_block_info_4
321 {
322 uint64_t bi_height;
323 uint64_t bi_timestamp;
324 uint64_t bi_coins;
325 uint64_t bi_weight; // a size_t really but we need 32-bit compat
326 uint64_t bi_diff_lo;
327 uint64_t bi_diff_hi;
328 crypto::hash bi_hash;
329 uint64_t bi_cum_rct;
330 uint64_t bi_long_term_block_weight;
331 } mdb_block_info_4;
332
333 typedef mdb_block_info_4 mdb_block_info;
334
335 typedef struct blk_height {
336 crypto::hash bh_hash;
337 uint64_t bh_height;
338 } blk_height;
339
340 typedef struct pre_rct_outkey {
341 uint64_t amount_index;
342 uint64_t output_id;
343 pre_rct_output_data_t data;
344 } pre_rct_outkey;
345
346 typedef struct outkey {
347 uint64_t amount_index;
348 uint64_t output_id;
349 output_data_t data;
350 } outkey;
351
352 typedef struct outtx {
353 uint64_t output_id;
354 crypto::hash tx_hash;
355 uint64_t local_index;
356 } outtx;
357
358 std::atomic<uint64_t> mdb_txn_safe::num_active_txns{0};
359 std::atomic_flag mdb_txn_safe::creation_gate = ATOMIC_FLAG_INIT;
360
361 mdb_threadinfo::~mdb_threadinfo()
362 {
363 MDB_cursor **cur = &m_ti_rcursors.m_txc_blocks;
364 unsigned i;
365 for (i=0; i<sizeof(mdb_txn_cursors)/sizeof(MDB_cursor *); i++)
366 if (cur[i])
367 mdb_cursor_close(cur[i]);
368 if (m_ti_rtxn)
369 mdb_txn_abort(m_ti_rtxn);
370 }
371
372 mdb_txn_safe::mdb_txn_safe(const bool check) : m_txn(NULL), m_tinfo(NULL), m_check(check)
373 {
374 if (check)
375 {
376 while (creation_gate.test_and_set());
377 num_active_txns++;
378 creation_gate.clear();
379 }
380 }
381
382 mdb_txn_safe::~mdb_txn_safe()
383 {
384 if (!m_check)
385 return;
386 LOG_PRINT_L3("mdb_txn_safe: destructor");
387 if (m_tinfo != nullptr)
388 {
389 mdb_txn_reset(m_tinfo->m_ti_rtxn);
390 memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
391 } else if (m_txn != nullptr)
392 {
393 if (m_batch_txn) // this is a batch txn and should have been handled before this point for safety
394 {
395 LOG_PRINT_L0("WARNING: mdb_txn_safe: m_txn is a batch txn and it's not NULL in destructor - calling mdb_txn_abort()");
396 }
397 else
398 {
399 // Example of when this occurs: a lookup fails, so a read-only txn is
400 // aborted through this destructor. However, successful read-only txns
401 // ideally should have been committed when done and not end up here.
402 //
403 // NOTE: not sure if this is ever reached for a non-batch write
404 // transaction, but it's probably not ideal if it did.
405 LOG_PRINT_L3("mdb_txn_safe: m_txn not NULL in destructor - calling mdb_txn_abort()");
406 }
407 mdb_txn_abort(m_txn);
408 }
409 num_active_txns--;
410 }
411
412 void mdb_txn_safe::uncheck()
413 {
414 num_active_txns--;
415 m_check = false;
416 }
417
418 void mdb_txn_safe::commit(std::string message)
419 {
420 if (message.size() == 0)
421 {
422 message = "Failed to commit a transaction to the db";
423 }
424
425 if (auto result = mdb_txn_commit(m_txn))
426 {
427 m_txn = nullptr;
428 throw0(DB_ERROR(lmdb_error(message + ": ", result).c_str()));
429 }
430 m_txn = nullptr;
431 }
432
433 void mdb_txn_safe::abort()
434 {
435 LOG_PRINT_L3("mdb_txn_safe: abort()");
436 if(m_txn != nullptr)
437 {
438 mdb_txn_abort(m_txn);
439 m_txn = nullptr;
440 }
441 else
442 {
443 LOG_PRINT_L0("WARNING: mdb_txn_safe: abort() called, but m_txn is NULL");
444 }
445 }
446
447 uint64_t mdb_txn_safe::num_active_tx() const
448 {
449 return num_active_txns;
450 }
451
452 void mdb_txn_safe::prevent_new_txns()
453 {
454 while (creation_gate.test_and_set());
455 }
456
457 void mdb_txn_safe::wait_no_active_txns()
458 {
459 while (num_active_txns > 0);
460 }
461
462 void mdb_txn_safe::allow_new_txns()
463 {
464 creation_gate.clear();
465 }
466
467 void mdb_txn_safe::increment_txns(int i)
468 {
469 num_active_txns += i;
470 }
471
472 #define TXN_PREFIX(flags); \
473 mdb_txn_safe auto_txn; \
474 mdb_txn_safe* txn_ptr = &auto_txn; \
475 if (m_batch_active) \
476 txn_ptr = m_write_txn; \
477 else \
478 { \
479 if (auto mdb_res = lmdb_txn_begin(m_env, NULL, flags, auto_txn)) \
480 throw0(DB_ERROR(lmdb_error(std::string("Failed to create a transaction for the db in ")+__FUNCTION__+": ", mdb_res).c_str())); \
481 } \
482
483 #define TXN_PREFIX_RDONLY() \
484 MDB_txn *m_txn; \
485 mdb_txn_cursors *m_cursors; \
486 mdb_txn_safe auto_txn; \
487 bool my_rtxn = block_rtxn_start(&m_txn, &m_cursors); \
488 if (my_rtxn) auto_txn.m_tinfo = m_tinfo.get(); \
489 else auto_txn.uncheck()
490 #define TXN_POSTFIX_RDONLY()
491
492 #define TXN_POSTFIX_SUCCESS() \
493 do { \
494 if (! m_batch_active) \
495 auto_txn.commit(); \
496 } while(0)
497
498 void lmdb_resized(MDB_env *env, int isactive)
499 {
500 mdb_txn_safe::prevent_new_txns();
501
502 MGINFO("LMDB map resize detected.");
503
504 MDB_envinfo mei;
505
506 mdb_env_info(env, &mei);
507 uint64_t old = mei.me_mapsize;
508
509 if (isactive)
510 mdb_txn_safe::increment_txns(-1);
511 mdb_txn_safe::wait_no_active_txns();
512 if (isactive)
513 mdb_txn_safe::increment_txns(1);
514
515 int result = mdb_env_set_mapsize(env, 0);
516 if (result)
517 throw0(DB_ERROR(lmdb_error("Failed to set new mapsize: ", result).c_str()));
518
519 mdb_env_info(env, &mei);
520 uint64_t new_mapsize = mei.me_mapsize;
521
522 MGINFO("LMDB Mapsize increased." << " Old: " << old / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB");
523
524 mdb_txn_safe::allow_new_txns();
525 }
526
527 inline int lmdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn)
528 {
529 int res = mdb_txn_begin(env, parent, flags, txn);
530 if (res == MDB_MAP_RESIZED) {
531 lmdb_resized(env, 1);
532 res = mdb_txn_begin(env, parent, flags, txn);
533 }
534 return res;
535 }
536
537 inline int lmdb_txn_renew(MDB_txn *txn)
538 {
539 int res = mdb_txn_renew(txn);
540 if (res == MDB_MAP_RESIZED) {
541 lmdb_resized(mdb_txn_env(txn), 0);
542 res = mdb_txn_renew(txn);
543 }
544 return res;
545 }
546
547 inline void BlockchainLMDB::check_open() const
548 {
549 if (!m_open)
550 throw0(DB_ERROR("DB operation attempted on a not-open DB instance"));
551 }
552
553 void BlockchainLMDB::do_resize(uint64_t increase_size)
554 {
555 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
556 CRITICAL_REGION_LOCAL(m_synchronization_lock);
557 const uint64_t add_size = 1LL << 30;
558
559 // check disk capacity
560 try
561 {
562 boost::filesystem::path path(m_folder);
563 boost::filesystem::space_info si = boost::filesystem::space(path);
564 if(si.available < add_size)
565 {
566 MERROR("!! WARNING: Insufficient free space to extend database !!: " <<
567 (si.available >> 20L) << " MB available, " << (add_size >> 20L) << " MB needed");
568 return;
569 }
570 }
571 catch(...)
572 {
573 // print something but proceed.
574 MWARNING("Unable to query free disk space.");
575 }
576
577 MDB_envinfo mei;
578
579 mdb_env_info(m_env, &mei);
580
581 MDB_stat mst;
582
583 mdb_env_stat(m_env, &mst);
584
585 // add 1Gb per resize, instead of doing a percentage increase
586 uint64_t new_mapsize = (uint64_t) mei.me_mapsize + add_size;
587
588 // If given, use increase_size instead of above way of resizing.
589 // This is currently used for increasing by an estimated size at start of new
590 // batch txn.
591 if (increase_size > 0)
592 new_mapsize = mei.me_mapsize + increase_size;
593
594 new_mapsize += (new_mapsize % mst.ms_psize);
595
596 mdb_txn_safe::prevent_new_txns();
597
598 if (m_write_txn != nullptr)
599 {
600 if (m_batch_active)
601 {
602 throw0(DB_ERROR("lmdb resizing not yet supported when batch transactions enabled!"));
603 }
604 else
605 {
606 throw0(DB_ERROR("attempting resize with write transaction in progress, this should not happen!"));
607 }
608 }
609
610 mdb_txn_safe::wait_no_active_txns();
611
612 int result = mdb_env_set_mapsize(m_env, new_mapsize);
613 if (result)
614 throw0(DB_ERROR(lmdb_error("Failed to set new mapsize: ", result).c_str()));
615
616 MGINFO("LMDB Mapsize increased." << " Old: " << mei.me_mapsize / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB");
617
618 mdb_txn_safe::allow_new_txns();
619 }
620
621 // threshold_size is used for batch transactions
622 bool BlockchainLMDB::need_resize(uint64_t threshold_size) const
623 {
624 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
625 #if defined(ENABLE_AUTO_RESIZE)
626 MDB_envinfo mei;
627
628 mdb_env_info(m_env, &mei);
629
630 MDB_stat mst;
631
632 mdb_env_stat(m_env, &mst);
633
634 // size_used doesn't include data yet to be committed, which can be
635 // significant size during batch transactions. For that, we estimate the size
636 // needed at the beginning of the batch transaction and pass in the
637 // additional size needed.
638 uint64_t size_used = mst.ms_psize * mei.me_last_pgno;
639
640 MDEBUG("DB map size: " << mei.me_mapsize);
641 MDEBUG("Space used: " << size_used);
642 MDEBUG("Space remaining: " << mei.me_mapsize - size_used);
643 MDEBUG("Size threshold: " << threshold_size);
644 float resize_percent = RESIZE_PERCENT;
645 MDEBUG(boost::format("Percent used: %.04f Percent threshold: %.04f") % (100.*size_used/mei.me_mapsize) % (100.*resize_percent));
646
647 if (threshold_size > 0)
648 {
649 if (mei.me_mapsize - size_used < threshold_size)
650 {
651 MINFO("Threshold met (size-based)");
652 return true;
653 }
654 else
655 return false;
656 }
657
658 if ((double)size_used / mei.me_mapsize > resize_percent)
659 {
660 MINFO("Threshold met (percent-based)");
661 return true;
662 }
663 return false;
664 #else
665 return false;
666 #endif
667 }
668
669 void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint64_t batch_bytes)
670 {
671 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
672 MTRACE("[" << __func__ << "] " << "checking DB size");
673 const uint64_t min_increase_size = 512 * (1 << 20);
674 uint64_t threshold_size = 0;
675 uint64_t increase_size = 0;
676 if (batch_num_blocks > 0)
677 {
678 threshold_size = get_estimated_batch_size(batch_num_blocks, batch_bytes);
679 MDEBUG("calculated batch size: " << threshold_size);
680
681 // The increased DB size could be a multiple of threshold_size, a fixed
682 // size increase (> threshold_size), or other variations.
683 //
684 // Currently we use the greater of threshold size and a minimum size. The
685 // minimum size increase is used to avoid frequent resizes when the batch
686 // size is set to a very small numbers of blocks.
687 increase_size = (threshold_size > min_increase_size) ? threshold_size : min_increase_size;
688 MDEBUG("increase size: " << increase_size);
689 }
690
691 // if threshold_size is 0 (i.e. number of blocks for batch not passed in), it
692 // will fall back to the percent-based threshold check instead of the
693 // size-based check
694 if (need_resize(threshold_size))
695 {
696 MGINFO("[batch] DB resize needed");
697 do_resize(increase_size);
698 }
699 }
700
701 uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uint64_t batch_bytes) const
702 {
703 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
704 uint64_t threshold_size = 0;
705
706 // batch size estimate * batch safety factor = final size estimate
707 // Takes into account "reasonable" block size increases in batch.
708 float batch_safety_factor = 1.7f;
709 float batch_fudge_factor = batch_safety_factor * batch_num_blocks;
710 // estimate of stored block expanded from raw block, including denormalization and db overhead.
711 // Note that this probably doesn't grow linearly with block size.
712 float db_expand_factor = 4.5f;
713 uint64_t num_prev_blocks = 500;
714 // For resizing purposes, allow for at least 4k average block size.
715 uint64_t min_block_size = 4 * 1024;
716
717 uint64_t block_stop = 0;
718 uint64_t m_height = height();
719 if (m_height > 1)
720 block_stop = m_height - 1;
721 uint64_t block_start = 0;
722 if (block_stop >= num_prev_blocks)
723 block_start = block_stop - num_prev_blocks + 1;
724 uint32_t num_blocks_used = 0;
725 uint64_t total_block_size = 0;
726 MDEBUG("[" << __func__ << "] " << "m_height: " << m_height << " block_start: " << block_start << " block_stop: " << block_stop);
727 size_t avg_block_size = 0;
728 if (batch_bytes)
729 {
730 avg_block_size = batch_bytes / batch_num_blocks;
731 goto estim;
732 }
733 if (m_height == 0)
734 {
735 MDEBUG("No existing blocks to check for average block size");
736 }
737 else if (m_cum_count >= num_prev_blocks)
738 {
739 avg_block_size = m_cum_size / m_cum_count;
740 MDEBUG("average block size across recent " << m_cum_count << " blocks: " << avg_block_size);
741 m_cum_size = 0;
742 m_cum_count = 0;
743 }
744 else
745 {
746 {
747 TXN_PREFIX_RDONLY();
748 for (uint64_t block_num = block_start; block_num <= block_stop; ++block_num)
749 {
750 // we have access to block weight, which will be greater or equal to block size,
751 // so use this as a proxy. If it's too much off, we might have to check actual size,
752 // which involves reading more data, so is not really wanted
753 size_t block_weight = get_block_weight(block_num);
754 total_block_size += block_weight;
755 // Track number of blocks being totalled here instead of assuming, in case
756 // some blocks were to be skipped for being outliers.
757 ++num_blocks_used;
758 }
759 }
760 avg_block_size = total_block_size / (num_blocks_used ? num_blocks_used : 1);
761 MDEBUG("average block size across recent " << num_blocks_used << " blocks: " << avg_block_size);
762 }
763 estim:
764 if (avg_block_size < min_block_size)
765 avg_block_size = min_block_size;
766 MDEBUG("estimated average block size for batch: " << avg_block_size);
767
768 // bigger safety margin on smaller block sizes
769 if (batch_fudge_factor < 5000.0)
770 batch_fudge_factor = 5000.0;
771 threshold_size = avg_block_size * db_expand_factor * batch_fudge_factor;
772 return threshold_size;
773 }
774
775 void BlockchainLMDB::add_block(const block& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated,
776 uint64_t num_rct_outs, const crypto::hash& blk_hash)
777 {
778 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
779 check_open();
780 mdb_txn_cursors *m_cursors = &m_wcursors;
781 uint64_t m_height = height();
782
783 CURSOR(block_heights)
784 blk_height bh = {blk_hash, m_height};
785 MDB_val_set(val_h, bh);
786 if (mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &val_h, MDB_GET_BOTH) == 0)
787 throw1(BLOCK_EXISTS("Attempting to add block that's already in the db"));
788
789 if (m_height > 0)
790 {
791 MDB_val_set(parent_key, blk.prev_id);
792 int result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &parent_key, MDB_GET_BOTH);
793 if (result)
794 {
795 LOG_PRINT_L3("m_height: " << m_height);
796 LOG_PRINT_L3("parent_key: " << blk.prev_id);
797 throw0(DB_ERROR(lmdb_error("Failed to get top block hash to check for new block's parent: ", result).c_str()));
798 }
799 blk_height *prev = (blk_height *)parent_key.mv_data;
800 if (prev->bh_height != m_height - 1)
801 throw0(BLOCK_PARENT_DNE("Top block is not new block's parent"));
802 }
803
804 int result = 0;
805
806 MDB_val_set(key, m_height);
807
808 CURSOR(blocks)
809 CURSOR(block_info)
810
811 // this call to mdb_cursor_put will change height()
812 cryptonote::blobdata block_blob(block_to_blob(blk));
813 MDB_val_sized(blob, block_blob);
814 result = mdb_cursor_put(m_cur_blocks, &key, &blob, MDB_APPEND);
815 if (result)
816 throw0(DB_ERROR(lmdb_error("Failed to add block blob to db transaction: ", result).c_str()));
817
818 mdb_block_info bi;
819 bi.bi_height = m_height;
820 bi.bi_timestamp = blk.timestamp;
821 bi.bi_coins = coins_generated;
822 bi.bi_weight = block_weight;
823 bi.bi_diff_hi = ((cumulative_difficulty >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
824 bi.bi_diff_lo = (cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
825 bi.bi_hash = blk_hash;
826 bi.bi_cum_rct = num_rct_outs;
827 if (blk.major_version >= 4)
828 {
829 uint64_t last_height = m_height-1;
830 MDB_val_set(h, last_height);
831 if ((result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &h, MDB_GET_BOTH)))
832 throw1(BLOCK_DNE(lmdb_error("Failed to get block info: ", result).c_str()));
833 const mdb_block_info *bi_prev = (const mdb_block_info*)h.mv_data;
834 bi.bi_cum_rct += bi_prev->bi_cum_rct;
835 }
836 bi.bi_long_term_block_weight = long_term_block_weight;
837
838 MDB_val_set(val, bi);
839 result = mdb_cursor_put(m_cur_block_info, (MDB_val *)&zerokval, &val, MDB_APPENDDUP);
840 if (result)
841 throw0(DB_ERROR(lmdb_error("Failed to add block info to db transaction: ", result).c_str()));
842
843 result = mdb_cursor_put(m_cur_block_heights, (MDB_val *)&zerokval, &val_h, 0);
844 if (result)
845 throw0(DB_ERROR(lmdb_error("Failed to add block height by hash to db transaction: ", result).c_str()));
846
847 // we use weight as a proxy for size, since we don't have size but weight is >= size
848 // and often actually equal
849 m_cum_size += block_weight;
850 m_cum_count++;
851 }
852
853 void BlockchainLMDB::remove_block()
854 {
855 int result;
856
857 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
858 check_open();
859 uint64_t m_height = height();
860
861 if (m_height == 0)
862 throw0(BLOCK_DNE ("Attempting to remove block from an empty blockchain"));
863
864 mdb_txn_cursors *m_cursors = &m_wcursors;
865 CURSOR(block_info)
866 CURSOR(block_heights)
867 CURSOR(blocks)
868 MDB_val_copy<uint64_t> k(m_height - 1);
869 MDB_val h = k;
870 if ((result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &h, MDB_GET_BOTH)))
871 throw1(BLOCK_DNE(lmdb_error("Attempting to remove block that's not in the db: ", result).c_str()));
872
873 // must use h now; deleting from m_block_info will invalidate it
874 mdb_block_info *bi = (mdb_block_info *)h.mv_data;
875 blk_height bh = {bi->bi_hash, 0};
876 h.mv_data = (void *)&bh;
877 h.mv_size = sizeof(bh);
878 if ((result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &h, MDB_GET_BOTH)))
879 throw1(DB_ERROR(lmdb_error("Failed to locate block height by hash for removal: ", result).c_str()));
880 if ((result = mdb_cursor_del(m_cur_block_heights, 0)))
881 throw1(DB_ERROR(lmdb_error("Failed to add removal of block height by hash to db transaction: ", result).c_str()));
882
883 if ((result = mdb_cursor_del(m_cur_blocks, 0)))
884 throw1(DB_ERROR(lmdb_error("Failed to add removal of block to db transaction: ", result).c_str()));
885
886 if ((result = mdb_cursor_del(m_cur_block_info, 0)))
887 throw1(DB_ERROR(lmdb_error("Failed to add removal of block info to db transaction: ", result).c_str()));
888 }
889
890 uint64_t BlockchainLMDB::add_transaction_data(const crypto::hash& blk_hash, const std::pair<transaction, blobdata_ref>& txp, const crypto::hash& tx_hash, const crypto::hash& tx_prunable_hash)
891 {
892 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
893 check_open();
894 mdb_txn_cursors *m_cursors = &m_wcursors;
895 uint64_t m_height = height();
896
897 int result;
898 uint64_t tx_id = get_tx_count();
899
900 CURSOR(txs_pruned)
901 CURSOR(txs_prunable)
902 CURSOR(txs_prunable_hash)
903 CURSOR(txs_prunable_tip)
904 CURSOR(tx_indices)
905
906 MDB_val_set(val_tx_id, tx_id);
907 MDB_val_set(val_h, tx_hash);
908 result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &val_h, MDB_GET_BOTH);
909 if (result == 0) {
910 txindex *tip = (txindex *)val_h.mv_data;
911 throw1(TX_EXISTS(std::string("Attempting to add transaction that's already in the db (tx id ").append(boost::lexical_cast<std::string>(tip->data.tx_id)).append(")").c_str()));
912 } else if (result != MDB_NOTFOUND) {
913 throw1(DB_ERROR(lmdb_error(std::string("Error checking if tx index exists for tx hash ") + epee::string_tools::pod_to_hex(tx_hash) + ": ", result).c_str()));
914 }
915
916 const cryptonote::transaction &tx = txp.first;
917 txindex ti;
918 ti.key = tx_hash;
919 ti.data.tx_id = tx_id;
920 ti.data.unlock_time = tx.unlock_time;
921 ti.data.block_id = m_height; // we don't need blk_hash since we know m_height
922
923 val_h.mv_size = sizeof(ti);
924 val_h.mv_data = (void *)&ti;
925
926 result = mdb_cursor_put(m_cur_tx_indices, (MDB_val *)&zerokval, &val_h, 0);
927 if (result)
928 throw0(DB_ERROR(lmdb_error("Failed to add tx data to db transaction: ", result).c_str()));
929
930 const cryptonote::blobdata_ref &blob = txp.second;
931
932 unsigned int unprunable_size = tx.unprunable_size;
933 if (unprunable_size == 0)
934 {
935 std::stringstream ss;
936 binary_archive<true> ba(ss);
937 bool r = const_cast<cryptonote::transaction&>(tx).serialize_base(ba);
938 if (!r)
939 throw0(DB_ERROR("Failed to serialize pruned tx"));
940 unprunable_size = ss.str().size();
941 }
942
943 if (unprunable_size > blob.size())
944 throw0(DB_ERROR("pruned tx size is larger than tx size"));
945
946 MDB_val pruned_blob = {unprunable_size, (void*)blob.data()};
947 result = mdb_cursor_put(m_cur_txs_pruned, &val_tx_id, &pruned_blob, MDB_APPEND);
948 if (result)
949 throw0(DB_ERROR(lmdb_error("Failed to add pruned tx blob to db transaction: ", result).c_str()));
950
951 MDB_val prunable_blob = {blob.size() - unprunable_size, (void*)(blob.data() + unprunable_size)};
952 result = mdb_cursor_put(m_cur_txs_prunable, &val_tx_id, &prunable_blob, MDB_APPEND);
953 if (result)
954 throw0(DB_ERROR(lmdb_error("Failed to add prunable tx blob to db transaction: ", result).c_str()));
955
956 if (get_blockchain_pruning_seed())
957 {
958 MDB_val_set(val_height, m_height);
959 result = mdb_cursor_put(m_cur_txs_prunable_tip, &val_tx_id, &val_height, 0);
960 if (result)
961 throw0(DB_ERROR(lmdb_error("Failed to add prunable tx id to db transaction: ", result).c_str()));
962 }
963
964 if (tx.version > 1)
965 {
966 MDB_val_set(val_prunable_hash, tx_prunable_hash);
967 result = mdb_cursor_put(m_cur_txs_prunable_hash, &val_tx_id, &val_prunable_hash, MDB_APPEND);
968 if (result)
969 throw0(DB_ERROR(lmdb_error("Failed to add prunable tx prunable hash to db transaction: ", result).c_str()));
970 }
971
972 return tx_id;
973 }
974
975 // TODO: compare pros and cons of looking up the tx hash's tx index once and
976 // passing it in to functions like this
977 void BlockchainLMDB::remove_transaction_data(const crypto::hash& tx_hash, const transaction& tx)
978 {
979 int result;
980
981 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
982 check_open();
983
984 mdb_txn_cursors *m_cursors = &m_wcursors;
985 CURSOR(tx_indices)
986 CURSOR(txs_pruned)
987 CURSOR(txs_prunable)
988 CURSOR(txs_prunable_hash)
989 CURSOR(txs_prunable_tip)
990 CURSOR(tx_outputs)
991
992 MDB_val_set(val_h, tx_hash);
993
994 if (mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &val_h, MDB_GET_BOTH))
995 throw1(TX_DNE("Attempting to remove transaction that isn't in the db"));
996 txindex *tip = (txindex *)val_h.mv_data;
997 MDB_val_set(val_tx_id, tip->data.tx_id);
998
999 if ((result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, NULL, MDB_SET)))
1000 throw1(DB_ERROR(lmdb_error("Failed to locate pruned tx for removal: ", result).c_str()));
1001 result = mdb_cursor_del(m_cur_txs_pruned, 0);
1002 if (result)
1003 throw1(DB_ERROR(lmdb_error("Failed to add removal of pruned tx to db transaction: ", result).c_str()));
1004
1005 result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, NULL, MDB_SET);
1006 if (result == 0)
1007 {
1008 result = mdb_cursor_del(m_cur_txs_prunable, 0);
1009 if (result)
1010 throw1(DB_ERROR(lmdb_error("Failed to add removal of prunable tx to db transaction: ", result).c_str()));
1011 }
1012 else if (result != MDB_NOTFOUND)
1013 throw1(DB_ERROR(lmdb_error("Failed to locate prunable tx for removal: ", result).c_str()));
1014
1015 result = mdb_cursor_get(m_cur_txs_prunable_tip, &val_tx_id, NULL, MDB_SET);
1016 if (result && result != MDB_NOTFOUND)
1017 throw1(DB_ERROR(lmdb_error("Failed to locate tx id for removal: ", result).c_str()));
1018 if (result == 0)
1019 {
1020 result = mdb_cursor_del(m_cur_txs_prunable_tip, 0);
1021 if (result)
1022 throw1(DB_ERROR(lmdb_error("Error adding removal of tx id to db transaction", result).c_str()));
1023 }
1024
1025 if (tx.version > 1)
1026 {
1027 if ((result = mdb_cursor_get(m_cur_txs_prunable_hash, &val_tx_id, NULL, MDB_SET)))
1028 throw1(DB_ERROR(lmdb_error("Failed to locate prunable hash tx for removal: ", result).c_str()));
1029 result = mdb_cursor_del(m_cur_txs_prunable_hash, 0);
1030 if (result)
1031 throw1(DB_ERROR(lmdb_error("Failed to add removal of prunable hash tx to db transaction: ", result).c_str()));
1032 }
1033
1034 remove_tx_outputs(tip->data.tx_id, tx);
1035
1036 result = mdb_cursor_get(m_cur_tx_outputs, &val_tx_id, NULL, MDB_SET);
1037 if (result == MDB_NOTFOUND)
1038 LOG_PRINT_L1("tx has no outputs to remove: " << tx_hash);
1039 else if (result)
1040 throw1(DB_ERROR(lmdb_error("Failed to locate tx outputs for removal: ", result).c_str()));
1041 if (!result)
1042 {
1043 result = mdb_cursor_del(m_cur_tx_outputs, 0);
1044 if (result)
1045 throw1(DB_ERROR(lmdb_error("Failed to add removal of tx outputs to db transaction: ", result).c_str()));
1046 }
1047
1048 // Don't delete the tx_indices entry until the end, after we're done with val_tx_id
1049 if (mdb_cursor_del(m_cur_tx_indices, 0))
1050 throw1(DB_ERROR("Failed to add removal of tx index to db transaction"));
1051 }
1052
1053 uint64_t BlockchainLMDB::add_output(const crypto::hash& tx_hash,
1054 const tx_out& tx_output,
1055 const uint64_t& local_index,
1056 const uint64_t unlock_time,
1057 const rct::key *commitment)
1058 {
1059 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1060 check_open();
1061 mdb_txn_cursors *m_cursors = &m_wcursors;
1062 uint64_t m_height = height();
1063 uint64_t m_num_outputs = num_outputs();
1064
1065 int result = 0;
1066
1067 CURSOR(output_txs)
1068 CURSOR(output_amounts)
1069
1070 crypto::public_key output_public_key;
1071 if (!get_output_public_key(tx_output, output_public_key))
1072 throw0(DB_ERROR("Could not get an output public key from a tx output."));
1073 if (tx_output.amount == 0 && !commitment)
1074 throw0(DB_ERROR("RCT output without commitment"));
1075
1076 outtx ot = {m_num_outputs, tx_hash, local_index};
1077 MDB_val_set(vot, ot);
1078
1079 result = mdb_cursor_put(m_cur_output_txs, (MDB_val *)&zerokval, &vot, MDB_APPENDDUP);
1080 if (result)
1081 throw0(DB_ERROR(lmdb_error("Failed to add output tx hash to db transaction: ", result).c_str()));
1082
1083 outkey ok;
1084 MDB_val data;
1085 MDB_val_copy<uint64_t> val_amount(tx_output.amount);
1086 result = mdb_cursor_get(m_cur_output_amounts, &val_amount, &data, MDB_SET);
1087 if (!result)
1088 {
1089 mdb_size_t num_elems = 0;
1090 result = mdb_cursor_count(m_cur_output_amounts, &num_elems);
1091 if (result)
1092 throw0(DB_ERROR(std::string("Failed to get number of outputs for amount: ").append(mdb_strerror(result)).c_str()));
1093 ok.amount_index = num_elems;
1094 }
1095 else if (result != MDB_NOTFOUND)
1096 throw0(DB_ERROR(lmdb_error("Failed to get output amount in db transaction: ", result).c_str()));
1097 else
1098 ok.amount_index = 0;
1099 ok.output_id = m_num_outputs;
1100 ok.data.pubkey = output_public_key;
1101 ok.data.unlock_time = unlock_time;
1102 ok.data.height = m_height;
1103 if (tx_output.amount == 0)
1104 {
1105 ok.data.commitment = *commitment;
1106 data.mv_size = sizeof(ok);
1107 }
1108 else
1109 {
1110 data.mv_size = sizeof(pre_rct_outkey);
1111 }
1112 data.mv_data = &ok;
1113
1114 if ((result = mdb_cursor_put(m_cur_output_amounts, &val_amount, &data, MDB_APPENDDUP)))
1115 throw0(DB_ERROR(lmdb_error("Failed to add output pubkey to db transaction: ", result).c_str()));
1116
1117 return ok.amount_index;
1118 }
1119
1120 void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id,
1121 const std::vector<uint64_t>& amount_output_indices)
1122 {
1123 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1124 check_open();
1125 mdb_txn_cursors *m_cursors = &m_wcursors;
1126 CURSOR(tx_outputs)
1127
1128 int result = 0;
1129
1130 size_t num_outputs = amount_output_indices.size();
1131
1132 MDB_val_set(k_tx_id, tx_id);
1133 MDB_val v;
1134 v.mv_data = num_outputs ? (void *)amount_output_indices.data() : (void*)"";
1135 v.mv_size = sizeof(uint64_t) * num_outputs;
1136 // LOG_PRINT_L1("tx_outputs[tx_hash] size: " << v.mv_size);
1137
1138 result = mdb_cursor_put(m_cur_tx_outputs, &k_tx_id, &v, MDB_APPEND);
1139 if (result)
1140 throw0(DB_ERROR(std::string("Failed to add <tx hash, amount output index array> to db transaction: ").append(mdb_strerror(result)).c_str()));
1141 }
1142
1143 void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& tx)
1144 {
1145 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1146
1147 std::vector<std::vector<uint64_t>> amount_output_indices_set = get_tx_amount_output_indices(tx_id, 1);
1148 const std::vector<uint64_t> &amount_output_indices = amount_output_indices_set.front();
1149
1150 if (amount_output_indices.empty())
1151 {
1152 if (tx.vout.empty())
1153 LOG_PRINT_L2("tx has no outputs, so no output indices");
1154 else
1155 throw0(DB_ERROR("tx has outputs, but no output indices found"));
1156 }
1157
1158 bool is_pseudo_rct = tx.version >= 2 && tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
1159 for (size_t i = tx.vout.size(); i-- > 0;)
1160 {
1161 uint64_t amount = is_pseudo_rct ? 0 : tx.vout[i].amount;
1162 remove_output(amount, amount_output_indices[i]);
1163 }
1164 }
1165
1166 void BlockchainLMDB::remove_output(const uint64_t amount, const uint64_t& out_index)
1167 {
1168 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1169 check_open();
1170 mdb_txn_cursors *m_cursors = &m_wcursors;
1171 CURSOR(output_amounts);
1172 CURSOR(output_txs);
1173
1174 MDB_val_set(k, amount);
1175 MDB_val_set(v, out_index);
1176
1177 auto result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
1178 if (result == MDB_NOTFOUND)
1179 throw1(OUTPUT_DNE("Attempting to get an output index by amount and amount index, but amount not found"));
1180 else if (result)
1181 throw0(DB_ERROR(lmdb_error("DB error attempting to get an output", result).c_str()));
1182
1183 const pre_rct_outkey *ok = (const pre_rct_outkey *)v.mv_data;
1184 MDB_val_set(otxk, ok->output_id);
1185 result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &otxk, MDB_GET_BOTH);
1186 if (result == MDB_NOTFOUND)
1187 {
1188 throw0(DB_ERROR("Unexpected: global output index not found in m_output_txs"));
1189 }
1190 else if (result)
1191 {
1192 throw1(DB_ERROR(lmdb_error("Error adding removal of output tx to db transaction", result).c_str()));
1193 }
1194 result = mdb_cursor_del(m_cur_output_txs, 0);
1195 if (result)
1196 throw0(DB_ERROR(lmdb_error(std::string("Error deleting output index ").append(boost::lexical_cast<std::string>(out_index).append(": ")).c_str(), result).c_str()));
1197
1198 // now delete the amount
1199 result = mdb_cursor_del(m_cur_output_amounts, 0);
1200 if (result)
1201 throw0(DB_ERROR(lmdb_error(std::string("Error deleting amount for output index ").append(boost::lexical_cast<std::string>(out_index).append(": ")).c_str(), result).c_str()));
1202 }
1203
1204 void BlockchainLMDB::prune_outputs(uint64_t amount)
1205 {
1206 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1207 check_open();
1208 mdb_txn_cursors *m_cursors = &m_wcursors;
1209 CURSOR(output_amounts);
1210 CURSOR(output_txs);
1211
1212 MINFO("Pruning outputs for amount " << amount);
1213
1214 MDB_val v;
1215 MDB_val_set(k, amount);
1216 int result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_SET);
1217 if (result == MDB_NOTFOUND)
1218 return;
1219 if (result)
1220 throw0(DB_ERROR(lmdb_error("Error looking up outputs: ", result).c_str()));
1221
1222 // gather output ids
1223 mdb_size_t num_elems;
1224 mdb_cursor_count(m_cur_output_amounts, &num_elems);
1225 MINFO(num_elems << " outputs found");
1226 std::vector<uint64_t> output_ids;
1227 output_ids.reserve(num_elems);
1228 while (1)
1229 {
1230 const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data;
1231 output_ids.push_back(okp->output_id);
1232 MDEBUG("output id " << okp->output_id);
1233 result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_NEXT_DUP);
1234 if (result == MDB_NOTFOUND)
1235 break;
1236 if (result)
1237 throw0(DB_ERROR(lmdb_error("Error counting outputs: ", result).c_str()));
1238 }
1239 if (output_ids.size() != num_elems)
1240 throw0(DB_ERROR("Unexpected number of outputs"));
1241
1242 result = mdb_cursor_del(m_cur_output_amounts, MDB_NODUPDATA);
1243 if (result)
1244 throw0(DB_ERROR(lmdb_error("Error deleting outputs: ", result).c_str()));
1245
1246 for (uint64_t output_id: output_ids)
1247 {
1248 MDB_val_set(v, output_id);
1249 result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
1250 if (result)
1251 throw0(DB_ERROR(lmdb_error("Error looking up output: ", result).c_str()));
1252 result = mdb_cursor_del(m_cur_output_txs, 0);
1253 if (result)
1254 throw0(DB_ERROR(lmdb_error("Error deleting output: ", result).c_str()));
1255 }
1256 }
1257
1258 void BlockchainLMDB::add_spent_key(const crypto::key_image& k_image)
1259 {
1260 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1261 check_open();
1262 mdb_txn_cursors *m_cursors = &m_wcursors;
1263
1264 CURSOR(spent_keys)
1265
1266 MDB_val k = {sizeof(k_image), (void *)&k_image};
1267 if (auto result = mdb_cursor_put(m_cur_spent_keys, (MDB_val *)&zerokval, &k, MDB_NODUPDATA)) {
1268 if (result == MDB_KEYEXIST)
1269 throw1(KEY_IMAGE_EXISTS("Attempting to add spent key image that's already in the db"));
1270 else
1271 throw1(DB_ERROR(lmdb_error("Error adding spent key image to db transaction: ", result).c_str()));
1272 }
1273 }
1274
1275 void BlockchainLMDB::remove_spent_key(const crypto::key_image& k_image)
1276 {
1277 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1278 check_open();
1279 mdb_txn_cursors *m_cursors = &m_wcursors;
1280
1281 CURSOR(spent_keys)
1282
1283 MDB_val k = {sizeof(k_image), (void *)&k_image};
1284 auto result = mdb_cursor_get(m_cur_spent_keys, (MDB_val *)&zerokval, &k, MDB_GET_BOTH);
1285 if (result != 0 && result != MDB_NOTFOUND)
1286 throw1(DB_ERROR(lmdb_error("Error finding spent key to remove", result).c_str()));
1287 if (!result)
1288 {
1289 result = mdb_cursor_del(m_cur_spent_keys, 0);
1290 if (result)
1291 throw1(DB_ERROR(lmdb_error("Error adding removal of key image to db transaction", result).c_str()));
1292 }
1293 }
1294
1295 BlockchainLMDB::~BlockchainLMDB()
1296 {
1297 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1298
1299 // batch transaction shouldn't be active at this point. If it is, consider it aborted.
1300 if (m_batch_active)
1301 {
1302 try { BlockchainLMDB::batch_abort(); }
1303 catch (...) { /* ignore */ }
1304 }
1305 if (m_open)
1306 BlockchainLMDB::close();
1307 }
1308
1309 BlockchainLMDB::BlockchainLMDB(bool batch_transactions): BlockchainDB()
1310 {
1311 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1312 // initialize folder to something "safe" just in case
1313 // someone accidentally misuses this class...
1314 m_folder = "thishsouldnotexistbecauseitisgibberish";
1315
1316 m_batch_transactions = batch_transactions;
1317 m_write_txn = nullptr;
1318 m_write_batch_txn = nullptr;
1319 m_batch_active = false;
1320 m_cum_size = 0;
1321 m_cum_count = 0;
1322
1323 // reset may also need changing when initialize things here
1324
1325 m_hardfork = nullptr;
1326 }
1327
1328 #ifdef WIN32
1329 static bool disable_ntfs_compression(const boost::filesystem::path& filepath)
1330 {
1331 DWORD file_attributes = ::GetFileAttributesW(filepath.c_str());
1332 if (file_attributes == INVALID_FILE_ATTRIBUTES)
1333 {
1334 MERROR("Failed to get " << filepath.string() << " file attributes. Error: " << ::GetLastError());
1335 return false;
1336 }
1337
1338 if (!(file_attributes & FILE_ATTRIBUTE_COMPRESSED))
1339 return true; // not compressed
1340
1341 LOG_PRINT_L1("Disabling NTFS compression for " << filepath.string());
1342 HANDLE file_handle = ::CreateFileW(
1343 filepath.c_str(),
1344 GENERIC_READ | GENERIC_WRITE,
1345 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1346 nullptr,
1347 OPEN_EXISTING,
1348 boost::filesystem::is_directory(filepath) ? FILE_FLAG_BACKUP_SEMANTICS : 0, // Needed to open handles to directories
1349 nullptr
1350 );
1351
1352 if (file_handle == INVALID_HANDLE_VALUE)
1353 {
1354 MERROR("Failed to open handle: " << filepath.string() << ". Error: " << ::GetLastError());
1355 return false;
1356 }
1357
1358 USHORT compression_state = COMPRESSION_FORMAT_NONE;
1359 DWORD bytes_returned;
1360 BOOL ok = ::DeviceIoControl(
1361 file_handle,
1362 FSCTL_SET_COMPRESSION,
1363 &compression_state,
1364 sizeof(compression_state),
1365 nullptr,
1366 0,
1367 &bytes_returned,
1368 nullptr
1369 );
1370
1371 ::CloseHandle(file_handle);
1372 return ok;
1373 }
1374 #endif
1375
1376 void BlockchainLMDB::open(const std::string& filename, const int db_flags)
1377 {
1378 int result;
1379 int mdb_flags = MDB_NORDAHEAD;
1380
1381 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1382
1383 if (m_open)
1384 throw0(DB_OPEN_FAILURE("Attempted to open db, but it's already open"));
1385
1386 boost::filesystem::path direc(filename);
1387 if (!boost::filesystem::exists(direc) &&
1388 !boost::filesystem::create_directories(direc)) {
1389 throw0(DB_OPEN_FAILURE(std::string("Failed to create directory ").append(filename).c_str()));
1390 }
1391
1392 // check for existing LMDB files in base directory
1393 boost::filesystem::path old_files = direc.parent_path();
1394 if (boost::filesystem::exists(old_files / CRYPTONOTE_BLOCKCHAINDATA_FILENAME)
1395 || boost::filesystem::exists(old_files / CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME))
1396 {
1397 LOG_PRINT_L0("Found existing LMDB files in " << old_files.string());
1398 LOG_PRINT_L0("Move " << CRYPTONOTE_BLOCKCHAINDATA_FILENAME << " and/or " << CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME << " to " << filename << ", or delete them, and then restart");
1399 throw DB_ERROR("Database could not be opened");
1400 }
1401
1402 #ifdef WIN32
1403 // ensure NTFS compression is disabled on the directory and database file to avoid corruption of the blockchain
1404 if (!disable_ntfs_compression(filename))
1405 LOG_PRINT_L0("Failed to disable NTFS compression on folder: " << filename << ". Error: " << ::GetLastError());
1406 boost::filesystem::path datafile(filename);
1407 datafile /= CRYPTONOTE_BLOCKCHAINDATA_FILENAME;
1408 if (!boost::filesystem::exists(datafile))
1409 boost::filesystem::ofstream(datafile).close(); // create the file to see if NTFS compression is enabled beforehand
1410 if (!disable_ntfs_compression(datafile))
1411 throw DB_ERROR("Database file is NTFS compressed and compression could not be disabled");
1412 #endif
1413
1414 boost::optional<bool> is_hdd_result = tools::is_hdd(filename.c_str());
1415 if (is_hdd_result)
1416 {
1417 if (is_hdd_result.value())
1418 MCLOG_RED(el::Level::Warning, "global", "The blockchain is on a rotating drive: this will be very slow, use an SSD if possible");
1419 }
1420
1421 m_folder = filename;
1422
1423 #ifdef __OpenBSD__
1424 if ((mdb_flags & MDB_WRITEMAP) == 0) {
1425 MCLOG_RED(el::Level::Info, "global", "Running on OpenBSD: forcing WRITEMAP");
1426 mdb_flags |= MDB_WRITEMAP;
1427 }
1428 #endif
1429 // set up lmdb environment
1430 if ((result = mdb_env_create(&m_env)))
1431 throw0(DB_ERROR(lmdb_error("Failed to create lmdb environment: ", result).c_str()));
1432 if ((result = mdb_env_set_maxdbs(m_env, 32)))
1433 throw0(DB_ERROR(lmdb_error("Failed to set max number of dbs: ", result).c_str()));
1434
1435 int threads = tools::get_max_concurrency();
1436 if (threads > 110 && /* maxreaders default is 126, leave some slots for other read processes */
1437 (result = mdb_env_set_maxreaders(m_env, threads+16)))
1438 throw0(DB_ERROR(lmdb_error("Failed to set max number of readers: ", result).c_str()));
1439
1440 size_t mapsize = DEFAULT_MAPSIZE;
1441
1442 if (db_flags & DBF_FAST)
1443 mdb_flags |= MDB_NOSYNC;
1444 if (db_flags & DBF_FASTEST)
1445 mdb_flags |= MDB_NOSYNC | MDB_WRITEMAP | MDB_MAPASYNC;
1446 if (db_flags & DBF_RDONLY)
1447 mdb_flags = MDB_RDONLY;
1448 if (db_flags & DBF_SALVAGE)
1449 mdb_flags |= MDB_PREVSNAPSHOT;
1450
1451 if (auto result = mdb_env_open(m_env, filename.c_str(), mdb_flags, 0644))
1452 throw0(DB_ERROR(lmdb_error("Failed to open lmdb environment: ", result).c_str()));
1453
1454 MDB_envinfo mei;
1455 mdb_env_info(m_env, &mei);
1456 uint64_t cur_mapsize = (uint64_t)mei.me_mapsize;
1457
1458 if (cur_mapsize < mapsize)
1459 {
1460 if (auto result = mdb_env_set_mapsize(m_env, mapsize))
1461 throw0(DB_ERROR(lmdb_error("Failed to set max memory map size: ", result).c_str()));
1462 mdb_env_info(m_env, &mei);
1463 cur_mapsize = (uint64_t)mei.me_mapsize;
1464 LOG_PRINT_L1("LMDB memory map size: " << cur_mapsize);
1465 }
1466
1467 if (need_resize())
1468 {
1469 LOG_PRINT_L0("LMDB memory map needs to be resized, doing that now.");
1470 do_resize();
1471 }
1472
1473 int txn_flags = 0;
1474 if (mdb_flags & MDB_RDONLY)
1475 txn_flags |= MDB_RDONLY;
1476
1477 // get a read/write MDB_txn, depending on mdb_flags
1478 mdb_txn_safe txn;
1479 if (auto mdb_res = mdb_txn_begin(m_env, NULL, txn_flags, txn))
1480 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", mdb_res).c_str()));
1481
1482 // open necessary databases, and set properties as needed
1483 // uses macros to avoid having to change things too many places
1484 // also change blockchain_prune.cpp to match
1485 lmdb_db_open(txn, LMDB_BLOCKS, MDB_INTEGERKEY | MDB_CREATE, m_blocks, "Failed to open db handle for m_blocks");
1486
1487 lmdb_db_open(txn, LMDB_BLOCK_INFO, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for m_block_info");
1488 lmdb_db_open(txn, LMDB_BLOCK_HEIGHTS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_heights, "Failed to open db handle for m_block_heights");
1489
1490 lmdb_db_open(txn, LMDB_TXS, MDB_INTEGERKEY | MDB_CREATE, m_txs, "Failed to open db handle for m_txs");
1491 lmdb_db_open(txn, LMDB_TXS_PRUNED, MDB_INTEGERKEY | MDB_CREATE, m_txs_pruned, "Failed to open db handle for m_txs_pruned");
1492 lmdb_db_open(txn, LMDB_TXS_PRUNABLE, MDB_INTEGERKEY | MDB_CREATE, m_txs_prunable, "Failed to open db handle for m_txs_prunable");
1493 lmdb_db_open(txn, LMDB_TXS_PRUNABLE_HASH, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_txs_prunable_hash, "Failed to open db handle for m_txs_prunable_hash");
1494 if (!(mdb_flags & MDB_RDONLY))
1495 lmdb_db_open(txn, LMDB_TXS_PRUNABLE_TIP, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_txs_prunable_tip, "Failed to open db handle for m_txs_prunable_tip");
1496 lmdb_db_open(txn, LMDB_TX_INDICES, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_tx_indices, "Failed to open db handle for m_tx_indices");
1497 lmdb_db_open(txn, LMDB_TX_OUTPUTS, MDB_INTEGERKEY | MDB_CREATE, m_tx_outputs, "Failed to open db handle for m_tx_outputs");
1498
1499 lmdb_db_open(txn, LMDB_OUTPUT_TXS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_output_txs, "Failed to open db handle for m_output_txs");
1500 lmdb_db_open(txn, LMDB_OUTPUT_AMOUNTS, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_output_amounts, "Failed to open db handle for m_output_amounts");
1501
1502 lmdb_db_open(txn, LMDB_SPENT_KEYS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_spent_keys, "Failed to open db handle for m_spent_keys");
1503
1504 lmdb_db_open(txn, LMDB_TXPOOL_META, MDB_CREATE, m_txpool_meta, "Failed to open db handle for m_txpool_meta");
1505 lmdb_db_open(txn, LMDB_TXPOOL_BLOB, MDB_CREATE, m_txpool_blob, "Failed to open db handle for m_txpool_blob");
1506
1507 lmdb_db_open(txn, LMDB_ALT_BLOCKS, MDB_CREATE, m_alt_blocks, "Failed to open db handle for m_alt_blocks");
1508
1509 // this subdb is dropped on sight, so it may not be present when we open the DB.
1510 // Since we use MDB_CREATE, we'll get an exception if we open read-only and it does not exist.
1511 // So we don't open for read-only, and also not drop below. It is not used elsewhere.
1512 if (!(mdb_flags & MDB_RDONLY))
1513 lmdb_db_open(txn, LMDB_HF_STARTING_HEIGHTS, MDB_CREATE, m_hf_starting_heights, "Failed to open db handle for m_hf_starting_heights");
1514
1515 lmdb_db_open(txn, LMDB_HF_VERSIONS, MDB_INTEGERKEY | MDB_CREATE, m_hf_versions, "Failed to open db handle for m_hf_versions");
1516
1517 lmdb_db_open(txn, LMDB_PROPERTIES, MDB_CREATE, m_properties, "Failed to open db handle for m_properties");
1518
1519 mdb_set_dupsort(txn, m_spent_keys, compare_hash32);
1520 mdb_set_dupsort(txn, m_block_heights, compare_hash32);
1521 mdb_set_dupsort(txn, m_tx_indices, compare_hash32);
1522 mdb_set_dupsort(txn, m_output_amounts, compare_uint64);
1523 mdb_set_dupsort(txn, m_output_txs, compare_uint64);
1524 mdb_set_dupsort(txn, m_block_info, compare_uint64);
1525 if (!(mdb_flags & MDB_RDONLY))
1526 mdb_set_dupsort(txn, m_txs_prunable_tip, compare_uint64);
1527 mdb_set_compare(txn, m_txs_prunable, compare_uint64);
1528 mdb_set_dupsort(txn, m_txs_prunable_hash, compare_uint64);
1529
1530 mdb_set_compare(txn, m_txpool_meta, compare_hash32);
1531 mdb_set_compare(txn, m_txpool_blob, compare_hash32);
1532 mdb_set_compare(txn, m_alt_blocks, compare_hash32);
1533 mdb_set_compare(txn, m_properties, compare_string);
1534
1535 if (!(mdb_flags & MDB_RDONLY))
1536 {
1537 result = mdb_drop(txn, m_hf_starting_heights, 1);
1538 if (result && result != MDB_NOTFOUND)
1539 throw0(DB_ERROR(lmdb_error("Failed to drop m_hf_starting_heights: ", result).c_str()));
1540 }
1541
1542 // get and keep current height
1543 MDB_stat db_stats;
1544 if ((result = mdb_stat(txn, m_blocks, &db_stats)))
1545 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
1546 LOG_PRINT_L2("Setting m_height to: " << db_stats.ms_entries);
1547 uint64_t m_height = db_stats.ms_entries;
1548
1549 bool compatible = true;
1550
1551 MDB_val_str(k, "version");
1552 MDB_val v;
1553 auto get_result = mdb_get(txn, m_properties, &k, &v);
1554 if(get_result == MDB_SUCCESS)
1555 {
1556 const uint32_t db_version = *(const uint32_t*)v.mv_data;
1557 if (db_version > VERSION)
1558 {
1559 MWARNING("Existing lmdb database was made by a later version (" << db_version << "). We don't know how it will change yet.");
1560 compatible = false;
1561 }
1562 #if VERSION > 0
1563 else if (db_version < VERSION)
1564 {
1565 if (mdb_flags & MDB_RDONLY)
1566 {
1567 txn.abort();
1568 mdb_env_close(m_env);
1569 m_open = false;
1570 MFATAL("Existing lmdb database needs to be converted, which cannot be done on a read-only database.");
1571 MFATAL("Please run monerod once to convert the database.");
1572 return;
1573 }
1574 // Note that there was a schema change within version 0 as well.
1575 // See commit e5d2680094ee15889934fe28901e4e133cda56f2 2015/07/10
1576 // We don't handle the old format previous to that commit.
1577 txn.commit();
1578 m_open = true;
1579 migrate(db_version);
1580 return;
1581 }
1582 #endif
1583 }
1584 else
1585 {
1586 // if not found, and the DB is non-empty, this is probably
1587 // an "old" version 0, which we don't handle. If the DB is
1588 // empty it's fine.
1589 if (VERSION > 0 && m_height > 0)
1590 compatible = false;
1591 }
1592
1593 if (!compatible)
1594 {
1595 txn.abort();
1596 mdb_env_close(m_env);
1597 m_open = false;
1598 MFATAL("Existing lmdb database is incompatible with this version.");
1599 MFATAL("Please delete the existing database and resync.");
1600 return;
1601 }
1602
1603 if (!(mdb_flags & MDB_RDONLY))
1604 {
1605 // only write version on an empty DB
1606 if (m_height == 0)
1607 {
1608 MDB_val_str(k, "version");
1609 MDB_val_copy<uint32_t> v(VERSION);
1610 auto put_result = mdb_put(txn, m_properties, &k, &v, 0);
1611 if (put_result != MDB_SUCCESS)
1612 {
1613 txn.abort();
1614 mdb_env_close(m_env);
1615 m_open = false;
1616 MERROR("Failed to write version to database.");
1617 return;
1618 }
1619 }
1620 }
1621
1622 // commit the transaction
1623 txn.commit();
1624
1625 m_open = true;
1626 // from here, init should be finished
1627 }
1628
1629 void BlockchainLMDB::close()
1630 {
1631 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1632 if (m_batch_active)
1633 {
1634 LOG_PRINT_L3("close() first calling batch_abort() due to active batch transaction");
1635 BlockchainLMDB::batch_abort();
1636 }
1637 BlockchainLMDB::sync();
1638 m_tinfo.reset();
1639
1640 // FIXME: not yet thread safe!!! Use with care.
1641 mdb_env_close(m_env);
1642 m_open = false;
1643 }
1644
1645 void BlockchainLMDB::sync()
1646 {
1647 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1648 check_open();
1649
1650 if (BlockchainLMDB::is_read_only())
1651 return;
1652
1653 // Does nothing unless LMDB environment was opened with MDB_NOSYNC or in part
1654 // MDB_NOMETASYNC. Force flush to be synchronous.
1655 if (auto result = mdb_env_sync(m_env, true))
1656 {
1657 throw0(DB_ERROR(lmdb_error("Failed to sync database: ", result).c_str()));
1658 }
1659 }
1660
1661 void BlockchainLMDB::safesyncmode(const bool onoff)
1662 {
1663 MINFO("switching safe mode " << (onoff ? "on" : "off"));
1664 mdb_env_set_flags(m_env, MDB_NOSYNC|MDB_MAPASYNC, !onoff);
1665 }
1666
1667 void BlockchainLMDB::reset()
1668 {
1669 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1670 check_open();
1671
1672 mdb_txn_safe txn;
1673 if (auto result = lmdb_txn_begin(m_env, NULL, 0, txn))
1674 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
1675
1676 if (auto result = mdb_drop(txn, m_blocks, 0))
1677 throw0(DB_ERROR(lmdb_error("Failed to drop m_blocks: ", result).c_str()));
1678 if (auto result = mdb_drop(txn, m_block_info, 0))
1679 throw0(DB_ERROR(lmdb_error("Failed to drop m_block_info: ", result).c_str()));
1680 if (auto result = mdb_drop(txn, m_block_heights, 0))
1681 throw0(DB_ERROR(lmdb_error("Failed to drop m_block_heights: ", result).c_str()));
1682 if (auto result = mdb_drop(txn, m_txs_pruned, 0))
1683 throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_pruned: ", result).c_str()));
1684 if (auto result = mdb_drop(txn, m_txs_prunable, 0))
1685 throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_prunable: ", result).c_str()));
1686 if (auto result = mdb_drop(txn, m_txs_prunable_hash, 0))
1687 throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_prunable_hash: ", result).c_str()));
1688 if (auto result = mdb_drop(txn, m_txs_prunable_tip, 0))
1689 throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_prunable_tip: ", result).c_str()));
1690 if (auto result = mdb_drop(txn, m_tx_indices, 0))
1691 throw0(DB_ERROR(lmdb_error("Failed to drop m_tx_indices: ", result).c_str()));
1692 if (auto result = mdb_drop(txn, m_tx_outputs, 0))
1693 throw0(DB_ERROR(lmdb_error("Failed to drop m_tx_outputs: ", result).c_str()));
1694 if (auto result = mdb_drop(txn, m_output_txs, 0))
1695 throw0(DB_ERROR(lmdb_error("Failed to drop m_output_txs: ", result).c_str()));
1696 if (auto result = mdb_drop(txn, m_output_amounts, 0))
1697 throw0(DB_ERROR(lmdb_error("Failed to drop m_output_amounts: ", result).c_str()));
1698 if (auto result = mdb_drop(txn, m_spent_keys, 0))
1699 throw0(DB_ERROR(lmdb_error("Failed to drop m_spent_keys: ", result).c_str()));
1700 (void)mdb_drop(txn, m_hf_starting_heights, 0); // this one is dropped in new code
1701 if (auto result = mdb_drop(txn, m_hf_versions, 0))
1702 throw0(DB_ERROR(lmdb_error("Failed to drop m_hf_versions: ", result).c_str()));
1703 if (auto result = mdb_drop(txn, m_properties, 0))
1704 throw0(DB_ERROR(lmdb_error("Failed to drop m_properties: ", result).c_str()));
1705
1706 // init with current version
1707 MDB_val_str(k, "version");
1708 MDB_val_copy<uint32_t> v(VERSION);
1709 if (auto result = mdb_put(txn, m_properties, &k, &v, 0))
1710 throw0(DB_ERROR(lmdb_error("Failed to write version to database: ", result).c_str()));
1711
1712 txn.commit();
1713 m_cum_size = 0;
1714 m_cum_count = 0;
1715 }
1716
1717 std::vector<std::string> BlockchainLMDB::get_filenames() const
1718 {
1719 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1720 std::vector<std::string> filenames;
1721
1722 boost::filesystem::path datafile(m_folder);
1723 datafile /= CRYPTONOTE_BLOCKCHAINDATA_FILENAME;
1724 boost::filesystem::path lockfile(m_folder);
1725 lockfile /= CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME;
1726
1727 filenames.push_back(datafile.string());
1728 filenames.push_back(lockfile.string());
1729
1730 return filenames;
1731 }
1732
1733 bool BlockchainLMDB::remove_data_file(const std::string& folder) const
1734 {
1735 const std::string filename = folder + "/data.mdb";
1736 try
1737 {
1738 boost::filesystem::remove(filename);
1739 }
1740 catch (const std::exception &e)
1741 {
1742 MERROR("Failed to remove " << filename << ": " << e.what());
1743 return false;
1744 }
1745 return true;
1746 }
1747
1748 std::string BlockchainLMDB::get_db_name() const
1749 {
1750 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1751
1752 return std::string("lmdb");
1753 }
1754
1755 // TODO: this?
1756 bool BlockchainLMDB::lock()
1757 {
1758 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1759 check_open();
1760 return false;
1761 }
1762
1763 // TODO: this?
1764 void BlockchainLMDB::unlock()
1765 {
1766 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1767 check_open();
1768 }
1769
1770
1771 // The below two macros are for DB access within block add/remove, whether
1772 // regular batch txn is in use or not. m_write_txn is used as a batch txn, even
1773 // if it's only within block add/remove.
1774 //
1775 // DB access functions that may be called both within block add/remove and
1776 // without should use these. If the function will be called ONLY within block
1777 // add/remove, m_write_txn alone may be used instead of these macros.
1778
1779 #define TXN_BLOCK_PREFIX(flags); \
1780 mdb_txn_safe auto_txn; \
1781 mdb_txn_safe* txn_ptr = &auto_txn; \
1782 if (m_batch_active || m_write_txn) \
1783 txn_ptr = m_write_txn; \
1784 else \
1785 { \
1786 if (auto mdb_res = lmdb_txn_begin(m_env, NULL, flags, auto_txn)) \
1787 throw0(DB_ERROR(lmdb_error(std::string("Failed to create a transaction for the db in ")+__FUNCTION__+": ", mdb_res).c_str())); \
1788 } \
1789
1790 #define TXN_BLOCK_POSTFIX_SUCCESS() \
1791 do { \
1792 if (! m_batch_active && ! m_write_txn) \
1793 auto_txn.commit(); \
1794 } while(0)
1795
1796 void BlockchainLMDB::add_txpool_tx(const crypto::hash &txid, const cryptonote::blobdata_ref &blob, const txpool_tx_meta_t &meta)
1797 {
1798 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1799 check_open();
1800 mdb_txn_cursors *m_cursors = &m_wcursors;
1801
1802 CURSOR(txpool_meta)
1803 CURSOR(txpool_blob)
1804
1805 MDB_val k = {sizeof(txid), (void *)&txid};
1806 MDB_val v = {sizeof(meta), (void *)&meta};
1807 if (auto result = mdb_cursor_put(m_cur_txpool_meta, &k, &v, MDB_NODUPDATA)) {
1808 if (result == MDB_KEYEXIST)
1809 throw1(DB_ERROR("Attempting to add txpool tx metadata that's already in the db"));
1810 else
1811 throw1(DB_ERROR(lmdb_error("Error adding txpool tx metadata to db transaction: ", result).c_str()));
1812 }
1813 MDB_val_sized(blob_val, blob);
1814 if (auto result = mdb_cursor_put(m_cur_txpool_blob, &k, &blob_val, MDB_NODUPDATA)) {
1815 if (result == MDB_KEYEXIST)
1816 throw1(DB_ERROR("Attempting to add txpool tx blob that's already in the db"));
1817 else
1818 throw1(DB_ERROR(lmdb_error("Error adding txpool tx blob to db transaction: ", result).c_str()));
1819 }
1820 }
1821
1822 void BlockchainLMDB::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta)
1823 {
1824 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1825 check_open();
1826 mdb_txn_cursors *m_cursors = &m_wcursors;
1827
1828 CURSOR(txpool_meta)
1829 CURSOR(txpool_blob)
1830
1831 MDB_val k = {sizeof(txid), (void *)&txid};
1832 MDB_val v;
1833 auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
1834 if (result != 0)
1835 throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta to update: ", result).c_str()));
1836 result = mdb_cursor_del(m_cur_txpool_meta, 0);
1837 if (result)
1838 throw1(DB_ERROR(lmdb_error("Error adding removal of txpool tx metadata to db transaction: ", result).c_str()));
1839 v = MDB_val({sizeof(meta), (void *)&meta});
1840 if ((result = mdb_cursor_put(m_cur_txpool_meta, &k, &v, MDB_NODUPDATA)) != 0) {
1841 if (result == MDB_KEYEXIST)
1842 throw1(DB_ERROR("Attempting to add txpool tx metadata that's already in the db"));
1843 else
1844 throw1(DB_ERROR(lmdb_error("Error adding txpool tx metadata to db transaction: ", result).c_str()));
1845 }
1846 }
1847
1848 uint64_t BlockchainLMDB::get_txpool_tx_count(relay_category category) const
1849 {
1850 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1851 check_open();
1852
1853 int result;
1854 uint64_t num_entries = 0;
1855
1856 TXN_PREFIX_RDONLY();
1857
1858 if (category == relay_category::all)
1859 {
1860 // No filtering, we can get the number of tx the "fast" way
1861 MDB_stat db_stats;
1862 if ((result = mdb_stat(m_txn, m_txpool_meta, &db_stats)))
1863 throw0(DB_ERROR(lmdb_error("Failed to query m_txpool_meta: ", result).c_str()));
1864 num_entries = db_stats.ms_entries;
1865 }
1866 else
1867 {
1868 // Filter unrelayed tx out of the result, so we need to loop over transactions and check their meta data
1869 RCURSOR(txpool_meta);
1870 RCURSOR(txpool_blob);
1871
1872 MDB_val k;
1873 MDB_val v;
1874 MDB_cursor_op op = MDB_FIRST;
1875 while (1)
1876 {
1877 result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, op);
1878 op = MDB_NEXT;
1879 if (result == MDB_NOTFOUND)
1880 break;
1881 if (result)
1882 throw0(DB_ERROR(lmdb_error("Failed to enumerate txpool tx metadata: ", result).c_str()));
1883 const txpool_tx_meta_t &meta = *(const txpool_tx_meta_t*)v.mv_data;
1884 if (meta.matches(category))
1885 ++num_entries;
1886 }
1887 }
1888 TXN_POSTFIX_RDONLY();
1889
1890 return num_entries;
1891 }
1892
1893 bool BlockchainLMDB::txpool_has_tx(const crypto::hash& txid, relay_category tx_category) const
1894 {
1895 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1896 check_open();
1897
1898 TXN_PREFIX_RDONLY();
1899 RCURSOR(txpool_meta)
1900
1901 MDB_val k = {sizeof(txid), (void *)&txid};
1902 MDB_val v;
1903 auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
1904 if (result != 0 && result != MDB_NOTFOUND)
1905 throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta: ", result).c_str()));
1906 if (result == MDB_NOTFOUND)
1907 return false;
1908
1909 bool found = true;
1910 if (tx_category != relay_category::all)
1911 {
1912 const txpool_tx_meta_t &meta = *(const txpool_tx_meta_t*)v.mv_data;
1913 found = meta.matches(tx_category);
1914 }
1915 TXN_POSTFIX_RDONLY();
1916 return found;
1917 }
1918
1919 void BlockchainLMDB::remove_txpool_tx(const crypto::hash& txid)
1920 {
1921 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1922 check_open();
1923 mdb_txn_cursors *m_cursors = &m_wcursors;
1924
1925 CURSOR(txpool_meta)
1926 CURSOR(txpool_blob)
1927
1928 MDB_val k = {sizeof(txid), (void *)&txid};
1929 auto result = mdb_cursor_get(m_cur_txpool_meta, &k, NULL, MDB_SET);
1930 if (result != 0 && result != MDB_NOTFOUND)
1931 throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta to remove: ", result).c_str()));
1932 if (!result)
1933 {
1934 result = mdb_cursor_del(m_cur_txpool_meta, 0);
1935 if (result)
1936 throw1(DB_ERROR(lmdb_error("Error adding removal of txpool tx metadata to db transaction: ", result).c_str()));
1937 }
1938 result = mdb_cursor_get(m_cur_txpool_blob, &k, NULL, MDB_SET);
1939 if (result != 0 && result != MDB_NOTFOUND)
1940 throw1(DB_ERROR(lmdb_error("Error finding txpool tx blob to remove: ", result).c_str()));
1941 if (!result)
1942 {
1943 result = mdb_cursor_del(m_cur_txpool_blob, 0);
1944 if (result)
1945 throw1(DB_ERROR(lmdb_error("Error adding removal of txpool tx blob to db transaction: ", result).c_str()));
1946 }
1947 }
1948
1949 bool BlockchainLMDB::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const
1950 {
1951 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1952 check_open();
1953
1954 TXN_PREFIX_RDONLY();
1955 RCURSOR(txpool_meta)
1956
1957 MDB_val k = {sizeof(txid), (void *)&txid};
1958 MDB_val v;
1959 auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
1960 if (result == MDB_NOTFOUND)
1961 return false;
1962 if (result != 0)
1963 throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta: ", result).c_str()));
1964
1965 meta = *(const txpool_tx_meta_t*)v.mv_data;
1966 TXN_POSTFIX_RDONLY();
1967 return true;
1968 }
1969
1970 bool BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd, relay_category tx_category) const
1971 {
1972 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
1973 check_open();
1974
1975 TXN_PREFIX_RDONLY();
1976 RCURSOR(txpool_blob)
1977
1978 MDB_val k = {sizeof(txid), (void *)&txid};
1979 MDB_val v;
1980
1981 // if filtering, make sure those requirements are met before copying blob
1982 if (tx_category != relay_category::all)
1983 {
1984 RCURSOR(txpool_meta)
1985 auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
1986 if (result == MDB_NOTFOUND)
1987 return false;
1988 if (result != 0)
1989 throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta: ", result).c_str()));
1990
1991 const txpool_tx_meta_t& meta = *(const txpool_tx_meta_t*)v.mv_data;
1992 if (!meta.matches(tx_category))
1993 return false;
1994 }
1995
1996 auto result = mdb_cursor_get(m_cur_txpool_blob, &k, &v, MDB_SET);
1997 if (result == MDB_NOTFOUND)
1998 return false;
1999 if (result != 0)
2000 throw1(DB_ERROR(lmdb_error("Error finding txpool tx blob: ", result).c_str()));
2001
2002 bd.assign(reinterpret_cast<const char*>(v.mv_data), v.mv_size);
2003 TXN_POSTFIX_RDONLY();
2004 return true;
2005 }
2006
2007 cryptonote::blobdata BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid, relay_category tx_category) const
2008 {
2009 cryptonote::blobdata bd;
2010 if (!get_txpool_tx_blob(txid, bd, tx_category))
2011 throw1(DB_ERROR("Tx not found in txpool: "));
2012 return bd;
2013 }
2014
2015 uint32_t BlockchainLMDB::get_blockchain_pruning_seed() const
2016 {
2017 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2018 check_open();
2019
2020 TXN_PREFIX_RDONLY();
2021 RCURSOR(properties)
2022 MDB_val_str(k, "pruning_seed");
2023 MDB_val v;
2024 int result = mdb_cursor_get(m_cur_properties, &k, &v, MDB_SET);
2025 if (result == MDB_NOTFOUND)
2026 return 0;
2027 if (result)
2028 throw0(DB_ERROR(lmdb_error("Failed to retrieve pruning seed: ", result).c_str()));
2029 if (v.mv_size != sizeof(uint32_t))
2030 throw0(DB_ERROR("Failed to retrieve or create pruning seed: unexpected value size"));
2031 uint32_t pruning_seed;
2032 memcpy(&pruning_seed, v.mv_data, sizeof(pruning_seed));
2033 TXN_POSTFIX_RDONLY();
2034 return pruning_seed;
2035 }
2036
2037 static bool is_v1_tx(MDB_cursor *c_txs_pruned, MDB_val *tx_id)
2038 {
2039 MDB_val v;
2040 int ret = mdb_cursor_get(c_txs_pruned, tx_id, &v, MDB_SET);
2041 if (ret)
2042 throw0(DB_ERROR(lmdb_error("Failed to find transaction pruned data: ", ret).c_str()));
2043 if (v.mv_size == 0)
2044 throw0(DB_ERROR("Invalid transaction pruned data"));
2045 return cryptonote::is_v1_tx(cryptonote::blobdata_ref{(const char*)v.mv_data, v.mv_size});
2046 }
2047
2048 enum { prune_mode_prune, prune_mode_update, prune_mode_check };
2049
2050 bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed)
2051 {
2052 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2053 const uint32_t log_stripes = tools::get_pruning_log_stripes(pruning_seed);
2054 if (log_stripes && log_stripes != CRYPTONOTE_PRUNING_LOG_STRIPES)
2055 throw0(DB_ERROR("Pruning seed not in range"));
2056 pruning_seed = tools::get_pruning_stripe(pruning_seed);
2057 if (pruning_seed > (1ul << CRYPTONOTE_PRUNING_LOG_STRIPES))
2058 throw0(DB_ERROR("Pruning seed not in range"));
2059 check_open();
2060
2061 TIME_MEASURE_START(t);
2062
2063 size_t n_total_records = 0, n_prunable_records = 0, n_pruned_records = 0, commit_counter = 0;
2064 uint64_t n_bytes = 0;
2065
2066 mdb_txn_safe txn;
2067 auto result = mdb_txn_begin(m_env, NULL, 0, txn);
2068 if (result)
2069 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
2070
2071 MDB_stat db_stats;
2072 if ((result = mdb_stat(txn, m_txs_prunable, &db_stats)))
2073 throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable: ", result).c_str()));
2074 const size_t pages0 = db_stats.ms_branch_pages + db_stats.ms_leaf_pages + db_stats.ms_overflow_pages;
2075
2076 MDB_val_str(k, "pruning_seed");
2077 MDB_val v;
2078 result = mdb_get(txn, m_properties, &k, &v);
2079 bool prune_tip_table = false;
2080 if (result == MDB_NOTFOUND)
2081 {
2082 // not pruned yet
2083 if (mode != prune_mode_prune)
2084 {
2085 txn.abort();
2086 TIME_MEASURE_FINISH(t);
2087 MDEBUG("Pruning not enabled, nothing to do");
2088 return true;
2089 }
2090 if (pruning_seed == 0)
2091 pruning_seed = tools::get_random_stripe();
2092 pruning_seed = tools::make_pruning_seed(pruning_seed, CRYPTONOTE_PRUNING_LOG_STRIPES);
2093 v.mv_data = &pruning_seed;
2094 v.mv_size = sizeof(pruning_seed);
2095 result = mdb_put(txn, m_properties, &k, &v, 0);
2096 if (result)
2097 throw0(DB_ERROR("Failed to save pruning seed"));
2098 prune_tip_table = false;
2099 }
2100 else if (result == 0)
2101 {
2102 // pruned already
2103 if (v.mv_size != sizeof(uint32_t))
2104 throw0(DB_ERROR("Failed to retrieve or create pruning seed: unexpected value size"));
2105 const uint32_t data = *(const uint32_t*)v.mv_data;
2106 if (pruning_seed == 0)
2107 pruning_seed = tools::get_pruning_stripe(data);
2108 if (tools::get_pruning_stripe(data) != pruning_seed)
2109 throw0(DB_ERROR("Blockchain already pruned with different seed"));
2110 if (tools::get_pruning_log_stripes(data) != CRYPTONOTE_PRUNING_LOG_STRIPES)
2111 throw0(DB_ERROR("Blockchain already pruned with different base"));
2112 pruning_seed = tools::make_pruning_seed(pruning_seed, CRYPTONOTE_PRUNING_LOG_STRIPES);
2113 prune_tip_table = (mode == prune_mode_update);
2114 }
2115 else
2116 {
2117 throw0(DB_ERROR(lmdb_error("Failed to retrieve or create pruning seed: ", result).c_str()));
2118 }
2119
2120 if (mode == prune_mode_check)
2121 MINFO("Checking blockchain pruning...");
2122 else
2123 MINFO("Pruning blockchain...");
2124
2125 MDB_cursor *c_txs_pruned, *c_txs_prunable, *c_txs_prunable_tip;
2126 result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned);
2127 if (result)
2128 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
2129 result = mdb_cursor_open(txn, m_txs_prunable, &c_txs_prunable);
2130 if (result)
2131 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
2132 result = mdb_cursor_open(txn, m_txs_prunable_tip, &c_txs_prunable_tip);
2133 if (result)
2134 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_tip: ", result).c_str()));
2135 const uint64_t blockchain_height = height();
2136
2137 if (prune_tip_table)
2138 {
2139 MDB_cursor_op op = MDB_FIRST;
2140 while (1)
2141 {
2142 int ret = mdb_cursor_get(c_txs_prunable_tip, &k, &v, op);
2143 op = MDB_NEXT;
2144 if (ret == MDB_NOTFOUND)
2145 break;
2146 if (ret)
2147 throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
2148
2149 uint64_t block_height;
2150 memcpy(&block_height, v.mv_data, sizeof(block_height));
2151 if (block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS < blockchain_height)
2152 {
2153 ++n_total_records;
2154 if (!tools::has_unpruned_block(block_height, blockchain_height, pruning_seed) && !is_v1_tx(c_txs_pruned, &k))
2155 {
2156 ++n_prunable_records;
2157 result = mdb_cursor_get(c_txs_prunable, &k, &v, MDB_SET);
2158 if (result == MDB_NOTFOUND)
2159 MDEBUG("Already pruned at height " << block_height << "/" << blockchain_height);
2160 else if (result)
2161 throw0(DB_ERROR(lmdb_error("Failed to find transaction prunable data: ", result).c_str()));
2162 else
2163 {
2164 MDEBUG("Pruning at height " << block_height << "/" << blockchain_height);
2165 ++n_pruned_records;
2166 ++commit_counter;
2167 n_bytes += k.mv_size + v.mv_size;
2168 result = mdb_cursor_del(c_txs_prunable, 0);
2169 if (result)
2170 throw0(DB_ERROR(lmdb_error("Failed to delete transaction prunable data: ", result).c_str()));
2171 }
2172 }
2173 result = mdb_cursor_del(c_txs_prunable_tip, 0);
2174 if (result)
2175 throw0(DB_ERROR(lmdb_error("Failed to delete transaction tip data: ", result).c_str()));
2176
2177 if (mode != prune_mode_check && commit_counter >= 4096)
2178 {
2179 MDEBUG("Committing txn at checkpoint...");
2180 txn.commit();
2181 result = mdb_txn_begin(m_env, NULL, 0, txn);
2182 if (result)
2183 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
2184 result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned);
2185 if (result)
2186 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
2187 result = mdb_cursor_open(txn, m_txs_prunable, &c_txs_prunable);
2188 if (result)
2189 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
2190 result = mdb_cursor_open(txn, m_txs_prunable_tip, &c_txs_prunable_tip);
2191 if (result)
2192 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_tip: ", result).c_str()));
2193 commit_counter = 0;
2194 }
2195 }
2196 }
2197 }
2198 else
2199 {
2200 MDB_cursor *c_tx_indices;
2201 result = mdb_cursor_open(txn, m_tx_indices, &c_tx_indices);
2202 if (result)
2203 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for tx_indices: ", result).c_str()));
2204 MDB_cursor_op op = MDB_FIRST;
2205 while (1)
2206 {
2207 int ret = mdb_cursor_get(c_tx_indices, &k, &v, op);
2208 op = MDB_NEXT;
2209 if (ret == MDB_NOTFOUND)
2210 break;
2211 if (ret)
2212 throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
2213
2214 ++n_total_records;
2215 //const txindex *ti = (const txindex *)v.mv_data;
2216 txindex ti;
2217 memcpy(&ti, v.mv_data, sizeof(ti));
2218 const uint64_t block_height = ti.data.block_id;
2219 if (block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS >= blockchain_height)
2220 {
2221 MDB_val_set(kp, ti.data.tx_id);
2222 MDB_val_set(vp, block_height);
2223 if (mode == prune_mode_check)
2224 {
2225 result = mdb_cursor_get(c_txs_prunable_tip, &kp, &vp, MDB_SET);
2226 if (result && result != MDB_NOTFOUND)
2227 throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
2228 if (result == MDB_NOTFOUND)
2229 MERROR("Transaction not found in prunable tip table for height " << block_height << "/" << blockchain_height <<
2230 ", seed " << epee::string_tools::to_string_hex(pruning_seed));
2231 }
2232 else
2233 {
2234 result = mdb_cursor_put(c_txs_prunable_tip, &kp, &vp, 0);
2235 if (result && result != MDB_NOTFOUND)
2236 throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
2237 }
2238 }
2239 MDB_val_set(kp, ti.data.tx_id);
2240 if (!tools::has_unpruned_block(block_height, blockchain_height, pruning_seed) && !is_v1_tx(c_txs_pruned, &kp))
2241 {
2242 result = mdb_cursor_get(c_txs_prunable, &kp, &v, MDB_SET);
2243 if (result && result != MDB_NOTFOUND)
2244 throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
2245 if (mode == prune_mode_check)
2246 {
2247 if (result != MDB_NOTFOUND)
2248 MERROR("Prunable data found for pruned height " << block_height << "/" << blockchain_height <<
2249 ", seed " << epee::string_tools::to_string_hex(pruning_seed));
2250 }
2251 else
2252 {
2253 ++n_prunable_records;
2254 if (result == MDB_NOTFOUND)
2255 MDEBUG("Already pruned at height " << block_height << "/" << blockchain_height);
2256 else
2257 {
2258 MDEBUG("Pruning at height " << block_height << "/" << blockchain_height);
2259 ++n_pruned_records;
2260 n_bytes += kp.mv_size + v.mv_size;
2261 result = mdb_cursor_del(c_txs_prunable, 0);
2262 if (result)
2263 throw0(DB_ERROR(lmdb_error("Failed to delete transaction prunable data: ", result).c_str()));
2264 ++commit_counter;
2265 }
2266 }
2267 }
2268 else
2269 {
2270 if (mode == prune_mode_check)
2271 {
2272 MDB_val_set(kp, ti.data.tx_id);
2273 result = mdb_cursor_get(c_txs_prunable, &kp, &v, MDB_SET);
2274 if (result && result != MDB_NOTFOUND)
2275 throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
2276 if (result == MDB_NOTFOUND)
2277 MERROR("Prunable data not found for unpruned height " << block_height << "/" << blockchain_height <<
2278 ", seed " << epee::string_tools::to_string_hex(pruning_seed));
2279 }
2280 }
2281
2282 if (mode != prune_mode_check && commit_counter >= 4096)
2283 {
2284 MDEBUG("Committing txn at checkpoint...");
2285 txn.commit();
2286 result = mdb_txn_begin(m_env, NULL, 0, txn);
2287 if (result)
2288 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
2289 result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned);
2290 if (result)
2291 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
2292 result = mdb_cursor_open(txn, m_txs_prunable, &c_txs_prunable);
2293 if (result)
2294 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
2295 result = mdb_cursor_open(txn, m_txs_prunable_tip, &c_txs_prunable_tip);
2296 if (result)
2297 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_tip: ", result).c_str()));
2298 result = mdb_cursor_open(txn, m_tx_indices, &c_tx_indices);
2299 if (result)
2300 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for tx_indices: ", result).c_str()));
2301 MDB_val val;
2302 val.mv_size = sizeof(ti);
2303 val.mv_data = (void *)&ti;
2304 result = mdb_cursor_get(c_tx_indices, (MDB_val*)&zerokval, &val, MDB_GET_BOTH);
2305 if (result)
2306 throw0(DB_ERROR(lmdb_error("Failed to restore cursor for tx_indices: ", result).c_str()));
2307 commit_counter = 0;
2308 }
2309 }
2310 mdb_cursor_close(c_tx_indices);
2311 }
2312
2313 if ((result = mdb_stat(txn, m_txs_prunable, &db_stats)))
2314 throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable: ", result).c_str()));
2315 const size_t pages1 = db_stats.ms_branch_pages + db_stats.ms_leaf_pages + db_stats.ms_overflow_pages;
2316 const size_t db_bytes = (pages0 - pages1) * db_stats.ms_psize;
2317
2318 mdb_cursor_close(c_txs_prunable_tip);
2319 mdb_cursor_close(c_txs_prunable);
2320 mdb_cursor_close(c_txs_pruned);
2321
2322 txn.commit();
2323
2324 TIME_MEASURE_FINISH(t);
2325
2326 MINFO((mode == prune_mode_check ? "Checked" : "Pruned") << " blockchain in " <<
2327 t << " ms: " << (n_bytes/1024.0f/1024.0f) << " MB (" << db_bytes/1024.0f/1024.0f << " MB) pruned in " <<
2328 n_pruned_records << " records (" << pages0 - pages1 << "/" << pages0 << " " << db_stats.ms_psize << " byte pages), " <<
2329 n_prunable_records << "/" << n_total_records << " pruned records");
2330 return true;
2331 }
2332
2333 bool BlockchainLMDB::prune_blockchain(uint32_t pruning_seed)
2334 {
2335 return prune_worker(prune_mode_prune, pruning_seed);
2336 }
2337
2338 bool BlockchainLMDB::update_pruning()
2339 {
2340 return prune_worker(prune_mode_update, 0);
2341 }
2342
2343 bool BlockchainLMDB::check_pruning()
2344 {
2345 return prune_worker(prune_mode_check, 0);
2346 }
2347
2348 bool BlockchainLMDB::for_all_txpool_txes(std::function<bool(const crypto::hash&, const txpool_tx_meta_t&, const cryptonote::blobdata_ref*)> f, bool include_blob, relay_category category) const
2349 {
2350 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2351 check_open();
2352
2353 TXN_PREFIX_RDONLY();
2354 RCURSOR(txpool_meta);
2355 RCURSOR(txpool_blob);
2356
2357 MDB_val k;
2358 MDB_val v;
2359 bool ret = true;
2360
2361 MDB_cursor_op op = MDB_FIRST;
2362 while (1)
2363 {
2364 int result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, op);
2365 op = MDB_NEXT;
2366 if (result == MDB_NOTFOUND)
2367 break;
2368 if (result)
2369 throw0(DB_ERROR(lmdb_error("Failed to enumerate txpool tx metadata: ", result).c_str()));
2370 const crypto::hash txid = *(const crypto::hash*)k.mv_data;
2371 const txpool_tx_meta_t &meta = *(const txpool_tx_meta_t*)v.mv_data;
2372 if (!meta.matches(category))
2373 continue;
2374 cryptonote::blobdata_ref bd;
2375 if (include_blob)
2376 {
2377 MDB_val b;
2378 result = mdb_cursor_get(m_cur_txpool_blob, &k, &b, MDB_SET);
2379 if (result == MDB_NOTFOUND)
2380 throw0(DB_ERROR("Failed to find txpool tx blob to match metadata"));
2381 if (result)
2382 throw0(DB_ERROR(lmdb_error("Failed to enumerate txpool tx blob: ", result).c_str()));
2383 bd = {reinterpret_cast<const char*>(b.mv_data), b.mv_size};
2384 }
2385
2386 if (!f(txid, meta, &bd)) {
2387 ret = false;
2388 break;
2389 }
2390 }
2391
2392 TXN_POSTFIX_RDONLY();
2393
2394 return ret;
2395 }
2396
2397 bool BlockchainLMDB::for_all_alt_blocks(std::function<bool(const crypto::hash&, const alt_block_data_t&, const cryptonote::blobdata_ref*)> f, bool include_blob) const
2398 {
2399 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2400 check_open();
2401
2402 TXN_PREFIX_RDONLY();
2403 RCURSOR(alt_blocks);
2404
2405 MDB_val k;
2406 MDB_val v;
2407 bool ret = true;
2408
2409 MDB_cursor_op op = MDB_FIRST;
2410 while (1)
2411 {
2412 int result = mdb_cursor_get(m_cur_alt_blocks, &k, &v, op);
2413 op = MDB_NEXT;
2414 if (result == MDB_NOTFOUND)
2415 break;
2416 if (result)
2417 throw0(DB_ERROR(lmdb_error("Failed to enumerate alt blocks: ", result).c_str()));
2418 const crypto::hash &blkid = *(const crypto::hash*)k.mv_data;
2419 if (v.mv_size < sizeof(alt_block_data_t))
2420 throw0(DB_ERROR("alt_blocks record is too small"));
2421 const alt_block_data_t *data = (const alt_block_data_t*)v.mv_data;
2422 cryptonote::blobdata_ref bd;
2423 if (include_blob)
2424 {
2425 bd = {reinterpret_cast<const char*>(v.mv_data) + sizeof(alt_block_data_t), v.mv_size - sizeof(alt_block_data_t)};
2426 }
2427
2428 if (!f(blkid, *data, &bd)) {
2429 ret = false;
2430 break;
2431 }
2432 }
2433
2434 TXN_POSTFIX_RDONLY();
2435
2436 return ret;
2437 }
2438
2439 bool BlockchainLMDB::block_exists(const crypto::hash& h, uint64_t *height) const
2440 {
2441 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2442 check_open();
2443
2444 TXN_PREFIX_RDONLY();
2445 RCURSOR(block_heights);
2446
2447 bool ret = false;
2448 MDB_val_set(key, h);
2449 auto get_result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
2450 if (get_result == MDB_NOTFOUND)
2451 {
2452 LOG_PRINT_L3("Block with hash " << epee::string_tools::pod_to_hex(h) << " not found in db");
2453 }
2454 else if (get_result)
2455 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch block index from hash", get_result).c_str()));
2456 else
2457 {
2458 if (height)
2459 {
2460 const blk_height *bhp = (const blk_height *)key.mv_data;
2461 *height = bhp->bh_height;
2462 }
2463 ret = true;
2464 }
2465
2466 TXN_POSTFIX_RDONLY();
2467 return ret;
2468 }
2469
2470 cryptonote::blobdata BlockchainLMDB::get_block_blob(const crypto::hash& h) const
2471 {
2472 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2473 check_open();
2474
2475 return get_block_blob_from_height(get_block_height(h));
2476 }
2477
2478 uint64_t BlockchainLMDB::get_block_height(const crypto::hash& h) const
2479 {
2480 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2481 check_open();
2482
2483 TXN_PREFIX_RDONLY();
2484 RCURSOR(block_heights);
2485
2486 MDB_val_set(key, h);
2487 auto get_result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
2488 if (get_result == MDB_NOTFOUND)
2489 throw1(BLOCK_DNE("Attempted to retrieve non-existent block height"));
2490 else if (get_result)
2491 throw0(DB_ERROR("Error attempting to retrieve a block height from the db"));
2492
2493 blk_height *bhp = (blk_height *)key.mv_data;
2494 uint64_t ret = bhp->bh_height;
2495 TXN_POSTFIX_RDONLY();
2496 return ret;
2497 }
2498
2499 block_header BlockchainLMDB::get_block_header(const crypto::hash& h) const
2500 {
2501 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2502 check_open();
2503
2504 // block_header object is automatically cast from block object
2505 return get_block(h);
2506 }
2507
2508 cryptonote::blobdata BlockchainLMDB::get_block_blob_from_height(const uint64_t& height) const
2509 {
2510 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2511 check_open();
2512
2513 TXN_PREFIX_RDONLY();
2514 RCURSOR(blocks);
2515
2516 MDB_val_copy<uint64_t> key(height);
2517 MDB_val result;
2518 auto get_result = mdb_cursor_get(m_cur_blocks, &key, &result, MDB_SET);
2519 if (get_result == MDB_NOTFOUND)
2520 {
2521 throw0(BLOCK_DNE(std::string("Attempt to get block from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block not in db").c_str()));
2522 }
2523 else if (get_result)
2524 throw0(DB_ERROR("Error attempting to retrieve a block from the db"));
2525
2526 blobdata bd;
2527 bd.assign(reinterpret_cast<char*>(result.mv_data), result.mv_size);
2528
2529 TXN_POSTFIX_RDONLY();
2530
2531 return bd;
2532 }
2533
2534 uint64_t BlockchainLMDB::get_block_timestamp(const uint64_t& height) const
2535 {
2536 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2537 check_open();
2538
2539 TXN_PREFIX_RDONLY();
2540 RCURSOR(block_info);
2541
2542 MDB_val_set(result, height);
2543 auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
2544 if (get_result == MDB_NOTFOUND)
2545 {
2546 throw0(BLOCK_DNE(std::string("Attempt to get timestamp from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- timestamp not in db").c_str()));
2547 }
2548 else if (get_result)
2549 throw0(DB_ERROR("Error attempting to retrieve a timestamp from the db"));
2550
2551 mdb_block_info *bi = (mdb_block_info *)result.mv_data;
2552 uint64_t ret = bi->bi_timestamp;
2553 TXN_POSTFIX_RDONLY();
2554 return ret;
2555 }
2556
2557 std::vector<uint64_t> BlockchainLMDB::get_block_cumulative_rct_outputs(const std::vector<uint64_t> &heights) const
2558 {
2559 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2560 check_open();
2561 std::vector<uint64_t> res;
2562 int result;
2563
2564 if (heights.empty())
2565 return {};
2566 res.reserve(heights.size());
2567
2568 TXN_PREFIX_RDONLY();
2569 RCURSOR(block_info);
2570
2571 MDB_stat db_stats;
2572 if ((result = mdb_stat(m_txn, m_blocks, &db_stats)))
2573 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
2574 for (size_t i = 0; i < heights.size(); ++i)
2575 if (heights[i] >= db_stats.ms_entries)
2576 throw0(BLOCK_DNE(std::string("Attempt to get rct distribution from height " + std::to_string(heights[i]) + " failed -- block size not in db").c_str()));
2577
2578 MDB_val v;
2579
2580 uint64_t prev_height = heights[0];
2581 uint64_t range_begin = 0, range_end = 0;
2582 for (uint64_t height: heights)
2583 {
2584 if (height >= range_begin && height < range_end)
2585 {
2586 // nohting to do
2587 }
2588 else
2589 {
2590 if (height == prev_height + 1)
2591 {
2592 MDB_val k2;
2593 result = mdb_cursor_get(m_cur_block_info, &k2, &v, MDB_NEXT_MULTIPLE);
2594 range_begin = ((const mdb_block_info*)v.mv_data)->bi_height;
2595 range_end = range_begin + v.mv_size / sizeof(mdb_block_info); // whole records please
2596 if (height < range_begin || height >= range_end)
2597 throw0(DB_ERROR(("Height " + std::to_string(height) + " not included in multuple record range: " + std::to_string(range_begin) + "-" + std::to_string(range_end)).c_str()));
2598 }
2599 else
2600 {
2601 v.mv_size = sizeof(uint64_t);
2602 v.mv_data = (void*)&height;
2603 result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
2604 range_begin = height;
2605 range_end = range_begin + 1;
2606 }
2607 if (result)
2608 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve rct distribution from the db: ", result).c_str()));
2609 }
2610 const mdb_block_info *bi = ((const mdb_block_info *)v.mv_data) + (height - range_begin);
2611 res.push_back(bi->bi_cum_rct);
2612 prev_height = height;
2613 }
2614
2615 TXN_POSTFIX_RDONLY();
2616 return res;
2617 }
2618
2619 uint64_t BlockchainLMDB::get_top_block_timestamp() const
2620 {
2621 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2622 check_open();
2623 uint64_t m_height = height();
2624
2625 // if no blocks, return 0
2626 if (m_height == 0)
2627 {
2628 return 0;
2629 }
2630
2631 return get_block_timestamp(m_height - 1);
2632 }
2633
2634 size_t BlockchainLMDB::get_block_weight(const uint64_t& height) const
2635 {
2636 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2637 check_open();
2638
2639 TXN_PREFIX_RDONLY();
2640 RCURSOR(block_info);
2641
2642 MDB_val_set(result, height);
2643 auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
2644 if (get_result == MDB_NOTFOUND)
2645 {
2646 throw0(BLOCK_DNE(std::string("Attempt to get block size from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block size not in db").c_str()));
2647 }
2648 else if (get_result)
2649 throw0(DB_ERROR("Error attempting to retrieve a block size from the db"));
2650
2651 mdb_block_info *bi = (mdb_block_info *)result.mv_data;
2652 size_t ret = bi->bi_weight;
2653 TXN_POSTFIX_RDONLY();
2654 return ret;
2655 }
2656
2657 std::vector<uint64_t> BlockchainLMDB::get_block_info_64bit_fields(uint64_t start_height, size_t count, off_t offset) const
2658 {
2659 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2660 check_open();
2661
2662 TXN_PREFIX_RDONLY();
2663 RCURSOR(block_info);
2664
2665 const uint64_t h = height();
2666 if (start_height >= h)
2667 throw0(DB_ERROR(("Height " + std::to_string(start_height) + " not in blockchain").c_str()));
2668
2669 std::vector<uint64_t> ret;
2670 ret.reserve(count);
2671
2672 MDB_val v;
2673 uint64_t range_begin = 0, range_end = 0;
2674 for (uint64_t height = start_height; height < h && count--; ++height)
2675 {
2676 if (height >= range_begin && height < range_end)
2677 {
2678 // nothing to do
2679 }
2680 else
2681 {
2682 int result = 0;
2683 if (range_end > 0)
2684 {
2685 MDB_val k2;
2686 result = mdb_cursor_get(m_cur_block_info, &k2, &v, MDB_NEXT_MULTIPLE);
2687 range_begin = ((const mdb_block_info*)v.mv_data)->bi_height;
2688 range_end = range_begin + v.mv_size / sizeof(mdb_block_info); // whole records please
2689 if (height < range_begin || height >= range_end)
2690 throw0(DB_ERROR(("Height " + std::to_string(height) + " not included in multiple record range: " + std::to_string(range_begin) + "-" + std::to_string(range_end)).c_str()));
2691 }
2692 else
2693 {
2694 v.mv_size = sizeof(uint64_t);
2695 v.mv_data = (void*)&height;
2696 result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
2697 range_begin = height;
2698 range_end = range_begin + 1;
2699 }
2700 if (result)
2701 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve block_info from the db: ", result).c_str()));
2702 }
2703 const mdb_block_info *bi = ((const mdb_block_info *)v.mv_data) + (height - range_begin);
2704 ret.push_back(*(const uint64_t*)(((const char*)bi) + offset));
2705 }
2706
2707 TXN_POSTFIX_RDONLY();
2708 return ret;
2709 }
2710
2711 uint64_t BlockchainLMDB::get_max_block_size()
2712 {
2713 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2714 check_open();
2715
2716 TXN_PREFIX_RDONLY();
2717 RCURSOR(properties)
2718 MDB_val_str(k, "max_block_size");
2719 MDB_val v;
2720 int result = mdb_cursor_get(m_cur_properties, &k, &v, MDB_SET);
2721 if (result == MDB_NOTFOUND)
2722 return std::numeric_limits<uint64_t>::max();
2723 if (result)
2724 throw0(DB_ERROR(lmdb_error("Failed to retrieve max block size: ", result).c_str()));
2725 if (v.mv_size != sizeof(uint64_t))
2726 throw0(DB_ERROR("Failed to retrieve or create max block size: unexpected value size"));
2727 uint64_t max_block_size;
2728 memcpy(&max_block_size, v.mv_data, sizeof(max_block_size));
2729 TXN_POSTFIX_RDONLY();
2730 return max_block_size;
2731 }
2732
2733 void BlockchainLMDB::add_max_block_size(uint64_t sz)
2734 {
2735 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2736 check_open();
2737 mdb_txn_cursors *m_cursors = &m_wcursors;
2738
2739 CURSOR(properties)
2740
2741 MDB_val_str(k, "max_block_size");
2742 MDB_val v;
2743 int result = mdb_cursor_get(m_cur_properties, &k, &v, MDB_SET);
2744 if (result && result != MDB_NOTFOUND)
2745 throw0(DB_ERROR(lmdb_error("Failed to retrieve max block size: ", result).c_str()));
2746 uint64_t max_block_size = 0;
2747 if (result == 0)
2748 {
2749 if (v.mv_size != sizeof(uint64_t))
2750 throw0(DB_ERROR("Failed to retrieve or create max block size: unexpected value size"));
2751 memcpy(&max_block_size, v.mv_data, sizeof(max_block_size));
2752 }
2753 if (sz > max_block_size)
2754 max_block_size = sz;
2755 v.mv_data = (void*)&max_block_size;
2756 v.mv_size = sizeof(max_block_size);
2757 result = mdb_cursor_put(m_cur_properties, &k, &v, 0);
2758 if (result)
2759 throw0(DB_ERROR(lmdb_error("Failed to set max_block_size: ", result).c_str()));
2760 }
2761
2762
2763 std::vector<uint64_t> BlockchainLMDB::get_block_weights(uint64_t start_height, size_t count) const
2764 {
2765 return get_block_info_64bit_fields(start_height, count, offsetof(mdb_block_info, bi_weight));
2766 }
2767
2768 std::vector<uint64_t> BlockchainLMDB::get_long_term_block_weights(uint64_t start_height, size_t count) const
2769 {
2770 return get_block_info_64bit_fields(start_height, count, offsetof(mdb_block_info, bi_long_term_block_weight));
2771 }
2772
2773 difficulty_type BlockchainLMDB::get_block_cumulative_difficulty(const uint64_t& height) const
2774 {
2775 LOG_PRINT_L3("BlockchainLMDB::" << __func__ << " height: " << height);
2776 check_open();
2777
2778 TXN_PREFIX_RDONLY();
2779 RCURSOR(block_info);
2780
2781 MDB_val_set(result, height);
2782 auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
2783 if (get_result == MDB_NOTFOUND)
2784 {
2785 throw0(BLOCK_DNE(std::string("Attempt to get cumulative difficulty from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- difficulty not in db").c_str()));
2786 }
2787 else if (get_result)
2788 throw0(DB_ERROR("Error attempting to retrieve a cumulative difficulty from the db"));
2789
2790 mdb_block_info *bi = (mdb_block_info *)result.mv_data;
2791 difficulty_type ret = bi->bi_diff_hi;
2792 ret <<= 64;
2793 ret |= bi->bi_diff_lo;
2794 TXN_POSTFIX_RDONLY();
2795 return ret;
2796 }
2797
2798 difficulty_type BlockchainLMDB::get_block_difficulty(const uint64_t& height) const
2799 {
2800 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2801 check_open();
2802
2803 difficulty_type diff1 = 0;
2804 difficulty_type diff2 = 0;
2805
2806 diff1 = get_block_cumulative_difficulty(height);
2807 if (height != 0)
2808 {
2809 diff2 = get_block_cumulative_difficulty(height - 1);
2810 }
2811
2812 return diff1 - diff2;
2813 }
2814
2815 void BlockchainLMDB::correct_block_cumulative_difficulties(const uint64_t& start_height, const std::vector<difficulty_type>& new_cumulative_difficulties)
2816 {
2817 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2818 check_open();
2819 mdb_txn_cursors *m_cursors = &m_wcursors;
2820
2821 int result = 0;
2822 block_wtxn_start();
2823 CURSOR(block_info)
2824
2825 const uint64_t bc_height = height();
2826 if (start_height + new_cumulative_difficulties.size() != bc_height)
2827 {
2828 block_wtxn_abort();
2829 throw0(DB_ERROR("Incorrect new_cumulative_difficulties size"));
2830 }
2831
2832 for (uint64_t height = start_height; height < bc_height; ++height)
2833 {
2834 MDB_val_set(key, height);
2835 result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
2836 if (result)
2837 throw1(BLOCK_DNE(lmdb_error("Failed to get block info: ", result).c_str()));
2838
2839 mdb_block_info bi = *(mdb_block_info*)key.mv_data;
2840 const difficulty_type d = new_cumulative_difficulties[height - start_height];
2841 bi.bi_diff_hi = ((d >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
2842 bi.bi_diff_lo = (d & 0xffffffffffffffff).convert_to<uint64_t>();
2843
2844 MDB_val_set(key2, height);
2845 MDB_val_set(val, bi);
2846 result = mdb_cursor_put(m_cur_block_info, &key2, &val, MDB_CURRENT);
2847 if (result)
2848 throw0(DB_ERROR(lmdb_error("Failed to overwrite block info to db transaction: ", result).c_str()));
2849 }
2850 block_wtxn_stop();
2851 }
2852
2853 uint64_t BlockchainLMDB::get_block_already_generated_coins(const uint64_t& height) const
2854 {
2855 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2856 check_open();
2857
2858 TXN_PREFIX_RDONLY();
2859 RCURSOR(block_info);
2860
2861 MDB_val_set(result, height);
2862 auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
2863 if (get_result == MDB_NOTFOUND)
2864 {
2865 throw0(BLOCK_DNE(std::string("Attempt to get generated coins from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block size not in db").c_str()));
2866 }
2867 else if (get_result)
2868 throw0(DB_ERROR("Error attempting to retrieve a total generated coins from the db"));
2869
2870 mdb_block_info *bi = (mdb_block_info *)result.mv_data;
2871 uint64_t ret = bi->bi_coins;
2872 TXN_POSTFIX_RDONLY();
2873 return ret;
2874 }
2875
2876 uint64_t BlockchainLMDB::get_block_long_term_weight(const uint64_t& height) const
2877 {
2878 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2879 check_open();
2880
2881 TXN_PREFIX_RDONLY();
2882 RCURSOR(block_info);
2883
2884 MDB_val_set(result, height);
2885 auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
2886 if (get_result == MDB_NOTFOUND)
2887 {
2888 throw0(BLOCK_DNE(std::string("Attempt to get block long term weight from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block info not in db").c_str()));
2889 }
2890 else if (get_result)
2891 throw0(DB_ERROR("Error attempting to retrieve a long term block weight from the db"));
2892
2893 mdb_block_info *bi = (mdb_block_info *)result.mv_data;
2894 uint64_t ret = bi->bi_long_term_block_weight;
2895 TXN_POSTFIX_RDONLY();
2896 return ret;
2897 }
2898
2899 crypto::hash BlockchainLMDB::get_block_hash_from_height(const uint64_t& height) const
2900 {
2901 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2902 check_open();
2903
2904 TXN_PREFIX_RDONLY();
2905 RCURSOR(block_info);
2906
2907 MDB_val_set(result, height);
2908 auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
2909 if (get_result == MDB_NOTFOUND)
2910 {
2911 throw0(BLOCK_DNE(std::string("Attempt to get hash from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- hash not in db").c_str()));
2912 }
2913 else if (get_result)
2914 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve a block hash from the db: ", get_result).c_str()));
2915
2916 mdb_block_info *bi = (mdb_block_info *)result.mv_data;
2917 crypto::hash ret = bi->bi_hash;
2918 TXN_POSTFIX_RDONLY();
2919 return ret;
2920 }
2921
2922 std::vector<block> BlockchainLMDB::get_blocks_range(const uint64_t& h1, const uint64_t& h2) const
2923 {
2924 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2925 check_open();
2926 std::vector<block> v;
2927
2928 for (uint64_t height = h1; height <= h2; ++height)
2929 {
2930 v.push_back(get_block_from_height(height));
2931 }
2932
2933 return v;
2934 }
2935
2936 std::vector<crypto::hash> BlockchainLMDB::get_hashes_range(const uint64_t& h1, const uint64_t& h2) const
2937 {
2938 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2939 check_open();
2940 std::vector<crypto::hash> v;
2941
2942 for (uint64_t height = h1; height <= h2; ++height)
2943 {
2944 v.push_back(get_block_hash_from_height(height));
2945 }
2946
2947 return v;
2948 }
2949
2950 crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const
2951 {
2952 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2953 check_open();
2954 uint64_t m_height = height();
2955 if (block_height)
2956 *block_height = m_height - 1;
2957 if (m_height != 0)
2958 {
2959 return get_block_hash_from_height(m_height - 1);
2960 }
2961
2962 return null_hash;
2963 }
2964
2965 block BlockchainLMDB::get_top_block() const
2966 {
2967 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2968 check_open();
2969 uint64_t m_height = height();
2970
2971 if (m_height != 0)
2972 {
2973 return get_block_from_height(m_height - 1);
2974 }
2975
2976 block b;
2977 return b;
2978 }
2979
2980 uint64_t BlockchainLMDB::height() const
2981 {
2982 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2983 check_open();
2984 TXN_PREFIX_RDONLY();
2985 int result;
2986
2987 // get current height
2988 MDB_stat db_stats;
2989 if ((result = mdb_stat(m_txn, m_blocks, &db_stats)))
2990 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
2991 return db_stats.ms_entries;
2992 }
2993
2994 uint64_t BlockchainLMDB::num_outputs() const
2995 {
2996 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
2997 check_open();
2998 TXN_PREFIX_RDONLY();
2999 int result;
3000
3001 RCURSOR(output_txs)
3002
3003 uint64_t num = 0;
3004 MDB_val k, v;
3005 result = mdb_cursor_get(m_cur_output_txs, &k, &v, MDB_LAST);
3006 if (result == MDB_NOTFOUND)
3007 num = 0;
3008 else if (result == 0)
3009 num = 1 + ((const outtx*)v.mv_data)->output_id;
3010 else
3011 throw0(DB_ERROR(lmdb_error("Failed to query m_output_txs: ", result).c_str()));
3012
3013 return num;
3014 }
3015
3016 bool BlockchainLMDB::tx_exists(const crypto::hash& h) const
3017 {
3018 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3019 check_open();
3020
3021 TXN_PREFIX_RDONLY();
3022 RCURSOR(tx_indices);
3023
3024 MDB_val_set(key, h);
3025 bool tx_found = false;
3026
3027 TIME_MEASURE_START(time1);
3028 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
3029 if (get_result == 0)
3030 tx_found = true;
3031 else if (get_result != MDB_NOTFOUND)
3032 throw0(DB_ERROR(lmdb_error(std::string("DB error attempting to fetch transaction index from hash ") + epee::string_tools::pod_to_hex(h) + ": ", get_result).c_str()));
3033
3034 TIME_MEASURE_FINISH(time1);
3035 time_tx_exists += time1;
3036
3037 TXN_POSTFIX_RDONLY();
3038
3039 if (! tx_found)
3040 {
3041 LOG_PRINT_L3("transaction with hash " << epee::string_tools::pod_to_hex(h) << " not found in db");
3042 return false;
3043 }
3044
3045 return true;
3046 }
3047
3048 bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const
3049 {
3050 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3051 check_open();
3052
3053 TXN_PREFIX_RDONLY();
3054 RCURSOR(tx_indices);
3055
3056 MDB_val_set(v, h);
3057
3058 TIME_MEASURE_START(time1);
3059 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3060 TIME_MEASURE_FINISH(time1);
3061 time_tx_exists += time1;
3062 if (!get_result) {
3063 txindex *tip = (txindex *)v.mv_data;
3064 tx_id = tip->data.tx_id;
3065 }
3066
3067 TXN_POSTFIX_RDONLY();
3068
3069 bool ret = false;
3070 if (get_result == MDB_NOTFOUND)
3071 {
3072 LOG_PRINT_L3("transaction with hash " << epee::string_tools::pod_to_hex(h) << " not found in db");
3073 }
3074 else if (get_result)
3075 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch transaction from hash", get_result).c_str()));
3076 else
3077 ret = true;
3078
3079 return ret;
3080 }
3081
3082 uint64_t BlockchainLMDB::get_tx_unlock_time(const crypto::hash& h) const
3083 {
3084 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3085 check_open();
3086
3087 TXN_PREFIX_RDONLY();
3088 RCURSOR(tx_indices);
3089
3090 MDB_val_set(v, h);
3091 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3092 if (get_result == MDB_NOTFOUND)
3093 throw1(TX_DNE(lmdb_error(std::string("tx data with hash ") + epee::string_tools::pod_to_hex(h) + " not found in db: ", get_result).c_str()));
3094 else if (get_result)
3095 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx data from hash: ", get_result).c_str()));
3096
3097 txindex *tip = (txindex *)v.mv_data;
3098 uint64_t ret = tip->data.unlock_time;
3099 TXN_POSTFIX_RDONLY();
3100 return ret;
3101 }
3102
3103 bool BlockchainLMDB::get_tx_blob(const crypto::hash& h, cryptonote::blobdata &bd) const
3104 {
3105 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3106 check_open();
3107
3108 TXN_PREFIX_RDONLY();
3109 RCURSOR(tx_indices);
3110 RCURSOR(txs_pruned);
3111 RCURSOR(txs_prunable);
3112
3113 MDB_val_set(v, h);
3114 MDB_val result0, result1;
3115 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3116 if (get_result == 0)
3117 {
3118 txindex *tip = (txindex *)v.mv_data;
3119 MDB_val_set(val_tx_id, tip->data.tx_id);
3120 get_result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &result0, MDB_SET);
3121 if (get_result == 0)
3122 {
3123 get_result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &result1, MDB_SET);
3124 }
3125 }
3126 if (get_result == MDB_NOTFOUND)
3127 return false;
3128 else if (get_result)
3129 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", get_result).c_str()));
3130
3131 bd.assign(reinterpret_cast<char*>(result0.mv_data), result0.mv_size);
3132 bd.append(reinterpret_cast<char*>(result1.mv_data), result1.mv_size);
3133
3134 TXN_POSTFIX_RDONLY();
3135
3136 return true;
3137 }
3138
3139 bool BlockchainLMDB::get_pruned_tx_blob(const crypto::hash& h, cryptonote::blobdata &bd) const
3140 {
3141 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3142 check_open();
3143
3144 TXN_PREFIX_RDONLY();
3145 RCURSOR(tx_indices);
3146 RCURSOR(txs_pruned);
3147
3148 MDB_val_set(v, h);
3149 MDB_val result;
3150 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3151 if (get_result == 0)
3152 {
3153 txindex *tip = (txindex *)v.mv_data;
3154 MDB_val_set(val_tx_id, tip->data.tx_id);
3155 get_result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &result, MDB_SET);
3156 }
3157 if (get_result == MDB_NOTFOUND)
3158 return false;
3159 else if (get_result)
3160 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", get_result).c_str()));
3161
3162 bd.assign(reinterpret_cast<char*>(result.mv_data), result.mv_size);
3163
3164 TXN_POSTFIX_RDONLY();
3165
3166 return true;
3167 }
3168
3169 bool BlockchainLMDB::get_pruned_tx_blobs_from(const crypto::hash& h, size_t count, std::vector<cryptonote::blobdata> &bd) const
3170 {
3171 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3172 check_open();
3173
3174 if (!count)
3175 return true;
3176
3177 TXN_PREFIX_RDONLY();
3178 RCURSOR(tx_indices);
3179 RCURSOR(txs_pruned);
3180
3181 bd.reserve(bd.size() + count);
3182
3183 MDB_val_set(v, h);
3184 MDB_val result;
3185 int res = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3186 if (res == MDB_NOTFOUND)
3187 return false;
3188 if (res)
3189 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", res).c_str()));
3190
3191 const txindex *tip = (const txindex *)v.mv_data;
3192 const uint64_t id = tip->data.tx_id;
3193 MDB_val_set(val_tx_id, id);
3194 MDB_cursor_op op = MDB_SET;
3195 while (count--)
3196 {
3197 res = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &result, op);
3198 op = MDB_NEXT;
3199 if (res == MDB_NOTFOUND)
3200 return false;
3201 if (res)
3202 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx blob", res).c_str()));
3203 bd.emplace_back(reinterpret_cast<char*>(result.mv_data), result.mv_size);
3204 }
3205
3206 TXN_POSTFIX_RDONLY();
3207
3208 return true;
3209 }
3210
3211 bool BlockchainLMDB::get_blocks_from(uint64_t start_height, size_t min_block_count, size_t max_block_count, size_t max_tx_count, size_t max_size, std::vector<std::pair<std::pair<cryptonote::blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, cryptonote::blobdata>>>>& blocks, bool pruned, bool skip_coinbase, bool get_miner_tx_hash) const
3212 {
3213 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3214 check_open();
3215
3216 TXN_PREFIX_RDONLY();
3217 RCURSOR(blocks);
3218 RCURSOR(tx_indices);
3219 RCURSOR(txs_pruned);
3220 if (!pruned)
3221 {
3222 RCURSOR(txs_prunable);
3223 }
3224
3225 blocks.reserve(std::min<size_t>(max_block_count, 10000)); // guard against very large max count if only checking bytes
3226 const uint64_t blockchain_height = height();
3227 uint64_t size = 0;
3228 size_t num_txes = 0;
3229 MDB_val_copy<uint64_t> key(start_height);
3230 MDB_val v, val_tx_id;
3231 uint64_t tx_id = ~0;
3232 for (uint64_t h = start_height; h < blockchain_height && blocks.size() < max_block_count && (size < max_size || blocks.size() < min_block_count); ++h)
3233 {
3234 MDB_cursor_op op = h == start_height ? MDB_SET : MDB_NEXT;
3235 int result = mdb_cursor_get(m_cur_blocks, &key, &v, op);
3236 if (result == MDB_NOTFOUND)
3237 throw0(BLOCK_DNE(std::string("Attempt to get block from height ").append(boost::lexical_cast<std::string>(h)).append(" failed -- block not in db").c_str()));
3238 else if (result)
3239 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve a block from the db", result).c_str()));
3240
3241 blocks.resize(blocks.size() + 1);
3242 auto &current_block = blocks.back();
3243
3244 current_block.first.first.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
3245 size += v.mv_size;
3246
3247 cryptonote::block b;
3248 if (!parse_and_validate_block_from_blob(current_block.first.first, b))
3249 throw0(DB_ERROR("Invalid block"));
3250 current_block.first.second = get_miner_tx_hash ? cryptonote::get_transaction_hash(b.miner_tx) : crypto::null_hash;
3251
3252 // get the tx_id for the first tx (the first block's coinbase tx)
3253 if (h == start_height)
3254 {
3255 crypto::hash hash = cryptonote::get_transaction_hash(b.miner_tx);
3256 MDB_val_set(v, hash);
3257 result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3258 if (result)
3259 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve block coinbase transaction from the db: ", result).c_str()));
3260
3261 const txindex *tip = (const txindex *)v.mv_data;
3262 tx_id = tip->data.tx_id;
3263 val_tx_id.mv_data = &tx_id;
3264 val_tx_id.mv_size = sizeof(tx_id);
3265 }
3266
3267 if (skip_coinbase)
3268 {
3269 result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &v, op);
3270 if (result)
3271 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
3272 if (!pruned)
3273 {
3274 result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &v, op);
3275 if (result)
3276 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
3277 }
3278 }
3279
3280 op = MDB_NEXT;
3281
3282 current_block.second.reserve(b.tx_hashes.size());
3283 num_txes += b.tx_hashes.size() + (skip_coinbase ? 0 : 1);
3284 for (const auto &tx_hash: b.tx_hashes)
3285 {
3286 // get pruned data
3287 cryptonote::blobdata tx_blob;
3288 result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &v, op);
3289 if (result)
3290 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
3291 tx_blob.assign((const char*)v.mv_data, v.mv_size);
3292
3293 if (!pruned)
3294 {
3295 result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &v, op);
3296 if (result)
3297 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
3298 tx_blob.append(reinterpret_cast<const char*>(v.mv_data), v.mv_size);
3299 }
3300 current_block.second.push_back(std::make_pair(tx_hash, std::move(tx_blob)));
3301 size += current_block.second.back().second.size();
3302 }
3303
3304 if (blocks.size() >= min_block_count && num_txes >= max_tx_count)
3305 break;
3306 }
3307
3308 TXN_POSTFIX_RDONLY();
3309
3310 return true;
3311 }
3312
3313 bool BlockchainLMDB::get_prunable_tx_blob(const crypto::hash& h, cryptonote::blobdata &bd) const
3314 {
3315 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3316 check_open();
3317
3318 TXN_PREFIX_RDONLY();
3319 RCURSOR(tx_indices);
3320 RCURSOR(txs_prunable);
3321
3322 MDB_val_set(v, h);
3323 MDB_val result;
3324 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3325 if (get_result == 0)
3326 {
3327 const txindex *tip = (const txindex *)v.mv_data;
3328 MDB_val_set(val_tx_id, tip->data.tx_id);
3329 get_result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &result, MDB_SET);
3330 }
3331 if (get_result == MDB_NOTFOUND)
3332 return false;
3333 else if (get_result)
3334 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", get_result).c_str()));
3335
3336 bd.assign(reinterpret_cast<char*>(result.mv_data), result.mv_size);
3337
3338 TXN_POSTFIX_RDONLY();
3339
3340 return true;
3341 }
3342
3343 bool BlockchainLMDB::get_prunable_tx_hash(const crypto::hash& tx_hash, crypto::hash &prunable_hash) const
3344 {
3345 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3346 check_open();
3347
3348 TXN_PREFIX_RDONLY();
3349 RCURSOR(tx_indices);
3350 RCURSOR(txs_prunable_hash);
3351
3352 MDB_val_set(v, tx_hash);
3353 MDB_val result;
3354 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3355 if (get_result == 0)
3356 {
3357 txindex *tip = (txindex *)v.mv_data;
3358 MDB_val_set(val_tx_id, tip->data.tx_id);
3359 get_result = mdb_cursor_get(m_cur_txs_prunable_hash, &val_tx_id, &result, MDB_SET);
3360 }
3361 if (get_result == MDB_NOTFOUND)
3362 return false;
3363 else if (get_result)
3364 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx prunable hash from tx hash", get_result).c_str()));
3365
3366 prunable_hash = *(const crypto::hash*)result.mv_data;
3367
3368 TXN_POSTFIX_RDONLY();
3369
3370 return true;
3371 }
3372
3373 uint64_t BlockchainLMDB::get_tx_count() const
3374 {
3375 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3376 check_open();
3377
3378 TXN_PREFIX_RDONLY();
3379 int result;
3380
3381 MDB_stat db_stats;
3382 if ((result = mdb_stat(m_txn, m_txs_pruned, &db_stats)))
3383 throw0(DB_ERROR(lmdb_error("Failed to query m_txs_pruned: ", result).c_str()));
3384
3385 TXN_POSTFIX_RDONLY();
3386
3387 return db_stats.ms_entries;
3388 }
3389
3390 std::vector<transaction> BlockchainLMDB::get_tx_list(const std::vector<crypto::hash>& hlist) const
3391 {
3392 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3393 check_open();
3394 std::vector<transaction> v;
3395
3396 for (auto& h : hlist)
3397 {
3398 v.push_back(get_tx(h));
3399 }
3400
3401 return v;
3402 }
3403
3404 uint64_t BlockchainLMDB::get_tx_block_height(const crypto::hash& h) const
3405 {
3406 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3407 check_open();
3408
3409 TXN_PREFIX_RDONLY();
3410 RCURSOR(tx_indices);
3411
3412 MDB_val_set(v, h);
3413 auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3414 if (get_result == MDB_NOTFOUND)
3415 {
3416 throw1(TX_DNE(std::string("tx_data_t with hash ").append(epee::string_tools::pod_to_hex(h)).append(" not found in db").c_str()));
3417 }
3418 else if (get_result)
3419 throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx height from hash", get_result).c_str()));
3420
3421 txindex *tip = (txindex *)v.mv_data;
3422 uint64_t ret = tip->data.block_id;
3423 TXN_POSTFIX_RDONLY();
3424 return ret;
3425 }
3426
3427 uint64_t BlockchainLMDB::get_num_outputs(const uint64_t& amount) const
3428 {
3429 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3430 check_open();
3431
3432 TXN_PREFIX_RDONLY();
3433 RCURSOR(output_amounts);
3434
3435 MDB_val_copy<uint64_t> k(amount);
3436 MDB_val v;
3437 mdb_size_t num_elems = 0;
3438 auto result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_SET);
3439 if (result == MDB_SUCCESS)
3440 {
3441 mdb_cursor_count(m_cur_output_amounts, &num_elems);
3442 }
3443 else if (result != MDB_NOTFOUND)
3444 throw0(DB_ERROR("DB error attempting to get number of outputs of an amount"));
3445
3446 TXN_POSTFIX_RDONLY();
3447
3448 return num_elems;
3449 }
3450
3451 output_data_t BlockchainLMDB::get_output_key(const uint64_t& amount, const uint64_t& index, bool include_commitmemt) const
3452 {
3453 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3454 check_open();
3455
3456 TXN_PREFIX_RDONLY();
3457 RCURSOR(output_amounts);
3458
3459 MDB_val_set(k, amount);
3460 MDB_val_set(v, index);
3461 auto get_result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
3462 if (get_result == MDB_NOTFOUND)
3463 throw1(OUTPUT_DNE(std::string("Attempting to get output pubkey by index, but key does not exist: amount " +
3464 std::to_string(amount) + ", index " + std::to_string(index)).c_str()));
3465 else if (get_result)
3466 throw0(DB_ERROR("Error attempting to retrieve an output pubkey from the db"));
3467
3468 output_data_t ret;
3469 if (amount == 0)
3470 {
3471 const outkey *okp = (const outkey *)v.mv_data;
3472 ret = okp->data;
3473 }
3474 else
3475 {
3476 const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data;
3477 memcpy(&ret, &okp->data, sizeof(pre_rct_output_data_t));
3478 if (include_commitmemt)
3479 ret.commitment = rct::zeroCommit(amount);
3480 }
3481 TXN_POSTFIX_RDONLY();
3482 return ret;
3483 }
3484
3485 tx_out_index BlockchainLMDB::get_output_tx_and_index_from_global(const uint64_t& output_id) const
3486 {
3487 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3488 check_open();
3489
3490 TXN_PREFIX_RDONLY();
3491 RCURSOR(output_txs);
3492
3493 MDB_val_set(v, output_id);
3494
3495 auto get_result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
3496 if (get_result == MDB_NOTFOUND)
3497 throw1(OUTPUT_DNE("output with given index not in db"));
3498 else if (get_result)
3499 throw0(DB_ERROR("DB error attempting to fetch output tx hash"));
3500
3501 outtx *ot = (outtx *)v.mv_data;
3502 tx_out_index ret = tx_out_index(ot->tx_hash, ot->local_index);
3503
3504 TXN_POSTFIX_RDONLY();
3505 return ret;
3506 }
3507
3508 tx_out_index BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const uint64_t& index) const
3509 {
3510 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3511 std::vector < uint64_t > offsets;
3512 std::vector<tx_out_index> indices;
3513 offsets.push_back(index);
3514 get_output_tx_and_index(amount, offsets, indices);
3515 if (!indices.size())
3516 throw1(OUTPUT_DNE("Attempting to get an output index by amount and amount index, but amount not found"));
3517
3518 return indices[0];
3519 }
3520
3521 std::vector<std::vector<uint64_t>> BlockchainLMDB::get_tx_amount_output_indices(uint64_t tx_id, size_t n_txes) const
3522 {
3523 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3524
3525 check_open();
3526
3527 TXN_PREFIX_RDONLY();
3528 RCURSOR(tx_outputs);
3529
3530 MDB_val_set(k_tx_id, tx_id);
3531 MDB_val v;
3532 std::vector<std::vector<uint64_t>> amount_output_indices_set;
3533 amount_output_indices_set.reserve(n_txes);
3534
3535 MDB_cursor_op op = MDB_SET;
3536 while (n_txes-- > 0)
3537 {
3538 int result = mdb_cursor_get(m_cur_tx_outputs, &k_tx_id, &v, op);
3539 if (result == MDB_NOTFOUND)
3540 LOG_PRINT_L0("WARNING: Unexpected: tx has no amount indices stored in "
3541 "tx_outputs, but it should have an empty entry even if it's a tx without "
3542 "outputs");
3543 else if (result)
3544 throw0(DB_ERROR(lmdb_error("DB error attempting to get data for tx_outputs[tx_index]", result).c_str()));
3545
3546 op = MDB_NEXT;
3547
3548 const uint64_t* indices = (const uint64_t*)v.mv_data;
3549 size_t num_outputs = v.mv_size / sizeof(uint64_t);
3550
3551 amount_output_indices_set.resize(amount_output_indices_set.size() + 1);
3552 std::vector<uint64_t> &amount_output_indices = amount_output_indices_set.back();
3553 amount_output_indices.reserve(num_outputs);
3554 for (size_t i = 0; i < num_outputs; ++i)
3555 {
3556 amount_output_indices.push_back(indices[i]);
3557 }
3558 }
3559
3560 TXN_POSTFIX_RDONLY();
3561 return amount_output_indices_set;
3562 }
3563
3564 bool BlockchainLMDB::has_key_image(const crypto::key_image& img) const
3565 {
3566 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3567 check_open();
3568
3569 bool ret;
3570
3571 TXN_PREFIX_RDONLY();
3572 RCURSOR(spent_keys);
3573
3574 MDB_val k = {sizeof(img), (void *)&img};
3575 ret = (mdb_cursor_get(m_cur_spent_keys, (MDB_val *)&zerokval, &k, MDB_GET_BOTH) == 0);
3576
3577 TXN_POSTFIX_RDONLY();
3578 return ret;
3579 }
3580
3581 bool BlockchainLMDB::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const
3582 {
3583 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3584 check_open();
3585
3586 TXN_PREFIX_RDONLY();
3587 RCURSOR(spent_keys);
3588
3589 MDB_val k, v;
3590 bool fret = true;
3591
3592 k = zerokval;
3593 MDB_cursor_op op = MDB_FIRST;
3594 while (1)
3595 {
3596 int ret = mdb_cursor_get(m_cur_spent_keys, &k, &v, op);
3597 op = MDB_NEXT;
3598 if (ret == MDB_NOTFOUND)
3599 break;
3600 if (ret < 0)
3601 throw0(DB_ERROR("Failed to enumerate key images"));
3602 const crypto::key_image k_image = *(const crypto::key_image*)v.mv_data;
3603 if (!f(k_image)) {
3604 fret = false;
3605 break;
3606 }
3607 }
3608
3609 TXN_POSTFIX_RDONLY();
3610
3611 return fret;
3612 }
3613
3614 bool BlockchainLMDB::for_blocks_range(const uint64_t& h1, const uint64_t& h2, std::function<bool(uint64_t, const crypto::hash&, const cryptonote::block&)> f) const
3615 {
3616 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3617 check_open();
3618
3619 TXN_PREFIX_RDONLY();
3620 RCURSOR(blocks);
3621
3622 MDB_val k;
3623 MDB_val v;
3624 bool fret = true;
3625
3626 MDB_cursor_op op;
3627 if (h1)
3628 {
3629 k = MDB_val{sizeof(h1), (void*)&h1};
3630 op = MDB_SET;
3631 } else
3632 {
3633 op = MDB_FIRST;
3634 }
3635 while (1)
3636 {
3637 int ret = mdb_cursor_get(m_cur_blocks, &k, &v, op);
3638 op = MDB_NEXT;
3639 if (ret == MDB_NOTFOUND)
3640 break;
3641 if (ret)
3642 throw0(DB_ERROR("Failed to enumerate blocks"));
3643 uint64_t height = *(const uint64_t*)k.mv_data;
3644 blobdata_ref bd{reinterpret_cast<char*>(v.mv_data), v.mv_size};
3645 block b;
3646 if (!parse_and_validate_block_from_blob(bd, b))
3647 throw0(DB_ERROR("Failed to parse block from blob retrieved from the db"));
3648 crypto::hash hash;
3649 if (!get_block_hash(b, hash))
3650 throw0(DB_ERROR("Failed to get block hash from blob retrieved from the db"));
3651 if (!f(height, hash, b)) {
3652 fret = false;
3653 break;
3654 }
3655 if (height >= h2)
3656 break;
3657 }
3658
3659 TXN_POSTFIX_RDONLY();
3660
3661 return fret;
3662 }
3663
3664 bool BlockchainLMDB::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f, bool pruned) const
3665 {
3666 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3667 check_open();
3668
3669 TXN_PREFIX_RDONLY();
3670 RCURSOR(txs_pruned);
3671 RCURSOR(txs_prunable);
3672 RCURSOR(tx_indices);
3673
3674 MDB_val k;
3675 MDB_val v;
3676 bool fret = true;
3677
3678 MDB_cursor_op op = MDB_FIRST;
3679 while (1)
3680 {
3681 int ret = mdb_cursor_get(m_cur_tx_indices, &k, &v, op);
3682 op = MDB_NEXT;
3683 if (ret == MDB_NOTFOUND)
3684 break;
3685 if (ret)
3686 throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
3687
3688 txindex *ti = (txindex *)v.mv_data;
3689 const crypto::hash hash = ti->key;
3690 k.mv_data = (void *)&ti->data.tx_id;
3691 k.mv_size = sizeof(ti->data.tx_id);
3692
3693 ret = mdb_cursor_get(m_cur_txs_pruned, &k, &v, MDB_SET);
3694 if (ret == MDB_NOTFOUND)
3695 break;
3696 if (ret)
3697 throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
3698 transaction tx;
3699 if (pruned)
3700 {
3701 blobdata_ref bd{reinterpret_cast<char*>(v.mv_data), v.mv_size};
3702 if (!parse_and_validate_tx_base_from_blob(bd, tx))
3703 throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
3704 }
3705 else
3706 {
3707 blobdata bd;
3708 bd.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
3709 ret = mdb_cursor_get(m_cur_txs_prunable, &k, &v, MDB_SET);
3710 if (ret)
3711 throw0(DB_ERROR(lmdb_error("Failed to get prunable tx data the db: ", ret).c_str()));
3712 bd.append(reinterpret_cast<char*>(v.mv_data), v.mv_size);
3713 if (!parse_and_validate_tx_from_blob(bd, tx))
3714 throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
3715 }
3716 if (!f(hash, tx)) {
3717 fret = false;
3718 break;
3719 }
3720 }
3721
3722 TXN_POSTFIX_RDONLY();
3723
3724 return fret;
3725 }
3726
3727 bool BlockchainLMDB::for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, uint64_t height, size_t tx_idx)> f) const
3728 {
3729 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3730 check_open();
3731
3732 TXN_PREFIX_RDONLY();
3733 RCURSOR(output_amounts);
3734
3735 MDB_val k;
3736 MDB_val v;
3737 bool fret = true;
3738
3739 MDB_cursor_op op = MDB_FIRST;
3740 while (1)
3741 {
3742 int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
3743 op = MDB_NEXT;
3744 if (ret == MDB_NOTFOUND)
3745 break;
3746 if (ret)
3747 throw0(DB_ERROR("Failed to enumerate outputs"));
3748 uint64_t amount = *(const uint64_t*)k.mv_data;
3749 outkey *ok = (outkey *)v.mv_data;
3750 tx_out_index toi = get_output_tx_and_index_from_global(ok->output_id);
3751 if (!f(amount, toi.first, ok->data.height, toi.second)) {
3752 fret = false;
3753 break;
3754 }
3755 }
3756
3757 TXN_POSTFIX_RDONLY();
3758
3759 return fret;
3760 }
3761
3762 bool BlockchainLMDB::for_all_outputs(uint64_t amount, const std::function<bool(uint64_t height)> &f) const
3763 {
3764 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3765 check_open();
3766
3767 TXN_PREFIX_RDONLY();
3768 RCURSOR(output_amounts);
3769
3770 MDB_val_set(k, amount);
3771 MDB_val v;
3772 bool fret = true;
3773
3774 MDB_cursor_op op = MDB_SET;
3775 while (1)
3776 {
3777 int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
3778 op = MDB_NEXT_DUP;
3779 if (ret == MDB_NOTFOUND)
3780 break;
3781 if (ret)
3782 throw0(DB_ERROR("Failed to enumerate outputs"));
3783 uint64_t out_amount = *(const uint64_t*)k.mv_data;
3784 if (amount != out_amount)
3785 {
3786 MERROR("Amount is not the expected amount");
3787 fret = false;
3788 break;
3789 }
3790 const outkey *ok = (const outkey *)v.mv_data;
3791 if (!f(ok->data.height)) {
3792 fret = false;
3793 break;
3794 }
3795 }
3796
3797 TXN_POSTFIX_RDONLY();
3798
3799 return fret;
3800 }
3801
3802 // batch_num_blocks: (optional) Used to check if resize needed before batch transaction starts.
3803 bool BlockchainLMDB::batch_start(uint64_t batch_num_blocks, uint64_t batch_bytes)
3804 {
3805 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3806 if (! m_batch_transactions)
3807 throw0(DB_ERROR("batch transactions not enabled"));
3808 if (m_batch_active)
3809 return false;
3810 if (m_write_batch_txn != nullptr)
3811 return false;
3812 if (m_write_txn)
3813 throw0(DB_ERROR("batch transaction attempted, but m_write_txn already in use"));
3814 check_open();
3815
3816 m_writer = boost::this_thread::get_id();
3817 check_and_resize_for_batch(batch_num_blocks, batch_bytes);
3818
3819 m_write_batch_txn = new mdb_txn_safe();
3820
3821 // NOTE: need to make sure it's destroyed properly when done
3822 if (auto mdb_res = lmdb_txn_begin(m_env, NULL, 0, *m_write_batch_txn))
3823 {
3824 delete m_write_batch_txn;
3825 m_write_batch_txn = nullptr;
3826 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", mdb_res).c_str()));
3827 }
3828 // indicates this transaction is for batch transactions, but not whether it's
3829 // active
3830 m_write_batch_txn->m_batch_txn = true;
3831 m_write_txn = m_write_batch_txn;
3832
3833 m_batch_active = true;
3834 memset(&m_wcursors, 0, sizeof(m_wcursors));
3835 if (m_tinfo.get())
3836 {
3837 if (m_tinfo->m_ti_rflags.m_rf_txn)
3838 mdb_txn_reset(m_tinfo->m_ti_rtxn);
3839 memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
3840 }
3841
3842 LOG_PRINT_L3("batch transaction: begin");
3843 return true;
3844 }
3845
3846 void BlockchainLMDB::batch_commit()
3847 {
3848 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3849 if (! m_batch_transactions)
3850 throw0(DB_ERROR("batch transactions not enabled"));
3851 if (! m_batch_active)
3852 throw1(DB_ERROR("batch transaction not in progress"));
3853 if (m_write_batch_txn == nullptr)
3854 throw1(DB_ERROR("batch transaction not in progress"));
3855 if (m_writer != boost::this_thread::get_id())
3856 throw1(DB_ERROR("batch transaction owned by other thread"));
3857
3858 check_open();
3859
3860 LOG_PRINT_L3("batch transaction: committing...");
3861 TIME_MEASURE_START(time1);
3862 m_write_txn->commit();
3863 TIME_MEASURE_FINISH(time1);
3864 time_commit1 += time1;
3865 LOG_PRINT_L3("batch transaction: committed");
3866
3867 m_write_txn = nullptr;
3868 delete m_write_batch_txn;
3869 m_write_batch_txn = nullptr;
3870 memset(&m_wcursors, 0, sizeof(m_wcursors));
3871 }
3872
3873 void BlockchainLMDB::cleanup_batch()
3874 {
3875 // for destruction of batch transaction
3876 m_write_txn = nullptr;
3877 delete m_write_batch_txn;
3878 m_write_batch_txn = nullptr;
3879 m_batch_active = false;
3880 memset(&m_wcursors, 0, sizeof(m_wcursors));
3881 }
3882
3883 void BlockchainLMDB::batch_stop()
3884 {
3885 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3886 if (! m_batch_transactions)
3887 throw0(DB_ERROR("batch transactions not enabled"));
3888 if (! m_batch_active)
3889 throw1(DB_ERROR("batch transaction not in progress"));
3890 if (m_write_batch_txn == nullptr)
3891 throw1(DB_ERROR("batch transaction not in progress"));
3892 if (m_writer != boost::this_thread::get_id())
3893 throw1(DB_ERROR("batch transaction owned by other thread"));
3894 check_open();
3895 LOG_PRINT_L3("batch transaction: committing...");
3896 TIME_MEASURE_START(time1);
3897 try
3898 {
3899 m_write_txn->commit();
3900 TIME_MEASURE_FINISH(time1);
3901 time_commit1 += time1;
3902 cleanup_batch();
3903 }
3904 catch (const std::exception &e)
3905 {
3906 cleanup_batch();
3907 throw;
3908 }
3909 LOG_PRINT_L3("batch transaction: end");
3910 }
3911
3912 void BlockchainLMDB::batch_abort()
3913 {
3914 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3915 if (! m_batch_transactions)
3916 throw0(DB_ERROR("batch transactions not enabled"));
3917 if (! m_batch_active)
3918 throw1(DB_ERROR("batch transaction not in progress"));
3919 if (m_write_batch_txn == nullptr)
3920 throw1(DB_ERROR("batch transaction not in progress"));
3921 if (m_writer != boost::this_thread::get_id())
3922 throw1(DB_ERROR("batch transaction owned by other thread"));
3923 check_open();
3924 // for destruction of batch transaction
3925 m_write_txn = nullptr;
3926 // explicitly call in case mdb_env_close() (BlockchainLMDB::close()) called before BlockchainLMDB destructor called.
3927 m_write_batch_txn->abort();
3928 delete m_write_batch_txn;
3929 m_write_batch_txn = nullptr;
3930 m_batch_active = false;
3931 memset(&m_wcursors, 0, sizeof(m_wcursors));
3932 LOG_PRINT_L3("batch transaction: aborted");
3933 }
3934
3935 void BlockchainLMDB::set_batch_transactions(bool batch_transactions)
3936 {
3937 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3938 if ((batch_transactions) && (m_batch_transactions))
3939 {
3940 MINFO("batch transaction mode already enabled, but asked to enable batch mode");
3941 }
3942 m_batch_transactions = batch_transactions;
3943 MINFO("batch transactions " << (m_batch_transactions ? "enabled" : "disabled"));
3944 }
3945
3946 // return true if we started the txn, false if already started
3947 bool BlockchainLMDB::block_rtxn_start(MDB_txn **mtxn, mdb_txn_cursors **mcur) const
3948 {
3949 bool ret = false;
3950 mdb_threadinfo *tinfo;
3951 if (m_write_txn && m_writer == boost::this_thread::get_id()) {
3952 *mtxn = m_write_txn->m_txn;
3953 *mcur = (mdb_txn_cursors *)&m_wcursors;
3954 return ret;
3955 }
3956 /* Check for existing info and force reset if env doesn't match -
3957 * only happens if env was opened/closed multiple times in same process
3958 */
3959 if (!(tinfo = m_tinfo.get()) || mdb_txn_env(tinfo->m_ti_rtxn) != m_env)
3960 {
3961 tinfo = new mdb_threadinfo;
3962 m_tinfo.reset(tinfo);
3963 memset(&tinfo->m_ti_rcursors, 0, sizeof(tinfo->m_ti_rcursors));
3964 memset(&tinfo->m_ti_rflags, 0, sizeof(tinfo->m_ti_rflags));
3965 if (auto mdb_res = lmdb_txn_begin(m_env, NULL, MDB_RDONLY, &tinfo->m_ti_rtxn))
3966 throw0(DB_ERROR_TXN_START(lmdb_error("Failed to create a read transaction for the db: ", mdb_res).c_str()));
3967 ret = true;
3968 } else if (!tinfo->m_ti_rflags.m_rf_txn)
3969 {
3970 if (auto mdb_res = lmdb_txn_renew(tinfo->m_ti_rtxn))
3971 throw0(DB_ERROR_TXN_START(lmdb_error("Failed to renew a read transaction for the db: ", mdb_res).c_str()));
3972 ret = true;
3973 }
3974 if (ret)
3975 tinfo->m_ti_rflags.m_rf_txn = true;
3976 *mtxn = tinfo->m_ti_rtxn;
3977 *mcur = &tinfo->m_ti_rcursors;
3978
3979 if (ret)
3980 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3981 return ret;
3982 }
3983
3984 void BlockchainLMDB::block_rtxn_stop() const
3985 {
3986 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
3987 mdb_txn_reset(m_tinfo->m_ti_rtxn);
3988 memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
3989 /* cancel out the increment from rtxn_start */
3990 mdb_txn_safe::increment_txns(-1);
3991 }
3992
3993 bool BlockchainLMDB::block_rtxn_start() const
3994 {
3995 MDB_txn *mtxn;
3996 mdb_txn_cursors *mcur;
3997 /* auto_txn is only used for the create gate */
3998 mdb_txn_safe auto_txn;
3999 bool ret = block_rtxn_start(&mtxn, &mcur);
4000 if (ret)
4001 auto_txn.increment_txns(1); /* remember there is an active readtxn */
4002 return ret;
4003 }
4004
4005 void BlockchainLMDB::block_wtxn_start()
4006 {
4007 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4008 // Distinguish the exceptions here from exceptions that would be thrown while
4009 // using the txn and committing it.
4010 //
4011 // If an exception is thrown in this setup, we don't want the caller to catch
4012 // it and proceed as if there were an existing write txn, such as trying to
4013 // call block_txn_abort(). It also indicates a serious issue which will
4014 // probably be thrown up another layer.
4015 if (! m_batch_active && m_write_txn)
4016 throw0(DB_ERROR_TXN_START((std::string("Attempted to start new write txn when write txn already exists in ")+__FUNCTION__).c_str()));
4017 if (! m_batch_active)
4018 {
4019 m_writer = boost::this_thread::get_id();
4020 m_write_txn = new mdb_txn_safe();
4021 if (auto mdb_res = lmdb_txn_begin(m_env, NULL, 0, *m_write_txn))
4022 {
4023 delete m_write_txn;
4024 m_write_txn = nullptr;
4025 throw0(DB_ERROR_TXN_START(lmdb_error("Failed to create a transaction for the db: ", mdb_res).c_str()));
4026 }
4027 memset(&m_wcursors, 0, sizeof(m_wcursors));
4028 if (m_tinfo.get())
4029 {
4030 if (m_tinfo->m_ti_rflags.m_rf_txn)
4031 mdb_txn_reset(m_tinfo->m_ti_rtxn);
4032 memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
4033 }
4034 } else if (m_writer != boost::this_thread::get_id())
4035 throw0(DB_ERROR_TXN_START((std::string("Attempted to start new write txn when batch txn already exists in ")+__FUNCTION__).c_str()));
4036 }
4037
4038 void BlockchainLMDB::block_wtxn_stop()
4039 {
4040 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4041 if (!m_write_txn)
4042 throw0(DB_ERROR_TXN_START((std::string("Attempted to stop write txn when no such txn exists in ")+__FUNCTION__).c_str()));
4043 if (m_writer != boost::this_thread::get_id())
4044 throw0(DB_ERROR_TXN_START((std::string("Attempted to stop write txn from the wrong thread in ")+__FUNCTION__).c_str()));
4045 {
4046 if (! m_batch_active)
4047 {
4048 TIME_MEASURE_START(time1);
4049 m_write_txn->commit();
4050 TIME_MEASURE_FINISH(time1);
4051 time_commit1 += time1;
4052
4053 delete m_write_txn;
4054 m_write_txn = nullptr;
4055 memset(&m_wcursors, 0, sizeof(m_wcursors));
4056 }
4057 }
4058 }
4059
4060 void BlockchainLMDB::block_wtxn_abort()
4061 {
4062 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4063 if (!m_write_txn)
4064 throw0(DB_ERROR_TXN_START((std::string("Attempted to abort write txn when no such txn exists in ")+__FUNCTION__).c_str()));
4065 if (m_writer != boost::this_thread::get_id())
4066 throw0(DB_ERROR_TXN_START((std::string("Attempted to abort write txn from the wrong thread in ")+__FUNCTION__).c_str()));
4067
4068 if (! m_batch_active)
4069 {
4070 delete m_write_txn;
4071 m_write_txn = nullptr;
4072 memset(&m_wcursors, 0, sizeof(m_wcursors));
4073 }
4074 }
4075
4076 void BlockchainLMDB::block_rtxn_abort() const
4077 {
4078 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4079 mdb_txn_reset(m_tinfo->m_ti_rtxn);
4080 memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
4081 }
4082
4083 uint64_t BlockchainLMDB::add_block(const std::pair<block, blobdata>& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated,
4084 const std::vector<std::pair<transaction, blobdata>>& txs)
4085 {
4086 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4087 check_open();
4088 uint64_t m_height = height();
4089
4090 if (m_height % 1024 == 0)
4091 {
4092 // for batch mode, DB resize check is done at start of batch transaction
4093 if (! m_batch_active && need_resize())
4094 {
4095 LOG_PRINT_L0("LMDB memory map needs to be resized, doing that now.");
4096 do_resize();
4097 }
4098 }
4099
4100 try
4101 {
4102 BlockchainDB::add_block(blk, block_weight, long_term_block_weight, cumulative_difficulty, coins_generated, txs);
4103 }
4104 catch (const DB_ERROR_TXN_START& e)
4105 {
4106 throw;
4107 }
4108
4109 return ++m_height;
4110 }
4111
4112 void BlockchainLMDB::pop_block(block& blk, std::vector<transaction>& txs)
4113 {
4114 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4115 check_open();
4116
4117 block_wtxn_start();
4118
4119 try
4120 {
4121 BlockchainDB::pop_block(blk, txs);
4122 block_wtxn_stop();
4123 }
4124 catch (...)
4125 {
4126 block_wtxn_abort();
4127 throw;
4128 }
4129 }
4130
4131 void BlockchainLMDB::get_output_tx_and_index_from_global(const std::vector<uint64_t> &global_indices,
4132 std::vector<tx_out_index> &tx_out_indices) const
4133 {
4134 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4135 check_open();
4136 tx_out_indices.clear();
4137 tx_out_indices.reserve(global_indices.size());
4138
4139 TXN_PREFIX_RDONLY();
4140 RCURSOR(output_txs);
4141
4142 for (const uint64_t &output_id : global_indices)
4143 {
4144 MDB_val_set(v, output_id);
4145
4146 auto get_result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
4147 if (get_result == MDB_NOTFOUND)
4148 throw1(OUTPUT_DNE("output with given index not in db"));
4149 else if (get_result)
4150 throw0(DB_ERROR("DB error attempting to fetch output tx hash"));
4151
4152 const outtx *ot = (const outtx *)v.mv_data;
4153 tx_out_indices.push_back(tx_out_index(ot->tx_hash, ot->local_index));
4154 }
4155
4156 TXN_POSTFIX_RDONLY();
4157 }
4158
4159 void BlockchainLMDB::get_output_key(const epee::span<const uint64_t> &amounts, const std::vector<uint64_t> &offsets, std::vector<output_data_t> &outputs, bool allow_partial) const
4160 {
4161 if (amounts.size() != 1 && amounts.size() != offsets.size())
4162 throw0(DB_ERROR("Invalid sizes of amounts and offsets"));
4163
4164 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4165 TIME_MEASURE_START(db3);
4166 check_open();
4167 outputs.clear();
4168 outputs.reserve(offsets.size());
4169
4170 TXN_PREFIX_RDONLY();
4171
4172 RCURSOR(output_amounts);
4173
4174 for (size_t i = 0; i < offsets.size(); ++i)
4175 {
4176 const uint64_t amount = amounts.size() == 1 ? amounts[0] : amounts[i];
4177 MDB_val_set(k, amount);
4178 MDB_val_set(v, offsets[i]);
4179
4180 auto get_result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
4181 if (get_result == MDB_NOTFOUND)
4182 {
4183 if (allow_partial)
4184 {
4185 MDEBUG("Partial result: " << outputs.size() << "/" << offsets.size());
4186 break;
4187 }
4188 throw1(OUTPUT_DNE((std::string("Attempting to get output pubkey by global index (amount ") + boost::lexical_cast<std::string>(amount) + ", index " + boost::lexical_cast<std::string>(offsets[i]) + ", count " + boost::lexical_cast<std::string>(get_num_outputs(amount)) + "), but key does not exist (current height " + boost::lexical_cast<std::string>(height()) + ")").c_str()));
4189 }
4190 else if (get_result)
4191 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve an output pubkey from the db", get_result).c_str()));
4192
4193 if (amount == 0)
4194 {
4195 const outkey *okp = (const outkey *)v.mv_data;
4196 outputs.push_back(okp->data);
4197 }
4198 else
4199 {
4200 const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data;
4201 outputs.resize(outputs.size() + 1);
4202 output_data_t &data = outputs.back();
4203 memcpy(&data, &okp->data, sizeof(pre_rct_output_data_t));
4204 data.commitment = rct::zeroCommit(amount);
4205 }
4206 }
4207
4208 TXN_POSTFIX_RDONLY();
4209
4210 TIME_MEASURE_FINISH(db3);
4211 LOG_PRINT_L3("db3: " << db3);
4212 }
4213
4214 void BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const std::vector<uint64_t> &offsets, std::vector<tx_out_index> &indices) const
4215 {
4216 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4217 check_open();
4218 indices.clear();
4219
4220 std::vector <uint64_t> tx_indices;
4221 tx_indices.reserve(offsets.size());
4222 TXN_PREFIX_RDONLY();
4223
4224 RCURSOR(output_amounts);
4225
4226 MDB_val_set(k, amount);
4227 for (const uint64_t &index : offsets)
4228 {
4229 MDB_val_set(v, index);
4230
4231 auto get_result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
4232 if (get_result == MDB_NOTFOUND)
4233 throw1(OUTPUT_DNE("Attempting to get output by index, but key does not exist"));
4234 else if (get_result)
4235 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve an output from the db", get_result).c_str()));
4236
4237 const outkey *okp = (const outkey *)v.mv_data;
4238 tx_indices.push_back(okp->output_id);
4239 }
4240
4241 TIME_MEASURE_START(db3);
4242 if(tx_indices.size() > 0)
4243 {
4244 get_output_tx_and_index_from_global(tx_indices, indices);
4245 }
4246 TIME_MEASURE_FINISH(db3);
4247 LOG_PRINT_L3("db3: " << db3);
4248 }
4249
4250 std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> BlockchainLMDB::get_output_histogram(const std::vector<uint64_t> &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count) const
4251 {
4252 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4253 check_open();
4254
4255 TXN_PREFIX_RDONLY();
4256 RCURSOR(output_amounts);
4257
4258 std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> histogram;
4259 MDB_val k;
4260 MDB_val v;
4261
4262 if (amounts.empty())
4263 {
4264 MDB_cursor_op op = MDB_FIRST;
4265 while (1)
4266 {
4267 int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
4268 op = MDB_NEXT_NODUP;
4269 if (ret == MDB_NOTFOUND)
4270 break;
4271 if (ret)
4272 throw0(DB_ERROR(lmdb_error("Failed to enumerate outputs: ", ret).c_str()));
4273 mdb_size_t num_elems = 0;
4274 mdb_cursor_count(m_cur_output_amounts, &num_elems);
4275 uint64_t amount = *(const uint64_t*)k.mv_data;
4276 if (num_elems >= min_count)
4277 histogram[amount] = std::make_tuple(num_elems, 0, 0);
4278 }
4279 }
4280 else
4281 {
4282 for (const auto &amount: amounts)
4283 {
4284 MDB_val_copy<uint64_t> k(amount);
4285 int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_SET);
4286 if (ret == MDB_NOTFOUND)
4287 {
4288 if (0 >= min_count)
4289 histogram[amount] = std::make_tuple(0, 0, 0);
4290 }
4291 else if (ret == MDB_SUCCESS)
4292 {
4293 mdb_size_t num_elems = 0;
4294 mdb_cursor_count(m_cur_output_amounts, &num_elems);
4295 if (num_elems >= min_count)
4296 histogram[amount] = std::make_tuple(num_elems, 0, 0);
4297 }
4298 else
4299 {
4300 throw0(DB_ERROR(lmdb_error("Failed to enumerate outputs: ", ret).c_str()));
4301 }
4302 }
4303 }
4304
4305 if (unlocked || recent_cutoff > 0) {
4306 const uint64_t blockchain_height = height();
4307 for (std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>>::iterator i = histogram.begin(); i != histogram.end(); ++i) {
4308 uint64_t amount = i->first;
4309 uint64_t num_elems = std::get<0>(i->second);
4310 while (num_elems > 0) {
4311 const tx_out_index toi = get_output_tx_and_index(amount, num_elems - 1);
4312 const uint64_t height = get_tx_block_height(toi.first);
4313 if (height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= blockchain_height)
4314 break;
4315 --num_elems;
4316 }
4317 // modifying second does not invalidate the iterator
4318 std::get<1>(i->second) = num_elems;
4319
4320 if (recent_cutoff > 0)
4321 {
4322 uint64_t recent = 0;
4323 while (num_elems > 0) {
4324 const tx_out_index toi = get_output_tx_and_index(amount, num_elems - 1);
4325 const uint64_t height = get_tx_block_height(toi.first);
4326 const uint64_t ts = get_block_timestamp(height);
4327 if (ts < recent_cutoff)
4328 break;
4329 --num_elems;
4330 ++recent;
4331 }
4332 // modifying second does not invalidate the iterator
4333 std::get<2>(i->second) = recent;
4334 }
4335 }
4336 }
4337
4338 TXN_POSTFIX_RDONLY();
4339
4340 return histogram;
4341 }
4342
4343 bool BlockchainLMDB::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, std::vector<uint64_t> &distribution, uint64_t &base) const
4344 {
4345 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4346 check_open();
4347
4348 TXN_PREFIX_RDONLY();
4349 RCURSOR(output_amounts);
4350
4351 distribution.clear();
4352 const uint64_t db_height = height();
4353 if (from_height >= db_height)
4354 return false;
4355 distribution.resize(db_height - from_height, 0);
4356
4357 MDB_val_set(k, amount);
4358 MDB_val v;
4359 MDB_cursor_op op = MDB_SET;
4360 base = 0;
4361 while (1)
4362 {
4363 int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
4364 op = MDB_NEXT_DUP;
4365 if (ret == MDB_NOTFOUND)
4366 break;
4367 if (ret)
4368 throw0(DB_ERROR("Failed to enumerate outputs"));
4369 const outkey *ok = (const outkey *)v.mv_data;
4370 const uint64_t height = ok->data.height;
4371 if (height >= from_height)
4372 distribution[height - from_height]++;
4373 else
4374 base++;
4375 if (to_height > 0 && height > to_height)
4376 break;
4377 }
4378
4379 distribution[0] += base;
4380 for (size_t n = 1; n < distribution.size(); ++n)
4381 distribution[n] += distribution[n - 1];
4382 base = 0;
4383
4384 TXN_POSTFIX_RDONLY();
4385
4386 return true;
4387 }
4388
4389 void BlockchainLMDB::check_hard_fork_info()
4390 {
4391 }
4392
4393 void BlockchainLMDB::drop_hard_fork_info()
4394 {
4395 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4396 check_open();
4397
4398 TXN_PREFIX(0);
4399
4400 auto result = mdb_drop(*txn_ptr, m_hf_starting_heights, 1);
4401 if (result)
4402 throw1(DB_ERROR(lmdb_error("Error dropping hard fork starting heights db: ", result).c_str()));
4403 result = mdb_drop(*txn_ptr, m_hf_versions, 1);
4404 if (result)
4405 throw1(DB_ERROR(lmdb_error("Error dropping hard fork versions db: ", result).c_str()));
4406
4407 TXN_POSTFIX_SUCCESS();
4408 }
4409
4410 void BlockchainLMDB::set_hard_fork_version(uint64_t height, uint8_t version)
4411 {
4412 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4413 check_open();
4414
4415 TXN_BLOCK_PREFIX(0);
4416
4417 MDB_val_copy<uint64_t> val_key(height);
4418 MDB_val_copy<uint8_t> val_value(version);
4419 int result;
4420 result = mdb_put(*txn_ptr, m_hf_versions, &val_key, &val_value, MDB_APPEND);
4421 if (result == MDB_KEYEXIST)
4422 result = mdb_put(*txn_ptr, m_hf_versions, &val_key, &val_value, 0);
4423 if (result)
4424 throw1(DB_ERROR(lmdb_error("Error adding hard fork version to db transaction: ", result).c_str()));
4425
4426 TXN_BLOCK_POSTFIX_SUCCESS();
4427 }
4428
4429 uint8_t BlockchainLMDB::get_hard_fork_version(uint64_t height) const
4430 {
4431 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4432 check_open();
4433
4434 TXN_PREFIX_RDONLY();
4435 RCURSOR(hf_versions);
4436
4437 MDB_val_copy<uint64_t> val_key(height);
4438 MDB_val val_ret;
4439 auto result = mdb_cursor_get(m_cur_hf_versions, &val_key, &val_ret, MDB_SET);
4440 if (result == MDB_NOTFOUND || result)
4441 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve a hard fork version at height " + boost::lexical_cast<std::string>(height) + " from the db: ", result).c_str()));
4442
4443 uint8_t ret = *(const uint8_t*)val_ret.mv_data;
4444 TXN_POSTFIX_RDONLY();
4445 return ret;
4446 }
4447
4448 void BlockchainLMDB::add_alt_block(const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const cryptonote::blobdata_ref &blob)
4449 {
4450 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4451 check_open();
4452 mdb_txn_cursors *m_cursors = &m_wcursors;
4453
4454 CURSOR(alt_blocks)
4455
4456 MDB_val k = {sizeof(blkid), (void *)&blkid};
4457 const size_t val_size = sizeof(alt_block_data_t) + blob.size();
4458 std::unique_ptr<char[]> val(new char[val_size]);
4459 memcpy(val.get(), &data, sizeof(alt_block_data_t));
4460 memcpy(val.get() + sizeof(alt_block_data_t), blob.data(), blob.size());
4461 MDB_val v = {val_size, (void *)val.get()};
4462 if (auto result = mdb_cursor_put(m_cur_alt_blocks, &k, &v, MDB_NODUPDATA)) {
4463 if (result == MDB_KEYEXIST)
4464 throw1(DB_ERROR("Attempting to add alternate block that's already in the db"));
4465 else
4466 throw1(DB_ERROR(lmdb_error("Error adding alternate block to db transaction: ", result).c_str()));
4467 }
4468 }
4469
4470 bool BlockchainLMDB::get_alt_block(const crypto::hash &blkid, alt_block_data_t *data, cryptonote::blobdata *blob)
4471 {
4472 LOG_PRINT_L3("BlockchainLMDB:: " << __func__);
4473 check_open();
4474
4475 TXN_PREFIX_RDONLY();
4476 RCURSOR(alt_blocks);
4477
4478 MDB_val_set(k, blkid);
4479 MDB_val v;
4480 int result = mdb_cursor_get(m_cur_alt_blocks, &k, &v, MDB_SET);
4481 if (result == MDB_NOTFOUND)
4482 return false;
4483
4484 if (result)
4485 throw0(DB_ERROR(lmdb_error("Error attempting to retrieve alternate block " + epee::string_tools::pod_to_hex(blkid) + " from the db: ", result).c_str()));
4486 if (v.mv_size < sizeof(alt_block_data_t))
4487 throw0(DB_ERROR("Record size is less than expected"));
4488
4489 const alt_block_data_t *ptr = (const alt_block_data_t*)v.mv_data;
4490 if (data)
4491 *data = *ptr;
4492 if (blob)
4493 blob->assign((const char*)(ptr + 1), v.mv_size - sizeof(alt_block_data_t));
4494
4495 TXN_POSTFIX_RDONLY();
4496 return true;
4497 }
4498
4499 void BlockchainLMDB::remove_alt_block(const crypto::hash &blkid)
4500 {
4501 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4502 check_open();
4503 mdb_txn_cursors *m_cursors = &m_wcursors;
4504
4505 CURSOR(alt_blocks)
4506
4507 MDB_val k = {sizeof(blkid), (void *)&blkid};
4508 MDB_val v;
4509 int result = mdb_cursor_get(m_cur_alt_blocks, &k, &v, MDB_SET);
4510 if (result)
4511 throw0(DB_ERROR(lmdb_error("Error locating alternate block " + epee::string_tools::pod_to_hex(blkid) + " in the db: ", result).c_str()));
4512 result = mdb_cursor_del(m_cur_alt_blocks, 0);
4513 if (result)
4514 throw0(DB_ERROR(lmdb_error("Error deleting alternate block " + epee::string_tools::pod_to_hex(blkid) + " from the db: ", result).c_str()));
4515 }
4516
4517 uint64_t BlockchainLMDB::get_alt_block_count()
4518 {
4519 LOG_PRINT_L3("BlockchainLMDB:: " << __func__);
4520 check_open();
4521
4522 TXN_PREFIX_RDONLY();
4523 RCURSOR(alt_blocks);
4524
4525 MDB_stat db_stats;
4526 int result = mdb_stat(m_txn, m_alt_blocks, &db_stats);
4527 uint64_t count = 0;
4528 if (result != MDB_NOTFOUND)
4529 {
4530 if (result)
4531 throw0(DB_ERROR(lmdb_error("Failed to query m_alt_blocks: ", result).c_str()));
4532 count = db_stats.ms_entries;
4533 }
4534 TXN_POSTFIX_RDONLY();
4535 return count;
4536 }
4537
4538 void BlockchainLMDB::drop_alt_blocks()
4539 {
4540 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4541 check_open();
4542
4543 TXN_PREFIX(0);
4544
4545 auto result = mdb_drop(*txn_ptr, m_alt_blocks, 0);
4546 if (result)
4547 throw1(DB_ERROR(lmdb_error("Error dropping alternative blocks: ", result).c_str()));
4548
4549 TXN_POSTFIX_SUCCESS();
4550 }
4551
4552 bool BlockchainLMDB::is_read_only() const
4553 {
4554 unsigned int flags;
4555 auto result = mdb_env_get_flags(m_env, &flags);
4556 if (result)
4557 throw0(DB_ERROR(lmdb_error("Error getting database environment info: ", result).c_str()));
4558
4559 if (flags & MDB_RDONLY)
4560 return true;
4561
4562 return false;
4563 }
4564
4565 uint64_t BlockchainLMDB::get_database_size() const
4566 {
4567 boost::filesystem::path datafile(m_folder);
4568 datafile /= CRYPTONOTE_BLOCKCHAINDATA_FILENAME;
4569 boost::system::error_code ec{};
4570 const boost::uintmax_t size = boost::filesystem::file_size(datafile, ec);
4571 return (ec ? 0 : static_cast<uint64_t>(size));
4572 }
4573
4574 void BlockchainLMDB::fixup()
4575 {
4576 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4577 // Always call parent as well
4578 BlockchainDB::fixup();
4579 }
4580
4581 #define RENAME_DB(name) do { \
4582 char n2[] = name; \
4583 MDB_dbi tdbi; \
4584 n2[sizeof(n2)-2]--; \
4585 /* play some games to put (name) on a writable page */ \
4586 result = mdb_dbi_open(txn, n2, MDB_CREATE, &tdbi); \
4587 if (result) \
4588 throw0(DB_ERROR(lmdb_error("Failed to create " + std::string(n2) + ": ", result).c_str())); \
4589 result = mdb_drop(txn, tdbi, 1); \
4590 if (result) \
4591 throw0(DB_ERROR(lmdb_error("Failed to delete " + std::string(n2) + ": ", result).c_str())); \
4592 k.mv_data = (void *)name; \
4593 k.mv_size = sizeof(name)-1; \
4594 result = mdb_cursor_open(txn, 1, &c_cur); \
4595 if (result) \
4596 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for " name ": ", result).c_str())); \
4597 result = mdb_cursor_get(c_cur, &k, NULL, MDB_SET_KEY); \
4598 if (result) \
4599 throw0(DB_ERROR(lmdb_error("Failed to get DB record for " name ": ", result).c_str())); \
4600 ptr = (char *)k.mv_data; \
4601 ptr[sizeof(name)-2]++; } while(0)
4602
4603 #define LOGIF(y) if (ELPP->vRegistry()->allowed(y, "global"))
4604
4605 void BlockchainLMDB::migrate_0_1()
4606 {
4607 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
4608 uint64_t i, z, m_height;
4609 int result;
4610 mdb_txn_safe txn(false);
4611 MDB_val k, v;
4612 char *ptr;
4613
4614 MGINFO_YELLOW("Migrating blockchain from DB version 0 to 1 - this may take a while:");
4615 MINFO("updating blocks, hf_versions, outputs, txs, and spent_keys tables...");
4616
4617 do {
4618 result = mdb_txn_begin(m_env, NULL, 0, txn);
4619 if (result)
4620 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4621
4622 MDB_stat db_stats;
4623 if ((result = mdb_stat(txn, m_blocks, &db_stats)))
4624 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
4625 m_height = db_stats.ms_entries;
4626 MINFO("Total number of blocks: " << m_height);
4627 MINFO("block migration will update block_heights, block_info, and hf_versions...");
4628
4629 MINFO("migrating block_heights:");
4630 MDB_dbi o_heights;
4631
4632 unsigned int flags;
4633 result = mdb_dbi_flags(txn, m_block_heights, &flags);
4634 if (result)
4635 throw0(DB_ERROR(lmdb_error("Failed to retrieve block_heights flags: ", result).c_str()));
4636 /* if the flags are what we expect, this table has already been migrated */
4637 if ((flags & (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) == (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) {
4638 txn.abort();
4639 LOG_PRINT_L1(" block_heights already migrated");
4640 break;
4641 }
4642
4643 /* the block_heights table name is the same but the old version and new version
4644 * have incompatible DB flags. Create a new table with the right flags. We want
4645 * the name to be similar to the old name so that it will occupy the same location
4646 * in the DB.
4647 */
4648 o_heights = m_block_heights;
4649 lmdb_db_open(txn, "block_heightr", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_heights, "Failed to open db handle for block_heightr");
4650 mdb_set_dupsort(txn, m_block_heights, compare_hash32);
4651
4652 MDB_cursor *c_old, *c_cur;
4653 blk_height bh;
4654 MDB_val_set(nv, bh);
4655
4656 /* old table was k(hash), v(height).
4657 * new table is DUPFIXED, k(zeroval), v{hash, height}.
4658 */
4659 i = 0;
4660 z = m_height;
4661 while(1) {
4662 if (!(i % 2000)) {
4663 if (i) {
4664 LOGIF(el::Level::Info) {
4665 std::cout << i << " / " << z << " \r" << std::flush;
4666 }
4667 txn.commit();
4668 result = mdb_txn_begin(m_env, NULL, 0, txn);
4669 if (result)
4670 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4671 }
4672 result = mdb_cursor_open(txn, m_block_heights, &c_cur);
4673 if (result)
4674 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_heightr: ", result).c_str()));
4675 result = mdb_cursor_open(txn, o_heights, &c_old);
4676 if (result)
4677 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_heights: ", result).c_str()));
4678 if (!i) {
4679 MDB_stat ms;
4680 result = mdb_stat(txn, m_block_heights, &ms);
4681 if (result)
4682 throw0(DB_ERROR(lmdb_error("Failed to query block_heights table: ", result).c_str()));
4683 i = ms.ms_entries;
4684 }
4685 }
4686 result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
4687 if (result == MDB_NOTFOUND) {
4688 txn.commit();
4689 break;
4690 }
4691 else if (result)
4692 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_heights: ", result).c_str()));
4693 bh.bh_hash = *(crypto::hash *)k.mv_data;
4694 bh.bh_height = *(uint64_t *)v.mv_data;
4695 result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
4696 if (result)
4697 throw0(DB_ERROR(lmdb_error("Failed to put a record into block_heightr: ", result).c_str()));
4698 /* we delete the old records immediately, so the overall DB and mapsize should not grow.
4699 * This is a little slower than just letting mdb_drop() delete it all at the end, but
4700 * it saves a significant amount of disk space.
4701 */
4702 result = mdb_cursor_del(c_old, 0);
4703 if (result)
4704 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_heights: ", result).c_str()));
4705 i++;
4706 }
4707
4708 result = mdb_txn_begin(m_env, NULL, 0, txn);
4709 if (result)
4710 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4711 /* Delete the old table */
4712 result = mdb_drop(txn, o_heights, 1);
4713 if (result)
4714 throw0(DB_ERROR(lmdb_error("Failed to delete old block_heights table: ", result).c_str()));
4715
4716 RENAME_DB("block_heightr");
4717
4718 /* close and reopen to get old dbi slot back */
4719 mdb_dbi_close(m_env, m_block_heights);
4720 lmdb_db_open(txn, "block_heights", MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED, m_block_heights, "Failed to open db handle for block_heights");
4721 mdb_set_dupsort(txn, m_block_heights, compare_hash32);
4722 txn.commit();
4723
4724 } while(0);
4725
4726 /* old tables are k(height), v(value).
4727 * new table is DUPFIXED, k(zeroval), v{height, values...}.
4728 */
4729 do {
4730 LOG_PRINT_L1("migrating block info:");
4731
4732 MDB_dbi coins;
4733 result = mdb_txn_begin(m_env, NULL, 0, txn);
4734 if (result)
4735 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4736 result = mdb_dbi_open(txn, "block_coins", 0, &coins);
4737 if (result == MDB_NOTFOUND) {
4738 txn.abort();
4739 LOG_PRINT_L1(" block_info already migrated");
4740 break;
4741 }
4742 MDB_dbi diffs, hashes, sizes, timestamps;
4743 mdb_block_info_1 bi;
4744 MDB_val_set(nv, bi);
4745
4746 lmdb_db_open(txn, "block_diffs", 0, diffs, "Failed to open db handle for block_diffs");
4747 lmdb_db_open(txn, "block_hashes", 0, hashes, "Failed to open db handle for block_hashes");
4748 lmdb_db_open(txn, "block_sizes", 0, sizes, "Failed to open db handle for block_sizes");
4749 lmdb_db_open(txn, "block_timestamps", 0, timestamps, "Failed to open db handle for block_timestamps");
4750 MDB_cursor *c_cur, *c_coins, *c_diffs, *c_hashes, *c_sizes, *c_timestamps;
4751 i = 0;
4752 z = m_height;
4753 while(1) {
4754 MDB_val k, v;
4755 if (!(i % 2000)) {
4756 if (i) {
4757 LOGIF(el::Level::Info) {
4758 std::cout << i << " / " << z << " \r" << std::flush;
4759 }
4760 txn.commit();
4761 result = mdb_txn_begin(m_env, NULL, 0, txn);
4762 if (result)
4763 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4764 }
4765 result = mdb_cursor_open(txn, m_block_info, &c_cur);
4766 if (result)
4767 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
4768 result = mdb_cursor_open(txn, coins, &c_coins);
4769 if (result)
4770 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_coins: ", result).c_str()));
4771 result = mdb_cursor_open(txn, diffs, &c_diffs);
4772 if (result)
4773 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_diffs: ", result).c_str()));
4774 result = mdb_cursor_open(txn, hashes, &c_hashes);
4775 if (result)
4776 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_hashes: ", result).c_str()));
4777 result = mdb_cursor_open(txn, sizes, &c_sizes);
4778 if (result)
4779 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_coins: ", result).c_str()));
4780 result = mdb_cursor_open(txn, timestamps, &c_timestamps);
4781 if (result)
4782 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_timestamps: ", result).c_str()));
4783 if (!i) {
4784 MDB_stat ms;
4785 result = mdb_stat(txn, m_block_info, &ms);
4786 if (result)
4787 throw0(DB_ERROR(lmdb_error("Failed to query block_info table: ", result).c_str()));
4788 i = ms.ms_entries;
4789 }
4790 }
4791 result = mdb_cursor_get(c_coins, &k, &v, MDB_NEXT);
4792 if (result == MDB_NOTFOUND) {
4793 break;
4794 } else if (result)
4795 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_coins: ", result).c_str()));
4796 bi.bi_height = *(uint64_t *)k.mv_data;
4797 bi.bi_coins = *(uint64_t *)v.mv_data;
4798 result = mdb_cursor_get(c_diffs, &k, &v, MDB_NEXT);
4799 if (result)
4800 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_diffs: ", result).c_str()));
4801 bi.bi_diff = *(uint64_t *)v.mv_data;
4802 result = mdb_cursor_get(c_hashes, &k, &v, MDB_NEXT);
4803 if (result)
4804 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_hashes: ", result).c_str()));
4805 bi.bi_hash = *(crypto::hash *)v.mv_data;
4806 result = mdb_cursor_get(c_sizes, &k, &v, MDB_NEXT);
4807 if (result)
4808 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_sizes: ", result).c_str()));
4809 if (v.mv_size == sizeof(uint32_t))
4810 bi.bi_weight = *(uint32_t *)v.mv_data;
4811 else
4812 bi.bi_weight = *(uint64_t *)v.mv_data; // this is a 32/64 compat bug in version 0
4813 result = mdb_cursor_get(c_timestamps, &k, &v, MDB_NEXT);
4814 if (result)
4815 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_timestamps: ", result).c_str()));
4816 bi.bi_timestamp = *(uint64_t *)v.mv_data;
4817 result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
4818 if (result)
4819 throw0(DB_ERROR(lmdb_error("Failed to put a record into block_info: ", result).c_str()));
4820 result = mdb_cursor_del(c_coins, 0);
4821 if (result)
4822 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_coins: ", result).c_str()));
4823 result = mdb_cursor_del(c_diffs, 0);
4824 if (result)
4825 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_diffs: ", result).c_str()));
4826 result = mdb_cursor_del(c_hashes, 0);
4827 if (result)
4828 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_hashes: ", result).c_str()));
4829 result = mdb_cursor_del(c_sizes, 0);
4830 if (result)
4831 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_sizes: ", result).c_str()));
4832 result = mdb_cursor_del(c_timestamps, 0);
4833 if (result)
4834 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_timestamps: ", result).c_str()));
4835 i++;
4836 }
4837 mdb_cursor_close(c_timestamps);
4838 mdb_cursor_close(c_sizes);
4839 mdb_cursor_close(c_hashes);
4840 mdb_cursor_close(c_diffs);
4841 mdb_cursor_close(c_coins);
4842 result = mdb_drop(txn, timestamps, 1);
4843 if (result)
4844 throw0(DB_ERROR(lmdb_error("Failed to delete block_timestamps from the db: ", result).c_str()));
4845 result = mdb_drop(txn, sizes, 1);
4846 if (result)
4847 throw0(DB_ERROR(lmdb_error("Failed to delete block_sizes from the db: ", result).c_str()));
4848 result = mdb_drop(txn, hashes, 1);
4849 if (result)
4850 throw0(DB_ERROR(lmdb_error("Failed to delete block_hashes from the db: ", result).c_str()));
4851 result = mdb_drop(txn, diffs, 1);
4852 if (result)
4853 throw0(DB_ERROR(lmdb_error("Failed to delete block_diffs from the db: ", result).c_str()));
4854 result = mdb_drop(txn, coins, 1);
4855 if (result)
4856 throw0(DB_ERROR(lmdb_error("Failed to delete block_coins from the db: ", result).c_str()));
4857 txn.commit();
4858 } while(0);
4859
4860 do {
4861 LOG_PRINT_L1("migrating hf_versions:");
4862 MDB_dbi o_hfv;
4863
4864 unsigned int flags;
4865 result = mdb_txn_begin(m_env, NULL, 0, txn);
4866 if (result)
4867 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4868 result = mdb_dbi_flags(txn, m_hf_versions, &flags);
4869 if (result)
4870 throw0(DB_ERROR(lmdb_error("Failed to retrieve hf_versions flags: ", result).c_str()));
4871 /* if the flags are what we expect, this table has already been migrated */
4872 if (flags & MDB_INTEGERKEY) {
4873 txn.abort();
4874 LOG_PRINT_L1(" hf_versions already migrated");
4875 break;
4876 }
4877
4878 /* the hf_versions table name is the same but the old version and new version
4879 * have incompatible DB flags. Create a new table with the right flags.
4880 */
4881 o_hfv = m_hf_versions;
4882 lmdb_db_open(txn, "hf_versionr", MDB_INTEGERKEY | MDB_CREATE, m_hf_versions, "Failed to open db handle for hf_versionr");
4883
4884 MDB_cursor *c_old, *c_cur;
4885 i = 0;
4886 z = m_height;
4887
4888 while(1) {
4889 if (!(i % 2000)) {
4890 if (i) {
4891 LOGIF(el::Level::Info) {
4892 std::cout << i << " / " << z << " \r" << std::flush;
4893 }
4894 txn.commit();
4895 result = mdb_txn_begin(m_env, NULL, 0, txn);
4896 if (result)
4897 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4898 }
4899 result = mdb_cursor_open(txn, m_hf_versions, &c_cur);
4900 if (result)
4901 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for spent_keyr: ", result).c_str()));
4902 result = mdb_cursor_open(txn, o_hfv, &c_old);
4903 if (result)
4904 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for spent_keys: ", result).c_str()));
4905 if (!i) {
4906 MDB_stat ms;
4907 result = mdb_stat(txn, m_hf_versions, &ms);
4908 if (result)
4909 throw0(DB_ERROR(lmdb_error("Failed to query hf_versions table: ", result).c_str()));
4910 i = ms.ms_entries;
4911 }
4912 }
4913 result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
4914 if (result == MDB_NOTFOUND) {
4915 txn.commit();
4916 break;
4917 }
4918 else if (result)
4919 throw0(DB_ERROR(lmdb_error("Failed to get a record from hf_versions: ", result).c_str()));
4920 result = mdb_cursor_put(c_cur, &k, &v, MDB_APPEND);
4921 if (result)
4922 throw0(DB_ERROR(lmdb_error("Failed to put a record into hf_versionr: ", result).c_str()));
4923 result = mdb_cursor_del(c_old, 0);
4924 if (result)
4925 throw0(DB_ERROR(lmdb_error("Failed to delete a record from hf_versions: ", result).c_str()));
4926 i++;
4927 }
4928
4929 result = mdb_txn_begin(m_env, NULL, 0, txn);
4930 if (result)
4931 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4932 /* Delete the old table */
4933 result = mdb_drop(txn, o_hfv, 1);
4934 if (result)
4935 throw0(DB_ERROR(lmdb_error("Failed to delete old hf_versions table: ", result).c_str()));
4936 RENAME_DB("hf_versionr");
4937 mdb_dbi_close(m_env, m_hf_versions);
4938 lmdb_db_open(txn, "hf_versions", MDB_INTEGERKEY, m_hf_versions, "Failed to open db handle for hf_versions");
4939
4940 txn.commit();
4941 } while(0);
4942
4943 do {
4944 LOG_PRINT_L1("deleting old indices:");
4945
4946 /* Delete all other tables, we're just going to recreate them */
4947 MDB_dbi dbi;
4948 result = mdb_txn_begin(m_env, NULL, 0, txn);
4949 if (result)
4950 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4951
4952 result = mdb_dbi_open(txn, "tx_unlocks", 0, &dbi);
4953 if (result == MDB_NOTFOUND) {
4954 txn.abort();
4955 LOG_PRINT_L1(" old indices already deleted");
4956 break;
4957 }
4958 txn.abort();
4959
4960 #define DELETE_DB(x) do { \
4961 LOG_PRINT_L1(" " x ":"); \
4962 result = mdb_txn_begin(m_env, NULL, 0, txn); \
4963 if (result) \
4964 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str())); \
4965 result = mdb_dbi_open(txn, x, 0, &dbi); \
4966 if (!result) { \
4967 result = mdb_drop(txn, dbi, 1); \
4968 if (result) \
4969 throw0(DB_ERROR(lmdb_error("Failed to delete " x ": ", result).c_str())); \
4970 txn.commit(); \
4971 } } while(0)
4972
4973 DELETE_DB("tx_heights");
4974 DELETE_DB("output_txs");
4975 DELETE_DB("output_indices");
4976 DELETE_DB("output_keys");
4977 DELETE_DB("spent_keys");
4978 DELETE_DB("output_amounts");
4979 DELETE_DB("tx_outputs");
4980 DELETE_DB("tx_unlocks");
4981
4982 /* reopen new DBs with correct flags */
4983 result = mdb_txn_begin(m_env, NULL, 0, txn);
4984 if (result)
4985 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
4986 lmdb_db_open(txn, LMDB_OUTPUT_TXS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_output_txs, "Failed to open db handle for m_output_txs");
4987 mdb_set_dupsort(txn, m_output_txs, compare_uint64);
4988 lmdb_db_open(txn, LMDB_TX_OUTPUTS, MDB_INTEGERKEY | MDB_CREATE, m_tx_outputs, "Failed to open db handle for m_tx_outputs");
4989 lmdb_db_open(txn, LMDB_SPENT_KEYS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_spent_keys, "Failed to open db handle for m_spent_keys");
4990 mdb_set_dupsort(txn, m_spent_keys, compare_hash32);
4991 lmdb_db_open(txn, LMDB_OUTPUT_AMOUNTS, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_output_amounts, "Failed to open db handle for m_output_amounts");
4992 mdb_set_dupsort(txn, m_output_amounts, compare_uint64);
4993 txn.commit();
4994 } while(0);
4995
4996 do {
4997 LOG_PRINT_L1("migrating txs and outputs:");
4998
4999 unsigned int flags;
5000 result = mdb_txn_begin(m_env, NULL, 0, txn);
5001 if (result)
5002 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5003 result = mdb_dbi_flags(txn, m_txs, &flags);
5004 if (result)
5005 throw0(DB_ERROR(lmdb_error("Failed to retrieve txs flags: ", result).c_str()));
5006 /* if the flags are what we expect, this table has already been migrated */
5007 if (flags & MDB_INTEGERKEY) {
5008 txn.abort();
5009 LOG_PRINT_L1(" txs already migrated");
5010 break;
5011 }
5012
5013 MDB_dbi o_txs;
5014 blobdata_ref bd;
5015 block b;
5016 MDB_val hk;
5017
5018 o_txs = m_txs;
5019 mdb_set_compare(txn, o_txs, compare_hash32);
5020 lmdb_db_open(txn, "txr", MDB_INTEGERKEY | MDB_CREATE, m_txs, "Failed to open db handle for txr");
5021
5022 txn.commit();
5023
5024 MDB_cursor *c_blocks, *c_txs, *c_props, *c_cur;
5025 i = 0;
5026 z = m_height;
5027
5028 hk.mv_size = sizeof(crypto::hash);
5029 set_batch_transactions(true);
5030 batch_start(1000);
5031 txn.m_txn = m_write_txn->m_txn;
5032 m_height = 0;
5033
5034 while(1) {
5035 if (!(i % 1000)) {
5036 if (i) {
5037 LOGIF(el::Level::Info) {
5038 std::cout << i << " / " << z << " \r" << std::flush;
5039 }
5040 MDB_val_set(pk, "txblk");
5041 MDB_val_set(pv, m_height);
5042 result = mdb_cursor_put(c_props, &pk, &pv, 0);
5043 if (result)
5044 throw0(DB_ERROR(lmdb_error("Failed to update txblk property: ", result).c_str()));
5045 txn.commit();
5046 result = mdb_txn_begin(m_env, NULL, 0, txn);
5047 if (result)
5048 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5049 m_write_txn->m_txn = txn.m_txn;
5050 m_write_batch_txn->m_txn = txn.m_txn;
5051 memset(&m_wcursors, 0, sizeof(m_wcursors));
5052 }
5053 result = mdb_cursor_open(txn, m_blocks, &c_blocks);
5054 if (result)
5055 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
5056 result = mdb_cursor_open(txn, m_properties, &c_props);
5057 if (result)
5058 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for properties: ", result).c_str()));
5059 result = mdb_cursor_open(txn, o_txs, &c_txs);
5060 if (result)
5061 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs: ", result).c_str()));
5062 if (!i) {
5063 MDB_stat ms;
5064 result = mdb_stat(txn, m_txs, &ms);
5065 if (result)
5066 throw0(DB_ERROR(lmdb_error("Failed to query txs table: ", result).c_str()));
5067 i = ms.ms_entries;
5068 if (i) {
5069 MDB_val_set(pk, "txblk");
5070 result = mdb_cursor_get(c_props, &pk, &k, MDB_SET);
5071 if (result)
5072 throw0(DB_ERROR(lmdb_error("Failed to get a record from properties: ", result).c_str()));
5073 m_height = *(uint64_t *)k.mv_data;
5074 }
5075 }
5076 if (i) {
5077 result = mdb_cursor_get(c_blocks, &k, &v, MDB_SET);
5078 if (result)
5079 throw0(DB_ERROR(lmdb_error("Failed to get a record from blocks: ", result).c_str()));
5080 }
5081 }
5082 result = mdb_cursor_get(c_blocks, &k, &v, MDB_NEXT);
5083 if (result == MDB_NOTFOUND) {
5084 MDB_val_set(pk, "txblk");
5085 result = mdb_cursor_get(c_props, &pk, &v, MDB_SET);
5086 if (result)
5087 throw0(DB_ERROR(lmdb_error("Failed to get a record from props: ", result).c_str()));
5088 result = mdb_cursor_del(c_props, 0);
5089 if (result)
5090 throw0(DB_ERROR(lmdb_error("Failed to delete a record from props: ", result).c_str()));
5091 batch_stop();
5092 break;
5093 } else if (result)
5094 throw0(DB_ERROR(lmdb_error("Failed to get a record from blocks: ", result).c_str()));
5095
5096 bd = {reinterpret_cast<char*>(v.mv_data), v.mv_size};
5097 if (!parse_and_validate_block_from_blob(bd, b))
5098 throw0(DB_ERROR("Failed to parse block from blob retrieved from the db"));
5099
5100 add_transaction(null_hash, std::make_pair(b.miner_tx, tx_to_blob(b.miner_tx)));
5101 for (unsigned int j = 0; j<b.tx_hashes.size(); j++) {
5102 transaction tx;
5103 hk.mv_data = &b.tx_hashes[j];
5104 result = mdb_cursor_get(c_txs, &hk, &v, MDB_SET);
5105 if (result)
5106 throw0(DB_ERROR(lmdb_error("Failed to get record from txs: ", result).c_str()));
5107 bd = {reinterpret_cast<char*>(v.mv_data), v.mv_size};
5108 if (!parse_and_validate_tx_from_blob(bd, tx))
5109 throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
5110 add_transaction(null_hash, std::make_pair(std::move(tx), bd), &b.tx_hashes[j]);
5111 result = mdb_cursor_del(c_txs, 0);
5112 if (result)
5113 throw0(DB_ERROR(lmdb_error("Failed to get record from txs: ", result).c_str()));
5114 }
5115 i++;
5116 m_height = i;
5117 }
5118 result = mdb_txn_begin(m_env, NULL, 0, txn);
5119 if (result)
5120 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5121 result = mdb_drop(txn, o_txs, 1);
5122 if (result)
5123 throw0(DB_ERROR(lmdb_error("Failed to delete txs from the db: ", result).c_str()));
5124
5125 RENAME_DB("txr");
5126
5127 mdb_dbi_close(m_env, m_txs);
5128
5129 lmdb_db_open(txn, "txs", MDB_INTEGERKEY, m_txs, "Failed to open db handle for txs");
5130
5131 txn.commit();
5132 } while(0);
5133
5134 uint32_t version = 1;
5135 v.mv_data = (void *)&version;
5136 v.mv_size = sizeof(version);
5137 MDB_val_str(vk, "version");
5138 result = mdb_txn_begin(m_env, NULL, 0, txn);
5139 if (result)
5140 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5141 result = mdb_put(txn, m_properties, &vk, &v, 0);
5142 if (result)
5143 throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
5144 txn.commit();
5145 }
5146
5147 void BlockchainLMDB::migrate_1_2()
5148 {
5149 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
5150 uint64_t i;
5151 int result;
5152 mdb_txn_safe txn(false);
5153 MDB_val v;
5154
5155 MGINFO_YELLOW("Migrating blockchain from DB version 1 to 2 - this may take a while:");
5156 MINFO("updating txs_pruned and txs_prunable tables...");
5157
5158 do {
5159 result = mdb_txn_begin(m_env, NULL, 0, txn);
5160 if (result)
5161 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5162
5163 MDB_stat db_stats_txs;
5164 MDB_stat db_stats_txs_pruned;
5165 MDB_stat db_stats_txs_prunable;
5166 MDB_stat db_stats_txs_prunable_hash;
5167 if ((result = mdb_stat(txn, m_txs, &db_stats_txs)))
5168 throw0(DB_ERROR(lmdb_error("Failed to query m_txs: ", result).c_str()));
5169 if ((result = mdb_stat(txn, m_txs_pruned, &db_stats_txs_pruned)))
5170 throw0(DB_ERROR(lmdb_error("Failed to query m_txs_pruned: ", result).c_str()));
5171 if ((result = mdb_stat(txn, m_txs_prunable, &db_stats_txs_prunable)))
5172 throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable: ", result).c_str()));
5173 if ((result = mdb_stat(txn, m_txs_prunable_hash, &db_stats_txs_prunable_hash)))
5174 throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable_hash: ", result).c_str()));
5175 if (db_stats_txs_pruned.ms_entries != db_stats_txs_prunable.ms_entries)
5176 throw0(DB_ERROR("Mismatched sizes for txs_pruned and txs_prunable"));
5177 if (db_stats_txs_pruned.ms_entries == db_stats_txs.ms_entries)
5178 {
5179 txn.commit();
5180 MINFO("txs already migrated");
5181 break;
5182 }
5183
5184 MINFO("updating txs tables:");
5185
5186 MDB_cursor *c_old, *c_cur0, *c_cur1, *c_cur2;
5187 i = 0;
5188
5189 while(1) {
5190 if (!(i % 1000)) {
5191 if (i) {
5192 result = mdb_stat(txn, m_txs, &db_stats_txs);
5193 if (result)
5194 throw0(DB_ERROR(lmdb_error("Failed to query m_txs: ", result).c_str()));
5195 LOGIF(el::Level::Info) {
5196 std::cout << i << " / " << (i + db_stats_txs.ms_entries) << " \r" << std::flush;
5197 }
5198 txn.commit();
5199 result = mdb_txn_begin(m_env, NULL, 0, txn);
5200 if (result)
5201 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5202 }
5203 result = mdb_cursor_open(txn, m_txs_pruned, &c_cur0);
5204 if (result)
5205 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
5206 result = mdb_cursor_open(txn, m_txs_prunable, &c_cur1);
5207 if (result)
5208 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
5209 result = mdb_cursor_open(txn, m_txs_prunable_hash, &c_cur2);
5210 if (result)
5211 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_hash: ", result).c_str()));
5212 result = mdb_cursor_open(txn, m_txs, &c_old);
5213 if (result)
5214 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs: ", result).c_str()));
5215 if (!i) {
5216 i = db_stats_txs_pruned.ms_entries;
5217 }
5218 }
5219 MDB_val_set(k, i);
5220 result = mdb_cursor_get(c_old, &k, &v, MDB_SET);
5221 if (result == MDB_NOTFOUND) {
5222 txn.commit();
5223 break;
5224 }
5225 else if (result)
5226 throw0(DB_ERROR(lmdb_error("Failed to get a record from txs: ", result).c_str()));
5227
5228 cryptonote::blobdata bd{reinterpret_cast<char*>(v.mv_data), v.mv_size};
5229 transaction tx;
5230 if (!parse_and_validate_tx_from_blob(bd, tx))
5231 throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
5232 std::stringstream ss;
5233 binary_archive<true> ba(ss);
5234 bool r = tx.serialize_base(ba);
5235 if (!r)
5236 throw0(DB_ERROR("Failed to serialize pruned tx"));
5237 std::string pruned = ss.str();
5238
5239 if (pruned.size() > bd.size())
5240 throw0(DB_ERROR("Pruned tx is larger than raw tx"));
5241 if (memcmp(pruned.data(), bd.data(), pruned.size()))
5242 throw0(DB_ERROR("Pruned tx is not a prefix of the raw tx"));
5243
5244 MDB_val nv;
5245 nv.mv_data = (void*)pruned.data();
5246 nv.mv_size = pruned.size();
5247 result = mdb_cursor_put(c_cur0, (MDB_val *)&k, &nv, 0);
5248 if (result)
5249 throw0(DB_ERROR(lmdb_error("Failed to put a record into txs_pruned: ", result).c_str()));
5250
5251 nv.mv_data = (void*)(bd.data() + pruned.size());
5252 nv.mv_size = bd.size() - pruned.size();
5253 result = mdb_cursor_put(c_cur1, (MDB_val *)&k, &nv, 0);
5254 if (result)
5255 throw0(DB_ERROR(lmdb_error("Failed to put a record into txs_prunable: ", result).c_str()));
5256
5257 if (tx.version > 1)
5258 {
5259 crypto::hash prunable_hash = get_transaction_prunable_hash(tx);
5260 MDB_val_set(val_prunable_hash, prunable_hash);
5261 result = mdb_cursor_put(c_cur2, (MDB_val *)&k, &val_prunable_hash, 0);
5262 if (result)
5263 throw0(DB_ERROR(lmdb_error("Failed to put a record into txs_prunable_hash: ", result).c_str()));
5264 }
5265
5266 result = mdb_cursor_del(c_old, 0);
5267 if (result)
5268 throw0(DB_ERROR(lmdb_error("Failed to delete a record from txs: ", result).c_str()));
5269
5270 i++;
5271 }
5272 } while(0);
5273
5274 uint32_t version = 2;
5275 v.mv_data = (void *)&version;
5276 v.mv_size = sizeof(version);
5277 MDB_val_str(vk, "version");
5278 result = mdb_txn_begin(m_env, NULL, 0, txn);
5279 if (result)
5280 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5281 result = mdb_put(txn, m_properties, &vk, &v, 0);
5282 if (result)
5283 throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
5284 txn.commit();
5285 }
5286
5287 void BlockchainLMDB::migrate_2_3()
5288 {
5289 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
5290 uint64_t i;
5291 int result;
5292 mdb_txn_safe txn(false);
5293 MDB_val k, v;
5294 char *ptr;
5295
5296 MGINFO_YELLOW("Migrating blockchain from DB version 2 to 3 - this may take a while:");
5297
5298 do {
5299 LOG_PRINT_L1("migrating block info:");
5300
5301 result = mdb_txn_begin(m_env, NULL, 0, txn);
5302 if (result)
5303 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5304
5305 MDB_stat db_stats;
5306 if ((result = mdb_stat(txn, m_blocks, &db_stats)))
5307 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
5308 const uint64_t blockchain_height = db_stats.ms_entries;
5309
5310 MDEBUG("enumerating rct outputs...");
5311 std::vector<uint64_t> distribution(blockchain_height, 0);
5312 bool r = for_all_outputs(0, [&](uint64_t height) {
5313 if (height >= blockchain_height)
5314 {
5315 MERROR("Output found claiming height >= blockchain height");
5316 return false;
5317 }
5318 distribution[height]++;
5319 return true;
5320 });
5321 if (!r)
5322 throw0(DB_ERROR("Failed to build rct output distribution"));
5323 for (size_t i = 1; i < distribution.size(); ++i)
5324 distribution[i] += distribution[i - 1];
5325
5326 /* the block_info table name is the same but the old version and new version
5327 * have incompatible data. Create a new table. We want the name to be similar
5328 * to the old name so that it will occupy the same location in the DB.
5329 */
5330 MDB_dbi o_block_info = m_block_info;
5331 lmdb_db_open(txn, "block_infn", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
5332 mdb_set_dupsort(txn, m_block_info, compare_uint64);
5333
5334 MDB_cursor *c_old, *c_cur;
5335 i = 0;
5336 while(1) {
5337 if (!(i % 1000)) {
5338 if (i) {
5339 LOGIF(el::Level::Info) {
5340 std::cout << i << " / " << blockchain_height << " \r" << std::flush;
5341 }
5342 txn.commit();
5343 result = mdb_txn_begin(m_env, NULL, 0, txn);
5344 if (result)
5345 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5346 }
5347 result = mdb_cursor_open(txn, m_block_info, &c_cur);
5348 if (result)
5349 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_infn: ", result).c_str()));
5350 result = mdb_cursor_open(txn, o_block_info, &c_old);
5351 if (result)
5352 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
5353 if (!i) {
5354 result = mdb_stat(txn, m_block_info, &db_stats);
5355 if (result)
5356 throw0(DB_ERROR(lmdb_error("Failed to query m_block_info: ", result).c_str()));
5357 i = db_stats.ms_entries;
5358 }
5359 }
5360 result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
5361 if (result == MDB_NOTFOUND) {
5362 txn.commit();
5363 break;
5364 }
5365 else if (result)
5366 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_info: ", result).c_str()));
5367 const mdb_block_info_1 *bi_old = (const mdb_block_info_1*)v.mv_data;
5368 mdb_block_info_2 bi;
5369 bi.bi_height = bi_old->bi_height;
5370 bi.bi_timestamp = bi_old->bi_timestamp;
5371 bi.bi_coins = bi_old->bi_coins;
5372 bi.bi_weight = bi_old->bi_weight;
5373 bi.bi_diff = bi_old->bi_diff;
5374 bi.bi_hash = bi_old->bi_hash;
5375 if (bi_old->bi_height >= distribution.size())
5376 throw0(DB_ERROR("Bad height in block_info record"));
5377 bi.bi_cum_rct = distribution[bi_old->bi_height];
5378 MDB_val_set(nv, bi);
5379 result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
5380 if (result)
5381 throw0(DB_ERROR(lmdb_error("Failed to put a record into block_infn: ", result).c_str()));
5382 /* we delete the old records immediately, so the overall DB and mapsize should not grow.
5383 * This is a little slower than just letting mdb_drop() delete it all at the end, but
5384 * it saves a significant amount of disk space.
5385 */
5386 result = mdb_cursor_del(c_old, 0);
5387 if (result)
5388 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_info: ", result).c_str()));
5389 i++;
5390 }
5391
5392 result = mdb_txn_begin(m_env, NULL, 0, txn);
5393 if (result)
5394 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5395 /* Delete the old table */
5396 result = mdb_drop(txn, o_block_info, 1);
5397 if (result)
5398 throw0(DB_ERROR(lmdb_error("Failed to delete old block_info table: ", result).c_str()));
5399
5400 RENAME_DB("block_infn");
5401 mdb_dbi_close(m_env, m_block_info);
5402
5403 lmdb_db_open(txn, "block_info", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
5404 mdb_set_dupsort(txn, m_block_info, compare_uint64);
5405
5406 txn.commit();
5407 } while(0);
5408
5409 uint32_t version = 3;
5410 v.mv_data = (void *)&version;
5411 v.mv_size = sizeof(version);
5412 MDB_val_str(vk, "version");
5413 result = mdb_txn_begin(m_env, NULL, 0, txn);
5414 if (result)
5415 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5416 result = mdb_put(txn, m_properties, &vk, &v, 0);
5417 if (result)
5418 throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
5419 txn.commit();
5420 }
5421
5422 void BlockchainLMDB::migrate_3_4()
5423 {
5424 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
5425 uint64_t i;
5426 int result;
5427 mdb_txn_safe txn(false);
5428 MDB_val k, v;
5429 char *ptr;
5430 bool past_long_term_weight = false;
5431
5432 MGINFO_YELLOW("Migrating blockchain from DB version 3 to 4 - this may take a while:");
5433
5434 do {
5435 LOG_PRINT_L1("migrating block info:");
5436
5437 result = mdb_txn_begin(m_env, NULL, 0, txn);
5438 if (result)
5439 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5440
5441 MDB_stat db_stats;
5442 if ((result = mdb_stat(txn, m_blocks, &db_stats)))
5443 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
5444 const uint64_t blockchain_height = db_stats.ms_entries;
5445
5446 boost::circular_buffer<uint64_t> long_term_block_weights(CRYPTONOTE_LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE);
5447
5448 /* the block_info table name is the same but the old version and new version
5449 * have incompatible data. Create a new table. We want the name to be similar
5450 * to the old name so that it will occupy the same location in the DB.
5451 */
5452 MDB_dbi o_block_info = m_block_info;
5453 lmdb_db_open(txn, "block_infn", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
5454 mdb_set_dupsort(txn, m_block_info, compare_uint64);
5455
5456
5457 MDB_cursor *c_blocks;
5458 result = mdb_cursor_open(txn, m_blocks, &c_blocks);
5459 if (result)
5460 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
5461
5462 MDB_cursor *c_old, *c_cur;
5463 i = 0;
5464 while(1) {
5465 if (!(i % 1000)) {
5466 if (i) {
5467 LOGIF(el::Level::Info) {
5468 std::cout << i << " / " << blockchain_height << " \r" << std::flush;
5469 }
5470 txn.commit();
5471 result = mdb_txn_begin(m_env, NULL, 0, txn);
5472 if (result)
5473 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5474 }
5475 result = mdb_cursor_open(txn, m_block_info, &c_cur);
5476 if (result)
5477 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_infn: ", result).c_str()));
5478 result = mdb_cursor_open(txn, o_block_info, &c_old);
5479 if (result)
5480 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
5481 result = mdb_cursor_open(txn, m_blocks, &c_blocks);
5482 if (result)
5483 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
5484 if (!i) {
5485 result = mdb_stat(txn, m_block_info, &db_stats);
5486 if (result)
5487 throw0(DB_ERROR(lmdb_error("Failed to query m_block_info: ", result).c_str()));
5488 i = db_stats.ms_entries;
5489 }
5490 }
5491 result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
5492 if (result == MDB_NOTFOUND) {
5493 txn.commit();
5494 break;
5495 }
5496 else if (result)
5497 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_info: ", result).c_str()));
5498 const mdb_block_info_2 *bi_old = (const mdb_block_info_2*)v.mv_data;
5499 mdb_block_info_3 bi;
5500 bi.bi_height = bi_old->bi_height;
5501 bi.bi_timestamp = bi_old->bi_timestamp;
5502 bi.bi_coins = bi_old->bi_coins;
5503 bi.bi_weight = bi_old->bi_weight;
5504 bi.bi_diff = bi_old->bi_diff;
5505 bi.bi_hash = bi_old->bi_hash;
5506 bi.bi_cum_rct = bi_old->bi_cum_rct;
5507
5508 // get block major version to determine which rule is in place
5509 if (!past_long_term_weight)
5510 {
5511 MDB_val_copy<uint64_t> kb(bi.bi_height);
5512 MDB_val vb;
5513 result = mdb_cursor_get(c_blocks, &kb, &vb, MDB_SET);
5514 if (result)
5515 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
5516 if (vb.mv_size == 0)
5517 throw0(DB_ERROR("Invalid data from m_blocks"));
5518 const uint8_t block_major_version = *((const uint8_t*)vb.mv_data);
5519 if (block_major_version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT)
5520 past_long_term_weight = true;
5521 }
5522
5523 uint64_t long_term_block_weight;
5524 if (past_long_term_weight)
5525 {
5526 std::vector<uint64_t> weights(long_term_block_weights.begin(), long_term_block_weights.end());
5527 uint64_t long_term_effective_block_median_weight = std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V5, epee::misc_utils::median(weights));
5528 long_term_block_weight = std::min<uint64_t>(bi.bi_weight, long_term_effective_block_median_weight + long_term_effective_block_median_weight * 2 / 5);
5529 }
5530 else
5531 {
5532 long_term_block_weight = bi.bi_weight;
5533 }
5534 long_term_block_weights.push_back(long_term_block_weight);
5535 bi.bi_long_term_block_weight = long_term_block_weight;
5536
5537 MDB_val_set(nv, bi);
5538 result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
5539 if (result)
5540 throw0(DB_ERROR(lmdb_error("Failed to put a record into block_infn: ", result).c_str()));
5541 /* we delete the old records immediately, so the overall DB and mapsize should not grow.
5542 * This is a little slower than just letting mdb_drop() delete it all at the end, but
5543 * it saves a significant amount of disk space.
5544 */
5545 result = mdb_cursor_del(c_old, 0);
5546 if (result)
5547 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_info: ", result).c_str()));
5548 i++;
5549 }
5550
5551 result = mdb_txn_begin(m_env, NULL, 0, txn);
5552 if (result)
5553 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5554 /* Delete the old table */
5555 result = mdb_drop(txn, o_block_info, 1);
5556 if (result)
5557 throw0(DB_ERROR(lmdb_error("Failed to delete old block_info table: ", result).c_str()));
5558
5559 RENAME_DB("block_infn");
5560 mdb_dbi_close(m_env, m_block_info);
5561
5562 lmdb_db_open(txn, "block_info", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
5563 mdb_set_dupsort(txn, m_block_info, compare_uint64);
5564
5565 txn.commit();
5566 } while(0);
5567
5568 uint32_t version = 4;
5569 v.mv_data = (void *)&version;
5570 v.mv_size = sizeof(version);
5571 MDB_val_str(vk, "version");
5572 result = mdb_txn_begin(m_env, NULL, 0, txn);
5573 if (result)
5574 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5575 result = mdb_put(txn, m_properties, &vk, &v, 0);
5576 if (result)
5577 throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
5578 txn.commit();
5579 }
5580
5581 void BlockchainLMDB::migrate_4_5()
5582 {
5583 LOG_PRINT_L3("BlockchainLMDB::" << __func__);
5584 uint64_t i;
5585 int result;
5586 mdb_txn_safe txn(false);
5587 MDB_val k, v;
5588 char *ptr;
5589
5590 MGINFO_YELLOW("Migrating blockchain from DB version 4 to 5 - this may take a while:");
5591
5592 do {
5593 LOG_PRINT_L1("migrating block info:");
5594
5595 result = mdb_txn_begin(m_env, NULL, 0, txn);
5596 if (result)
5597 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5598
5599 MDB_stat db_stats;
5600 if ((result = mdb_stat(txn, m_blocks, &db_stats)))
5601 throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
5602 const uint64_t blockchain_height = db_stats.ms_entries;
5603
5604 /* the block_info table name is the same but the old version and new version
5605 * have incompatible data. Create a new table. We want the name to be similar
5606 * to the old name so that it will occupy the same location in the DB.
5607 */
5608 MDB_dbi o_block_info = m_block_info;
5609 lmdb_db_open(txn, "block_infn", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
5610 mdb_set_dupsort(txn, m_block_info, compare_uint64);
5611
5612
5613 MDB_cursor *c_blocks;
5614 result = mdb_cursor_open(txn, m_blocks, &c_blocks);
5615 if (result)
5616 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
5617
5618 MDB_cursor *c_old, *c_cur;
5619 i = 0;
5620 while(1) {
5621 if (!(i % 1000)) {
5622 if (i) {
5623 LOGIF(el::Level::Info) {
5624 std::cout << i << " / " << blockchain_height << " \r" << std::flush;
5625 }
5626 txn.commit();
5627 result = mdb_txn_begin(m_env, NULL, 0, txn);
5628 if (result)
5629 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5630 }
5631 result = mdb_cursor_open(txn, m_block_info, &c_cur);
5632 if (result)
5633 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_infn: ", result).c_str()));
5634 result = mdb_cursor_open(txn, o_block_info, &c_old);
5635 if (result)
5636 throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
5637 if (!i) {
5638 result = mdb_stat(txn, m_block_info, &db_stats);
5639 if (result)
5640 throw0(DB_ERROR(lmdb_error("Failed to query m_block_info: ", result).c_str()));
5641 i = db_stats.ms_entries;
5642 }
5643 }
5644 result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
5645 if (result == MDB_NOTFOUND) {
5646 txn.commit();
5647 break;
5648 }
5649 else if (result)
5650 throw0(DB_ERROR(lmdb_error("Failed to get a record from block_info: ", result).c_str()));
5651 const mdb_block_info_3 *bi_old = (const mdb_block_info_3*)v.mv_data;
5652 mdb_block_info_4 bi;
5653 bi.bi_height = bi_old->bi_height;
5654 bi.bi_timestamp = bi_old->bi_timestamp;
5655 bi.bi_coins = bi_old->bi_coins;
5656 bi.bi_weight = bi_old->bi_weight;
5657 bi.bi_diff_lo = bi_old->bi_diff;
5658 bi.bi_diff_hi = 0;
5659 bi.bi_hash = bi_old->bi_hash;
5660 bi.bi_cum_rct = bi_old->bi_cum_rct;
5661 bi.bi_long_term_block_weight = bi_old->bi_long_term_block_weight;
5662
5663 MDB_val_set(nv, bi);
5664 result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
5665 if (result)
5666 throw0(DB_ERROR(lmdb_error("Failed to put a record into block_infn: ", result).c_str()));
5667 /* we delete the old records immediately, so the overall DB and mapsize should not grow.
5668 * This is a little slower than just letting mdb_drop() delete it all at the end, but
5669 * it saves a significant amount of disk space.
5670 */
5671 result = mdb_cursor_del(c_old, 0);
5672 if (result)
5673 throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_info: ", result).c_str()));
5674 i++;
5675 }
5676
5677 result = mdb_txn_begin(m_env, NULL, 0, txn);
5678 if (result)
5679 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5680 /* Delete the old table */
5681 result = mdb_drop(txn, o_block_info, 1);
5682 if (result)
5683 throw0(DB_ERROR(lmdb_error("Failed to delete old block_info table: ", result).c_str()));
5684
5685 RENAME_DB("block_infn");
5686 mdb_dbi_close(m_env, m_block_info);
5687
5688 lmdb_db_open(txn, "block_info", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
5689 mdb_set_dupsort(txn, m_block_info, compare_uint64);
5690
5691 txn.commit();
5692 } while(0);
5693
5694 uint32_t version = 5;
5695 v.mv_data = (void *)&version;
5696 v.mv_size = sizeof(version);
5697 MDB_val_str(vk, "version");
5698 result = mdb_txn_begin(m_env, NULL, 0, txn);
5699 if (result)
5700 throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
5701 result = mdb_put(txn, m_properties, &vk, &v, 0);
5702 if (result)
5703 throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
5704 txn.commit();
5705 }
5706
5707 void BlockchainLMDB::migrate(const uint32_t oldversion)
5708 {
5709 if (oldversion < 1)
5710 migrate_0_1();
5711 if (oldversion < 2)
5712 migrate_1_2();
5713 if (oldversion < 3)
5714 migrate_2_3();
5715 if (oldversion < 4)
5716 migrate_3_4();
5717 if (oldversion < 5)
5718 migrate_4_5();
5719 }
5720
5721 } // namespace cryptonote