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