Repository navigation
Expand file tree
/
Copy pathdb_bdb.cpp
More file actions
2339 lines (1908 loc) · 69.2 KB
/
Copy pathdb_bdb.cpp
File metadata and controls
2339 lines (1908 loc) · 69.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2014-2018, The Monero Project
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "db_bdb.h"
#include <boost/filesystem.hpp>
#include <memory> // std::unique_ptr
#include <cstring> // memcpy
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "crypto/crypto.h"
#include "profile_tools.h"
using epee::string_tools::pod_to_hex;
#define DB_DEFAULT_TX (m_write_txn != nullptr ? *m_write_txn : (DbTxn*) nullptr)
// Increase when the DB changes in a non backward compatible way, and there
// is no automatic conversion, so that a full resync is needed.
#define VERSION 0
namespace
{
template <typename T>
inline void throw0(const T &e)
{
LOG_PRINT_L0(e.what());
throw e;
}
template <typename T>
inline void throw1(const T &e)
{
LOG_PRINT_L1(e.what());
throw e;
}
// cursor needs to be closed when it goes out of scope,
// this helps if the function using it throws
struct bdb_cur
{
bdb_cur(DbTxn* txn, Db* dbi)
{
if (dbi->cursor(txn, &m_cur, 0))
throw0(cryptonote::DB_ERROR("Error opening db cursor"));
done = false;
}
~bdb_cur()
{
close();
}
operator Dbc*()
{
return m_cur;
}
operator Dbc**()
{
return &m_cur;
}
Dbc* operator->()
{
return m_cur;
}
void close()
{
if (!done)
{
m_cur->close();
done = true;
}
}
private:
Dbc* m_cur;
bool done;
};
const char* const BDB_BLOCKS = "blocks";
const char* const BDB_BLOCK_TIMESTAMPS = "block_timestamps";
const char* const BDB_BLOCK_HEIGHTS = "block_heights";
const char* const BDB_BLOCK_HASHES = "block_hashes";
const char* const BDB_BLOCK_SIZES = "block_sizes";
const char* const BDB_BLOCK_DIFFS = "block_diffs";
const char* const BDB_BLOCK_COINS = "block_coins";
const char* const BDB_TXS = "txs";
const char* const BDB_TX_UNLOCKS = "tx_unlocks";
const char* const BDB_TX_HEIGHTS = "tx_heights";
const char* const BDB_TX_OUTPUTS = "tx_outputs";
const char* const BDB_OUTPUT_TXS = "output_txs";
const char* const BDB_OUTPUT_INDICES = "output_indices";
const char* const BDB_OUTPUT_AMOUNTS = "output_amounts";
const char* const BDB_OUTPUT_KEYS = "output_keys";
const char* const BDB_SPENT_KEYS = "spent_keys";
const char* const BDB_HF_STARTING_HEIGHTS = "hf_starting_heights";
const char* const BDB_HF_VERSIONS = "hf_versions";
const char* const BDB_PROPERTIES = "properties";
const unsigned int MB = 1024 * 1024;
// ND: FIXME: db keeps running out of locks when doing full syncs. Possible bug??? Set it to 5K for now.
const unsigned int DB_MAX_LOCKS = 5000;
const unsigned int DB_BUFFER_LENGTH = 32 * MB;
// 256MB cache adjust as necessary using DB_CONFIG
const unsigned int DB_DEF_CACHESIZE = 256 * MB;
#if defined(BDB_BULK_CAN_THREAD)
const unsigned int DB_BUFFER_COUNT = tools::get_max_concurrency();
#else
const unsigned int DB_BUFFER_COUNT = 1;
#endif
template<typename T>
struct Dbt_copy: public Dbt
{
Dbt_copy(const T &t) :
t_copy(t)
{
init();
}
Dbt_copy()
{
init();
}
void init()
{
set_data(&t_copy);
set_size(sizeof(T));
set_ulen(sizeof(T));
set_flags(DB_DBT_USERMEM);
}
operator T()
{
return t_copy;
}
private:
T t_copy;
};
template<>
struct Dbt_copy<cryptonote::blobdata>: public Dbt
{
Dbt_copy(const cryptonote::blobdata &bd) :
m_data(new char[bd.size()])
{
memcpy(m_data.get(), bd.data(), bd.size());
set_data(m_data.get());
set_size(bd.size());
set_ulen(bd.size());
set_flags(DB_DBT_USERMEM);
}
private:
std::unique_ptr<char[]> m_data;
};
template<>
struct Dbt_copy<const char*>: public Dbt
{
Dbt_copy(const char *s) :
m_data(strdup(s))
{
size_t len = strlen(s) + 1; // include the NUL, makes it easier for compare
set_data(m_data.get());
set_size(len);
set_ulen(len);
set_flags(DB_DBT_USERMEM);
}
private:
std::unique_ptr<char[]> m_data;
};
struct Dbt_safe : public Dbt
{
Dbt_safe()
{
set_data(NULL);
set_flags(DB_DBT_MALLOC);
}
~Dbt_safe()
{
void* buf = get_data();
if (buf != NULL)
{
free(buf);
}
}
};
} // anonymous namespace
namespace cryptonote
{
void BlockchainBDB::add_block(const block& blk, size_t block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated, const crypto::hash& blk_hash)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<crypto::hash> val_h(blk_hash);
if (m_block_heights->exists(DB_DEFAULT_TX, &val_h, 0) == 0)
throw1(BLOCK_EXISTS("Attempting to add block that's already in the db"));
if (m_height > 0)
{
Dbt_copy<crypto::hash> parent_key(blk.prev_id);
Dbt_copy<uint32_t> parent_h;
if (m_block_heights->get(DB_DEFAULT_TX, &parent_key, &parent_h, 0))
{
LOG_PRINT_L3("m_height: " << m_height);
LOG_PRINT_L3("parent_key: " << blk.prev_id);
throw0(DB_ERROR("Failed to get top block hash to check for new block's parent"));
}
uint32_t parent_height = parent_h;
if (parent_height != m_height)
throw0(BLOCK_PARENT_DNE("Top block is not new block's parent"));
}
Dbt_copy<uint32_t> key(m_height + 1);
Dbt_copy<blobdata> blob(block_to_blob(blk));
auto res = m_blocks->put(DB_DEFAULT_TX, &key, &blob, 0);
if (res)
throw0(DB_ERROR("Failed to add block blob to db transaction."));
Dbt_copy<size_t> sz(block_weight);
if (m_block_sizes->put(DB_DEFAULT_TX, &key, &sz, 0))
throw0(DB_ERROR("Failed to add block size to db transaction."));
Dbt_copy<uint64_t> ts(blk.timestamp);
if (m_block_timestamps->put(DB_DEFAULT_TX, &key, &ts, 0))
throw0(DB_ERROR("Failed to add block timestamp to db transaction."));
Dbt_copy<difficulty_type> diff(cumulative_difficulty);
if (m_block_diffs->put(DB_DEFAULT_TX, &key, &diff, 0))
throw0(DB_ERROR("Failed to add block cumulative difficulty to db transaction."));
Dbt_copy<uint64_t> coinsgen(coins_generated);
if (m_block_coins->put(DB_DEFAULT_TX, &key, &coinsgen, 0))
throw0(DB_ERROR("Failed to add block total generated coins to db transaction."));
if (m_block_heights->put(DB_DEFAULT_TX, &val_h, &key, 0))
throw0(DB_ERROR("Failed to add block height by hash to db transaction."));
if (m_block_hashes->put(DB_DEFAULT_TX, &key, &val_h, 0))
throw0(DB_ERROR("Failed to add block hash to db transaction."));
}
void BlockchainBDB::remove_block()
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
if (m_height == 0)
throw0(BLOCK_DNE ("Attempting to remove block from an empty blockchain"));
Dbt_copy<uint32_t> k(m_height);
Dbt_copy<crypto::hash> h;
if (m_block_hashes->get(DB_DEFAULT_TX, &k, &h, 0))
throw1(BLOCK_DNE("Attempting to remove block that's not in the db"));
if (m_blocks->del(DB_DEFAULT_TX, &k, 0))
throw1(DB_ERROR("Failed to add removal of block to db transaction"));
if (m_block_sizes->del(DB_DEFAULT_TX, &k, 0))
throw1(DB_ERROR("Failed to add removal of block size to db transaction"));
if (m_block_diffs->del(DB_DEFAULT_TX, &k, 0))
throw1(DB_ERROR("Failed to add removal of block cumulative difficulty to db transaction"));
if (m_block_coins->del(DB_DEFAULT_TX, &k, 0))
throw1(DB_ERROR("Failed to add removal of block total generated coins to db transaction"));
if (m_block_timestamps->del(DB_DEFAULT_TX, &k, 0))
throw1(DB_ERROR("Failed to add removal of block timestamp to db transaction"));
if (m_block_heights->del(DB_DEFAULT_TX, &h, 0))
throw1(DB_ERROR("Failed to add removal of block height by hash to db transaction"));
if (m_block_hashes->del(DB_DEFAULT_TX, &k, 0))
throw1(DB_ERROR("Failed to add removal of block hash to db transaction"));
}
void BlockchainBDB::add_transaction_data(const crypto::hash& blk_hash, const transaction& tx, const crypto::hash& tx_hash, const crypto::hash& tx_prunable_hash)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<crypto::hash> val_h(tx_hash);
if (m_txs->exists(DB_DEFAULT_TX, &val_h, 0) == 0)
throw1(TX_EXISTS("Attempting to add transaction that's already in the db"));
Dbt_copy<blobdata> blob(tx_to_blob(tx));
if (m_txs->put(DB_DEFAULT_TX, &val_h, &blob, 0))
throw0(DB_ERROR("Failed to add tx blob to db transaction"));
Dbt_copy<uint64_t> height(m_height + 1);
if (m_tx_heights->put(DB_DEFAULT_TX, &val_h, &height, 0))
throw0(DB_ERROR("Failed to add tx block height to db transaction"));
Dbt_copy<uint64_t> unlock_time(tx.unlock_time);
if (m_tx_unlocks->put(DB_DEFAULT_TX, &val_h, &unlock_time, 0))
throw0(DB_ERROR("Failed to add tx unlock time to db transaction"));
}
void BlockchainBDB::remove_transaction_data(const crypto::hash& tx_hash, const transaction& tx)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<crypto::hash> val_h(tx_hash);
if (m_txs->exists(DB_DEFAULT_TX, &val_h, 0))
throw1(TX_DNE("Attempting to remove transaction that isn't in the db"));
if (m_txs->del(DB_DEFAULT_TX, &val_h, 0))
throw1(DB_ERROR("Failed to add removal of tx to db transaction"));
if (m_tx_unlocks->del(DB_DEFAULT_TX, &val_h, 0))
throw1(DB_ERROR("Failed to add removal of tx unlock time to db transaction"));
if (m_tx_heights->del(DB_DEFAULT_TX, &val_h, 0))
throw1(DB_ERROR("Failed to add removal of tx block height to db transaction"));
remove_tx_outputs(tx_hash, tx);
auto result = m_tx_outputs->del(DB_DEFAULT_TX, &val_h, 0);
if (result == DB_NOTFOUND)
LOG_PRINT_L1("tx has no outputs to remove: " << tx_hash);
else if (result)
throw1(DB_ERROR("Failed to add removal of tx outputs to db transaction"));
}
void BlockchainBDB::add_output(const crypto::hash& tx_hash, const tx_out& tx_output, const uint64_t& local_index, const uint64_t unlock_time, const rct::key *commitment)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<uint32_t> k(m_num_outputs + 1);
Dbt_copy<crypto::hash> v(tx_hash);
if (m_output_txs->put(DB_DEFAULT_TX, &k, &v, 0))
throw0(DB_ERROR("Failed to add output tx hash to db transaction"));
if (m_tx_outputs->put(DB_DEFAULT_TX, &v, &k, 0))
throw0(DB_ERROR("Failed to add tx output index to db transaction"));
Dbt_copy<uint64_t> val_local_index(local_index);
if (m_output_indices->put(DB_DEFAULT_TX, &k, &val_local_index, 0))
throw0(DB_ERROR("Failed to add tx output index to db transaction"));
Dbt_copy<uint64_t> val_amount(tx_output.amount);
if (m_output_amounts->put(DB_DEFAULT_TX, &val_amount, &k, 0))
throw0(DB_ERROR("Failed to add output amount to db transaction."));
if (tx_output.target.type() == typeid(txout_to_key))
{
output_data_t od;
od.pubkey = boost::get < txout_to_key > (tx_output.target).key;
od.unlock_time = unlock_time;
od.height = m_height;
Dbt_copy<output_data_t> data(od);
if (m_output_keys->put(DB_DEFAULT_TX, &k, &data, 0))
throw0(DB_ERROR("Failed to add output pubkey to db transaction"));
}
else
{
throw0(DB_ERROR("Wrong output type: expected txout_to_key"));
}
m_num_outputs++;
}
void BlockchainBDB::remove_tx_outputs(const crypto::hash& tx_hash, const transaction& tx)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
bdb_cur cur(DB_DEFAULT_TX, m_tx_outputs);
Dbt_copy<crypto::hash> k(tx_hash);
Dbt_copy<uint32_t> v;
auto result = cur->get(&k, &v, DB_SET);
if (result == DB_NOTFOUND)
{
LOG_PRINT_L2("tx has no outputs, so no global output indices");
}
else if (result)
{
throw0(DB_ERROR("DB error attempting to get an output"));
}
else
{
result = cur->get(&k, &v, DB_NEXT_NODUP);
if (result != 0 && result != DB_NOTFOUND)
throw0(DB_ERROR("DB error attempting to get next non-duplicate tx hash"));
if (result == 0)
result = cur->get(&k, &v, DB_PREV);
else if (result == DB_NOTFOUND)
result = cur->get(&k, &v, DB_LAST);
db_recno_t num_elems = 0;
cur->count(&num_elems, 0);
// remove in order: from newest to oldest
for (uint64_t i = num_elems; i > 0; --i)
{
const tx_out tx_output = tx.vout[i-1];
remove_output(v, tx_output.amount);
if (i > 1)
{
cur->get(&k, &v, DB_PREV_DUP);
}
}
}
cur.close();
}
// TODO: probably remove this function
void BlockchainBDB::remove_output(const tx_out& tx_output)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__ << " (unused version - does nothing)");
return;
}
void BlockchainBDB::remove_output(const uint64_t& out_index, const uint64_t amount)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<uint32_t> k(out_index);
auto result = m_output_indices->del(DB_DEFAULT_TX, &k, 0);
if (result == DB_NOTFOUND)
{
LOG_PRINT_L0("Unexpected: global output index not found in m_output_indices");
}
else if (result)
{
throw1(DB_ERROR("Error adding removal of output tx index to db transaction"));
}
result = m_output_txs->del(DB_DEFAULT_TX, &k, 0);
// if (result != 0 && result != DB_NOTFOUND)
// throw1(DB_ERROR("Error adding removal of output tx hash to db transaction"));
if (result == DB_NOTFOUND)
{
LOG_PRINT_L0("Unexpected: global output index not found in m_output_txs");
}
else if (result)
{
throw1(DB_ERROR("Error adding removal of output tx hash to db transaction"));
}
result = m_output_keys->del(DB_DEFAULT_TX, &k, 0);
if (result == DB_NOTFOUND)
{
LOG_PRINT_L0("Unexpected: global output index not found in m_output_keys");
}
else if (result)
throw1(DB_ERROR("Error adding removal of output pubkey to db transaction"));
remove_amount_output_index(amount, out_index);
m_num_outputs--;
}
void BlockchainBDB::remove_amount_output_index(const uint64_t amount, const uint64_t global_output_index)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
bdb_cur cur(DB_DEFAULT_TX, m_output_amounts);
Dbt_copy<uint64_t> k(amount);
Dbt_copy<uint32_t> v;
auto result = cur->get(&k, &v, DB_SET);
if (result == DB_NOTFOUND)
throw1(OUTPUT_DNE("Attempting to get an output index by amount and amount index, but amount not found"));
else if (result)
throw0(DB_ERROR("DB error attempting to get an output"));
db_recno_t num_elems = 0;
cur->count(&num_elems, 0);
// workaround for Berkeley DB to start at end of k's duplicate list:
// if next key exists:
// - move cursor to start of next key's duplicate list, then move back one
// duplicate element to reach the end of the original key's duplicate
// list.
//
// else if the next key doesn't exist:
// - that means we're already on the last key.
// - move cursor to last element in the db, which is the last element of
// the desired key's duplicate list.
result = cur->get(&k, &v, DB_NEXT_NODUP);
if (result != 0 && result != DB_NOTFOUND)
throw0(DB_ERROR("DB error attempting to get next non-duplicate output amount"));
if (result == 0)
result = cur->get(&k, &v, DB_PREV);
else if (result == DB_NOTFOUND)
result = cur->get(&k, &v, DB_LAST);
bool found_index = false;
uint64_t amount_output_index = 0;
uint64_t goi = 0;
for (uint64_t i = num_elems; i > 0; --i)
{
goi = v;
if (goi == global_output_index)
{
amount_output_index = i-1;
found_index = true;
break;
}
if (i > 1)
cur->get(&k, &v, DB_PREV_DUP);
}
if (found_index)
{
// found the amount output index
// now delete it
result = cur->del(0);
if (result)
throw0(DB_ERROR(std::string("Error deleting amount output index ").append(boost::lexical_cast<std::string>(amount_output_index)).c_str()));
}
else
{
// not found
throw1(OUTPUT_DNE("Failed to find amount output index"));
}
cur.close();
}
void BlockchainBDB::add_spent_key(const crypto::key_image& k_image)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<crypto::key_image> val_key(k_image);
if (m_spent_keys->exists(DB_DEFAULT_TX, &val_key, 0) == 0)
throw1(KEY_IMAGE_EXISTS("Attempting to add spent key image that's already in the db"));
Dbt_copy<char> val('\0');
if (m_spent_keys->put(DB_DEFAULT_TX, &val_key, &val, 0))
throw1(DB_ERROR("Error adding spent key image to db transaction."));
}
void BlockchainBDB::remove_spent_key(const crypto::key_image& k_image)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
Dbt_copy<crypto::key_image> k(k_image);
auto result = m_spent_keys->del(DB_DEFAULT_TX, &k, 0);
if (result != 0 && result != DB_NOTFOUND)
throw1(DB_ERROR("Error adding removal of key image to db transaction"));
}
bool BlockchainBDB::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
bdb_cur cur(DB_DEFAULT_TX, m_spent_keys);
Dbt_copy<crypto::key_image> k;
Dbt_copy<char> v;
bool ret = true;
int result;
while ((result = cur->get(&k, &v, DB_NEXT)) == 0)
{
if (!f(k))
{
ret = false;
break;
}
}
if (result != DB_NOTFOUND)
ret = false;
cur.close();
return ret;
}
bool BlockchainBDB::for_all_blocks(std::function<bool(uint64_t, const crypto::hash&, const cryptonote::block&)> f) const
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
bdb_cur cur(DB_DEFAULT_TX, m_blocks);
Dbt_copy<uint32_t> k;
Dbt_safe v;
bool ret = true;
int result;
while ((result = cur->get(&k, &v, DB_NEXT)) == 0)
{
uint64_t height = k - 1;
blobdata bd;
bd.assign(reinterpret_cast<char*>(v.get_data()), v.get_size());
block b;
if (!parse_and_validate_block_from_blob(bd, b))
throw0(DB_ERROR("Failed to parse block from blob retrieved from the db"));
crypto::hash hash;
if (!get_block_hash(b, hash))
throw0(DB_ERROR("Failed to get block hash from blob retrieved from the db"));
if (!f(height, hash, b))
{
ret = false;
break;
}
}
if (result != DB_NOTFOUND)
ret = false;
cur.close();
return ret;
}
bool BlockchainBDB::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f, bool pruned) const
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
bdb_cur cur(DB_DEFAULT_TX, m_txs);
Dbt_copy<crypto::hash> k;
Dbt_safe v;
bool ret = true;
int result;
while ((result = cur->get(&k, &v, DB_NEXT)) == 0)
{
blobdata bd;
bd.assign(reinterpret_cast<char*>(v.get_data()), v.get_size());
transaction tx;
if (!parse_and_validate_tx_from_blob(bd, tx))
throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
if (!f(k, tx))
{
ret = false;
break;
}
}
if (result != DB_NOTFOUND)
ret = false;
cur.close();
return ret;
}
bool BlockchainBDB::for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, size_t tx_idx)> f) const
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
bdb_cur cur(DB_DEFAULT_TX, m_output_amounts);
Dbt_copy<uint64_t> k;
Dbt_copy<uint32_t> v;
bool ret = true;
int result;
while ((result = cur->get(&k, &v, DB_NEXT)) == 0)
{
uint32_t global_index = v - 1;
tx_out_index toi = get_output_tx_and_index_from_global(global_index);
if (!f(k, toi.first, toi.second))
{
ret = false;
break;
}
}
if (result != DB_NOTFOUND)
ret = false;
cur.close();
return ret;
}
uint64_t BlockchainBDB::get_output_global_index(const uint64_t& amount, const uint64_t& index)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
check_open();
std::vector < uint64_t > offsets;
std::vector < uint64_t > global_indices;
offsets.push_back(index);
get_output_global_indices(amount, offsets, global_indices);
if (!global_indices.size())
throw1(OUTPUT_DNE("Attempting to get an output index by amount and amount index, but amount not found"));
return global_indices[0];
}
void BlockchainBDB::check_open() const
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
if (!m_open)
throw0(DB_ERROR("DB operation attempted on a not-open DB instance"));
}
BlockchainBDB::~BlockchainBDB()
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
if (m_open)
{
close();
}
}
BlockchainBDB::BlockchainBDB(bool batch_transactions) :
BlockchainDB(),
m_buffer(DB_BUFFER_COUNT, DB_BUFFER_LENGTH)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
// initialize folder to something "safe" just in case
// someone accidentally misuses this class...
m_folder = "thishsouldnotexistbecauseitisgibberish";
m_run_checkpoint = 0;
m_batch_transactions = batch_transactions;
m_write_txn = nullptr;
m_height = 0;
m_hardfork = nullptr;
}
void BlockchainBDB::open(const std::string& filename, const int db_flags)
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
if (m_open)
throw0(DB_OPEN_FAILURE("Attempted to open db, but it's already open"));
boost::filesystem::path direc(filename);
if (boost::filesystem::exists(direc))
{
if (!boost::filesystem::is_directory(direc))
throw0(DB_OPEN_FAILURE("DB needs a directory path, but a file was passed"));
}
else
{
if (!boost::filesystem::create_directories(direc))
throw0(DB_OPEN_FAILURE(std::string("Failed to create directory ").append(filename).c_str()));
}
m_folder = filename;
try
{
//Create BerkeleyDB environment
m_env = new DbEnv(0); // no flags needed for DbEnv
uint32_t db_env_open_flags = DB_CREATE | DB_INIT_MPOOL | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_TXN | DB_RECOVER | DB_THREAD;
// Set some default values for these parameters.
// They can be overridden using the DB_CONFIG file.
m_env->set_cachesize(0, DB_DEF_CACHESIZE, 1);
m_env->set_lk_max_locks(DB_MAX_LOCKS);
m_env->set_lk_max_lockers(DB_MAX_LOCKS);
m_env->set_lk_max_objects(DB_MAX_LOCKS);
#ifndef __OpenBSD__ //OpenBSD's DB package is too old to support this feature
if(m_auto_remove_logs)
m_env->log_set_config(DB_LOG_AUTO_REMOVE, 1);
#endif
// last parameter left 0, files will be created with default rw access
m_env->open(filename.c_str(), db_env_open_flags, 0);
m_env->set_flags(db_flags, 1);
// begin transaction to init dbs
bdb_txn_safe txn;
m_env->txn_begin(NULL, txn, 0);
// create Dbs in the environment
m_blocks = new Db(m_env, 0);
m_block_heights = new Db(m_env, 0);
m_block_hashes = new Db(m_env, 0);
m_block_timestamps = new Db(m_env, 0);
m_block_sizes = new Db(m_env, 0);
m_block_diffs = new Db(m_env, 0);
m_block_coins = new Db(m_env, 0);
m_txs = new Db(m_env, 0);
m_tx_unlocks = new Db(m_env, 0);
m_tx_heights = new Db(m_env, 0);
m_tx_outputs = new Db(m_env, 0);
m_output_txs = new Db(m_env, 0);
m_output_indices = new Db(m_env, 0);
m_output_amounts = new Db(m_env, 0);
m_output_keys = new Db(m_env, 0);
m_spent_keys = new Db(m_env, 0);
m_hf_starting_heights = new Db(m_env, 0);
m_hf_versions = new Db(m_env, 0);
m_properties = new Db(m_env, 0);
// Tell DB about Dbs that need duplicate support
// Note: no need to tell about sorting,
// as the default is insertion order, which we want
m_tx_outputs->set_flags(DB_DUP);
m_output_amounts->set_flags(DB_DUP);
// Tell DB about fixed-size values.
m_block_hashes->set_re_len(sizeof(crypto::hash));
m_block_timestamps->set_re_len(sizeof(uint64_t));
m_block_sizes->set_re_len(sizeof(size_t)); // should really store block size as uint64_t...
m_block_diffs->set_re_len(sizeof(difficulty_type));
m_block_coins->set_re_len(sizeof(uint64_t));
m_output_txs->set_re_len(sizeof(crypto::hash));
m_output_indices->set_re_len(sizeof(uint64_t));
m_output_keys->set_re_len(sizeof(output_data_t));
m_hf_starting_heights->set_re_len(sizeof(uint64_t));
m_hf_versions->set_re_len(sizeof(uint8_t));
//TODO: Find out if we need to do Db::set_flags(DB_RENUMBER)
// for the RECNO databases. We shouldn't as we're only
// inserting/removing from the end, but we'll see.
// open Dbs in the environment
// m_tx_outputs and m_output_amounts must be DB_HASH or DB_BTREE
// because they need duplicate entry support. The rest are DB_RECNO,
// as it seems that will be the most performant choice.
m_blocks->open(txn, BDB_BLOCKS, NULL, DB_RECNO, DB_CREATE, 0);
m_block_timestamps->open(txn, BDB_BLOCK_TIMESTAMPS, NULL, DB_RECNO, DB_CREATE, 0);
m_block_heights->open(txn, BDB_BLOCK_HEIGHTS, NULL, DB_HASH, DB_CREATE, 0);
m_block_hashes->open(txn, BDB_BLOCK_HASHES, NULL, DB_RECNO, DB_CREATE, 0);
m_block_sizes->open(txn, BDB_BLOCK_SIZES, NULL, DB_RECNO, DB_CREATE, 0);
m_block_diffs->open(txn, BDB_BLOCK_DIFFS, NULL, DB_RECNO, DB_CREATE, 0);
m_block_coins->open(txn, BDB_BLOCK_COINS, NULL, DB_RECNO, DB_CREATE, 0);
m_txs->open(txn, BDB_TXS, NULL, DB_HASH, DB_CREATE, 0);
m_tx_unlocks->open(txn, BDB_TX_UNLOCKS, NULL, DB_HASH, DB_CREATE, 0);
m_tx_heights->open(txn, BDB_TX_HEIGHTS, NULL, DB_HASH, DB_CREATE, 0);
m_tx_outputs->open(txn, BDB_TX_OUTPUTS, NULL, DB_HASH, DB_CREATE, 0);
m_output_txs->open(txn, BDB_OUTPUT_TXS, NULL, DB_RECNO, DB_CREATE, 0);
m_output_indices->open(txn, BDB_OUTPUT_INDICES, NULL, DB_RECNO, DB_CREATE, 0);
m_output_amounts->open(txn, BDB_OUTPUT_AMOUNTS, NULL, DB_HASH, DB_CREATE, 0);
m_output_keys->open(txn, BDB_OUTPUT_KEYS, NULL, DB_RECNO, DB_CREATE, 0);
m_spent_keys->open(txn, BDB_SPENT_KEYS, NULL, DB_HASH, DB_CREATE, 0);
m_hf_starting_heights->open(txn, BDB_HF_STARTING_HEIGHTS, NULL, DB_RECNO, DB_CREATE, 0);
m_hf_versions->open(txn, BDB_HF_VERSIONS, NULL, DB_RECNO, DB_CREATE, 0);
m_properties->open(txn, BDB_PROPERTIES, NULL, DB_HASH, DB_CREATE, 0);
txn.commit();
DB_BTREE_STAT* stats;
// DB_FAST_STAT can apparently cause an incorrect number of records
// to be returned. The flag should be set to 0 instead if this proves
// to be the case.
// ND: The bug above can occur when a block is popped and the application
// exits without pushing a new block to the db. Set txn to NULL and DB_FAST_STAT
// to zero (0) for reliability.
m_blocks->stat(NULL, &stats, 0);
m_height = stats->bt_nkeys;
free(stats);
// see above comment about DB_FAST_STAT
m_output_indices->stat(NULL, &stats, 0);
m_num_outputs = stats->bt_nkeys;
free(stats);
// checks for compatibility
bool compatible = true;
Dbt_copy<const char*> key("version");
Dbt_copy<uint32_t> result;
auto get_result = m_properties->get(DB_DEFAULT_TX, &key, &result, 0);
if (get_result == 0)
{
if (result > VERSION)
{
LOG_PRINT_RED_L0("Existing BerkeleyDB database was made by a later version. We don't know how it will change yet.");
compatible = false;
}
#if VERSION > 0
else if (result < VERSION)
{
compatible = false;
}
#endif
}
else
{
// if not found, but we're on version 0, it's fine. If the DB's empty, it's fine too.
if (VERSION > 0 && m_height > 0)
compatible = false;
}
if (!compatible)
{
m_open = false;
LOG_PRINT_RED_L0("Existing BerkeleyDB database is incompatible with this version.");
LOG_PRINT_RED_L0("Please delete the existing database and resync.");
return;
}
if (1 /* this can't be set readonly atm */)
{
// only write version on an empty DB
if (m_height == 0)
{
Dbt_copy<const char*> k("version");
Dbt_copy<uint32_t> v(VERSION);
auto put_result = m_properties->put(DB_DEFAULT_TX, &k, &v, 0);
if (put_result != 0)
{
m_open = false;
LOG_PRINT_RED_L0("Failed to write version to database.");
return;
}
}
}
// run checkpoint thread
m_run_checkpoint = true;
m_checkpoint_thread.reset(new boost::thread(&BlockchainBDB::checkpoint_worker, this));
}
catch (const std::exception& e)
{
throw0(DB_OPEN_FAILURE(e.what()));
}
m_open = true;
}
void BlockchainBDB::close()
{
LOG_PRINT_L3("BlockchainBDB::" << __func__);
this->sync();
m_run_checkpoint = false;
m_checkpoint_thread->join();
m_checkpoint_thread.reset();
// FIXME: not yet thread safe!!! Use with care.
m_open = false;
// DB_FORCESYNC is only available on newer version of libdb.
// The libdb doc says using the DB_FORCESYNC flag to DB_ENV->close
// is "similar to calling the DB->close(0) method to close each
// database handle". So this is what we do here as a fallback.
#ifdef DB_FORCESYNC
m_env->close(DB_FORCESYNC);
#else
m_blocks->close(0);
m_block_heights->close(0);
m_block_hashes->close(0);
m_block_timestamps->close(0);