forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlmdb_wrapper.cpp
More file actions
3733 lines (3110 loc) · 111 KB
/
lmdb_wrapper.cpp
File metadata and controls
3733 lines (3110 loc) · 111 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) 2011-2015, Armory Technologies, Inc. //
// Distributed under the GNU Affero General Public License (AGPL v3) //
// See LICENSE or http://www.gnu.org/licenses/agpl.html //
// //
////////////////////////////////////////////////////////////////////////////////
//
#include <iostream>
#include <sstream>
#include <map>
#include <list>
#include <vector>
#include <set>
#include "BinaryData.h"
#include "BtcUtils.h"
#include "BlockObj.h"
#include "StoredBlockObj.h"
#include "lmdb_wrapper.h"
#include "txio.h"
struct MDB_val;
////////////////////////////////////////////////////////////////////////////////
LDBIter::LDBIter(LMDB::Iterator&& mv)
: iter_(std::move(mv))
{
isDirty_ = true;
}
////////////////////////////////////////////////////////////////////////////////
LDBIter::LDBIter(LDBIter&& mv)
: iter_(std::move(mv.iter_))
{
isDirty_ = true;
}
LDBIter::LDBIter(const LDBIter& cp)
: iter_(cp.iter_)
{
isDirty_ = true;
}
////////////////////////////////////////////////////////////////////////////////
LDBIter& LDBIter::operator=(LMDB::Iterator&& mv)
{
iter_ = std::move(mv);
return *this;
}
////////////////////////////////////////////////////////////////////////////////
LDBIter& LDBIter::operator=(LDBIter&& mv)
{
iter_ = std::move(mv.iter_);
return *this;
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::isValid(DB_PREFIX dbpref)
{
if(!isValid() || iter_.key().size() == 0)
return false;
return iter_.key()[0] == (char)dbpref;
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::advance(void)
{
++iter_;
isDirty_ = true;
return isValid();
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::retreat(void)
{
--iter_;
isDirty_ = true;
return isValid();
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::advance(DB_PREFIX prefix)
{
++iter_;
isDirty_ = true;
return isValid(prefix);
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::readIterData(void)
{
if(!isValid())
{
isDirty_ = true;
return false;
}
currKey_ = BinaryData(iter_.key());
currValue_ = BinaryData(iter_.value());
currKeyReader_.setNewData( currKey_ );
currValueReader_.setNewData( currValue_ );
isDirty_ = false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::advanceAndRead(void)
{
if(!advance())
return false;
return readIterData();
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::advanceAndRead(DB_PREFIX prefix)
{
if(!advance(prefix))
return false;
return readIterData();
}
////////////////////////////////////////////////////////////////////////////////
BinaryData LDBIter::getKey(void) const
{
if(isDirty_)
{
LOGERR << "Returning dirty key ref";
return BinaryData(0);
}
return currKey_;
}
////////////////////////////////////////////////////////////////////////////////
BinaryData LDBIter::getValue(void) const
{
if(isDirty_)
{
LOGERR << "Returning dirty value ref";
return BinaryData(0);
}
return currValue_;
}
////////////////////////////////////////////////////////////////////////////////
BinaryDataRef LDBIter::getKeyRef(void) const
{
if(isDirty_)
{
LOGERR << "Returning dirty key ref";
return BinaryDataRef();
}
return currKeyReader_.getRawRef();
}
////////////////////////////////////////////////////////////////////////////////
BinaryDataRef LDBIter::getValueRef(void) const
{
if(isDirty_)
{
LOGERR << "Returning dirty value ref";
return BinaryDataRef();
}
return currValueReader_.getRawRef();
}
////////////////////////////////////////////////////////////////////////////////
BinaryRefReader& LDBIter::getKeyReader(void) const
{
if(isDirty_)
LOGERR << "Returning dirty key reader";
return currKeyReader_;
}
////////////////////////////////////////////////////////////////////////////////
BinaryRefReader& LDBIter::getValueReader(void) const
{
if(isDirty_)
LOGERR << "Returning dirty value reader";
return currValueReader_;
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekTo(BinaryDataRef key)
{
iter_.seek(CharacterArrayRef(key.getSize(), key.getPtr()), LMDB::Iterator::Seek_GE);
return readIterData();
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekTo(DB_PREFIX pref, BinaryDataRef key)
{
BinaryWriter bw(key.getSize() + 1);
bw.put_uint8_t((uint8_t)pref);
bw.put_BinaryData(key);
return seekTo(bw.getDataRef());
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekToExact(BinaryDataRef key)
{
if(!seekTo(key))
return false;
return checkKeyExact(key);
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekToExact(DB_PREFIX pref, BinaryDataRef key)
{
if(!seekTo(pref, key))
return false;
return checkKeyExact(pref, key);
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekToStartsWith(BinaryDataRef key)
{
if(!seekTo(key))
return false;
return checkKeyStartsWith(key);
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekToStartsWith(DB_PREFIX prefix)
{
BinaryWriter bw(1);
bw.put_uint8_t((uint8_t)prefix);
if(!seekTo(bw.getDataRef()))
return false;
return checkKeyStartsWith(bw.getDataRef());
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekToStartsWith(DB_PREFIX pref, BinaryDataRef key)
{
if(!seekTo(pref, key))
return false;
return checkKeyStartsWith(pref, key);
}
bool LDBIter::seekToBefore(BinaryDataRef key)
{
iter_.seek(CharacterArrayRef(key.getSize(), key.getPtr()), LMDB::Iterator::Seek_LE);
return readIterData();
}
bool LDBIter::seekToBefore(DB_PREFIX prefix)
{
BinaryWriter bw(1);
bw.put_uint8_t((uint8_t)prefix);
return seekToBefore(bw.getDataRef());
}
bool LDBIter::seekToBefore(DB_PREFIX pref, BinaryDataRef key)
{
BinaryWriter bw(key.getSize() + 1);
bw.put_uint8_t((uint8_t)pref);
bw.put_BinaryData(key);
return seekToBefore(bw.getDataRef());
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::seekToFirst(void)
{
iter_.toFirst();
readIterData();
return true;
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::checkKeyExact(BinaryDataRef key)
{
if(isDirty_ && !readIterData())
return false;
return (key==currKeyReader_.getRawRef());
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::checkKeyExact(DB_PREFIX prefix, BinaryDataRef key)
{
BinaryWriter bw(key.getSize() + 1);
bw.put_uint8_t((uint8_t)prefix);
bw.put_BinaryData(key);
if(isDirty_ && !readIterData())
return false;
return (bw.getDataRef()==currKeyReader_.getRawRef());
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::checkKeyStartsWith(BinaryDataRef key)
{
if(isDirty_ && !readIterData())
return false;
return (currKeyReader_.getRawRef().startsWith(key));
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::verifyPrefix(DB_PREFIX prefix, bool advanceReader)
{
if(isDirty_ && !readIterData())
return false;
if(currKeyReader_.getSizeRemaining() < 1)
return false;
if(advanceReader)
return (currKeyReader_.get_uint8_t() == (uint8_t)prefix);
else
return (currKeyReader_.getRawRef()[0] == (uint8_t)prefix);
}
////////////////////////////////////////////////////////////////////////////////
bool LDBIter::checkKeyStartsWith(DB_PREFIX prefix, BinaryDataRef key)
{
BinaryWriter bw(key.getSize() + 1);
bw.put_uint8_t((uint8_t)prefix);
bw.put_BinaryData(key);
return checkKeyStartsWith(bw.getDataRef());
}
////////////////////////////////////////////////////////////////////////////////
LMDBBlockDatabase::LMDBBlockDatabase(function<bool(void)> isDBReady) :
isDBReady_(isDBReady)
{
//for some reason the WRITE_UINT16 macros create 4 byte long BinaryData
//instead of 2, so I'm doing this the hard way instead
uint8_t* ptr = const_cast<uint8_t*>(ZCprefix_.getPtr());
memset(ptr, 0xFF, 2);
}
/////////////////////////////////////////////////////////////////////////////
LMDBBlockDatabase::~LMDBBlockDatabase(void)
{
closeDatabases();
}
/////////////////////////////////////////////////////////////////////////////
// The dbType and pruneType inputs are left blank if you are just going to
// take whatever is the current state of database. You can choose to
// manually specify them, if you want to throw an error if it's not what you
// were expecting
void LMDBBlockDatabase::openDatabases(
const string& basedir,
BinaryData const & genesisBlkHash,
BinaryData const & genesisTxHash,
BinaryData const & magic,
ARMORY_DB_TYPE dbtype,
DB_PRUNE_TYPE pruneType
)
{
baseDir_ = basedir;
if (dbtype == ARMORY_DB_SUPER)
{
//make sure it is a supernode DB
#ifdef WIN32
if (access(dbHeadersFilename().c_str(), 0) == 0)
#else
if (access(dbHeadersFilename().c_str(), F_OK) == 0)
#endif
{
LOGERR << "Mismatch in DB type";
LOGERR << "Requested supernode";
LOGERR << "Current DB is fullnode";
throw runtime_error("Mismatch in DB type");
}
try
{
openDatabasesSupernode(basedir,
genesisBlkHash, genesisTxHash,
magic, dbtype, pruneType);
}
catch (LMDBException &e)
{
LOGERR << "Exception thrown while opening database";
LOGERR << e.what();
throw e;
}
catch (runtime_error &e)
{
throw e;
}
catch (...)
{
LOGERR << "Exception thrown while opening database";
closeDatabases();
throw;
}
return;
}
/***
Supernode and Fullnode use different DB.
Supernode keeps all data within the same file.
Fullnode is meant for lighter duty and keep its static data (blocks and
headers) separate from dynamic data (history, utxo spentness, ssh, ZC).
TxHints are also separeated in their dedicated DB. Each block is saved as
a single binary string as opposed to Supernode which breaks block data down
into Tx and TxOut.
Consequently, in Fullnode, blocks need to be processed after they're pulled
from DB, so individual Tx and TxOut cannot be pulled separately from entire
blocks, as opposed to supernode.
This allows Fullnode to keep its static data sequential, with very little
fragmentation, while random block data access is slower. This in turns speeds
up DB building and scanning, which suits individual use profile with
100~100,000 registered addresses.
Supernode on the other hand tracks all addresses so it will have a tons of
fragmentation to begin with, and is meant to handle lots of concurent
random access, which is LMDB's strong suit with lots of RAM and high
permanent storage bandwidth (i.e. servers).
In Supernode, TxOut entries are in the BLKDATA DB.
In Fullnode, they are in the HISTORY DB, only for TxOuts relevant to the
tracked set of addresses. Fullnode also carries the amount of txouts per
relevant Tx + txHash saved as :
TxDBKey6 | uint32_t | txHash
This prevents pulling each Tx from full blocks in order to identity STS
transactions and getting the hash, keeping ledger computation speed on
par with Supernode
In Supernode, BLKDATA sdbi sits in the BLKDATA DB.
In Fullnode, BLDDATA sdbi goes in the HISTORY DB instead, while BLKDATA DB
has no sdbi
In Supernode, txHints go in the BLKDATA DB.
In Fullnode, only hints for relevant transactions are saved, in the
dedicated TXHINTS DB. So while Supernode compiles and commits txhints
in the building phase, Fullnode processes the few relevant ones during
scans.
There are a couple reasons to this: while Supernode may be used to track
all ZC (which requires hints for all transactions), Fullnode will only ever
need txhints for those transactions relevant to its set of tracked addresses
Besides the obvious space gain (~7% smaller), txhints aren't sequential by
nature, and as this DB grows it will slow down DB building. The processing
cost over doubles the build time from scratch. Even then the hints will be
mostly remain in RAM through OS mapped file management, so writes won't
impact buidling much.
However, a cold start with new blocks to commit will grind HDDs to a halt,
taking around 10 minutes to catch up on 12h worth of new blocks. So keeping
track of all txhints in Fullnode is not only unecessary, it is detrimental
to overall DB speed.
***/
SCOPED_TIMER("openDatabases");
LOGINFO << "Opening databases...";
magicBytes_ = magic;
genesisTxHash_ = genesisTxHash;
genesisBlkHash_ = genesisBlkHash;
armoryDbType_ = dbtype;
dbPruneType_ = pruneType;
if (genesisBlkHash_.getSize() == 0 || magicBytes_.getSize() == 0)
{
LOGERR << " must set magic bytes and genesis block";
LOGERR << " before opening databases.";
throw runtime_error("magic bytes not set");
}
// Just in case this isn't the first time we tried to open it.
closeDatabases();
for (int i = 0; i < COUNT; i++)
dbEnv_[DB_SELECT(i)].reset(new LMDBEnv());
dbEnv_[BLKDATA]->open(dbBlkdataFilename());
//make sure it's a fullnode DB
{
LMDB checkDBType;
const char* dataPtr = nullptr;
{
LMDBEnv::Transaction tx(dbEnv_[BLKDATA].get(), LMDB::ReadWrite);
checkDBType.open(dbEnv_[BLKDATA].get(), "blkdata");
auto dbKey = StoredDBInfo::getDBKey();
CharacterArrayRef data = checkDBType.get_NoCopy(CharacterArrayRef(
dbKey.getSize(), (char*)dbKey.getPtr()));
dataPtr = data.data;
}
checkDBType.close();
if (dataPtr != nullptr)
{
LOGERR << "Mismatch in DB type";
LOGERR << "Requested fullnode";
LOGERR << "Current DB is supernode";
throw runtime_error("Mismatch in DB type");
}
}
dbEnv_[HEADERS]->open(dbHeadersFilename());
dbEnv_[HISTORY]->open(dbHistoryFilename());
dbEnv_[TXHINTS]->open(dbTxhintsFilename());
map<DB_SELECT, string> DB_NAMES;
DB_NAMES[HEADERS] = "headers";
DB_NAMES[HISTORY] = "history";
DB_NAMES[BLKDATA] = "blocks";
DB_NAMES[TXHINTS] = "txhints";
try
{
for (auto& db : DB_NAMES)
{
DB_SELECT CURRDB = db.first;
LMDBEnv::Transaction tx(dbEnv_[CURRDB].get(), LMDB::ReadWrite);
dbs_[CURRDB].open(dbEnv_[CURRDB].get(), db.second);
//no SDBI in TXHINTS
if (CURRDB == TXHINTS)
continue;
StoredDBInfo sdbi;
getStoredDBInfo(CURRDB, sdbi, false);
if (!sdbi.isInitialized())
{
// If DB didn't exist yet (dbinfo key is empty), seed it
// A new database has the maximum flag settings
// Flags can only be reduced. Increasing requires redownloading
StoredDBInfo sdbi;
sdbi.magic_ = magicBytes_;
sdbi.topBlkHgt_ = 0;
sdbi.topBlkHash_ = genesisBlkHash_;
sdbi.armoryType_ = armoryDbType_;
sdbi.pruneType_ = dbPruneType_;
putStoredDBInfo(CURRDB, sdbi);
}
else
{
// Check that the magic bytes are correct
if (magicBytes_ != sdbi.magic_)
{
throw runtime_error("Magic bytes mismatch! Different blkchain?");
}
else if (armoryDbType_ != sdbi.armoryType_)
{
LOGERR << "Mismatch in DB type";
LOGERR << "DB is in mode: " << (uint32_t)armoryDbType_;
LOGERR << "Expecting mode: " << sdbi.armoryType_;
throw runtime_error("Mismatch in DB type");
}
if (dbPruneType_ != sdbi.pruneType_)
{
throw runtime_error("Mismatch in DB type");
}
}
}
}
catch (LMDBException &e)
{
LOGERR << "Exception thrown while opening database";
LOGERR << e.what();
throw e;
}
catch (runtime_error &e)
{
LOGERR << "Exception thrown while opening database";
LOGERR << e.what();
throw e;
}
catch (...)
{
LOGERR << "Exception thrown while opening database";
closeDatabases();
throw;
}
dbIsOpen_ = true;
}
void LMDBBlockDatabase::openDatabasesSupernode(
const string& basedir,
BinaryData const & genesisBlkHash,
BinaryData const & genesisTxHash,
BinaryData const & magic,
ARMORY_DB_TYPE dbtype,
DB_PRUNE_TYPE pruneType
)
{
SCOPED_TIMER("openDatabases");
LOGINFO << "Opening databases...";
baseDir_ = basedir;
magicBytes_ = magic;
genesisTxHash_ = genesisTxHash;
genesisBlkHash_ = genesisBlkHash;
armoryDbType_ = dbtype;
dbPruneType_ = pruneType;
if(genesisBlkHash_.getSize() == 0 || magicBytes_.getSize() == 0)
{
LOGERR << " must set magic bytes and genesis block";
LOGERR << " before opening databases.";
throw runtime_error("magic bytes not set");
}
// Just in case this isn't the first time we tried to open it.
closeDatabasesSupernode();
dbEnv_[BLKDATA].reset(new LMDBEnv());
dbEnv_[BLKDATA]->open(dbBlkdataFilename());
map<DB_SELECT, string> DB_NAMES;
DB_NAMES[HEADERS] = "headers";
DB_NAMES[BLKDATA] = "blkdata";
try
{
for(auto& db : DB_NAMES)
{
DB_SELECT CURRDB = db.first;
LMDBEnv::Transaction tx(dbEnv_[BLKDATA].get(), LMDB::ReadWrite);
dbs_[CURRDB].open(dbEnv_[BLKDATA].get(), db.second);
StoredDBInfo sdbi;
getStoredDBInfo(CURRDB, sdbi, false);
if(!sdbi.isInitialized())
{
// If DB didn't exist yet (dbinfo key is empty), seed it
// A new database has the maximum flag settings
// Flags can only be reduced. Increasing requires redownloading
StoredDBInfo sdbi;
sdbi.magic_ = magicBytes_;
sdbi.topBlkHgt_ = 0;
sdbi.topBlkHash_ = genesisBlkHash_;
sdbi.armoryType_ = armoryDbType_;
sdbi.pruneType_ = dbPruneType_;
putStoredDBInfo(CURRDB, sdbi);
}
else
{
// Check that the magic bytes are correct
if(magicBytes_ != sdbi.magic_)
{
throw runtime_error("Magic bytes mismatch! Different blkchain?");
}
else if(armoryDbType_ != sdbi.armoryType_)
{
LOGERR << "Mismatch in DB type";
LOGERR << "DB is in mode: " << (uint32_t)armoryDbType_;
LOGERR << "Expecting mode: " << sdbi.armoryType_;
throw runtime_error("Mismatch in DB type");
}
if(dbPruneType_ != sdbi.pruneType_)
{
throw runtime_error("Mismatch in DB type");
}
}
}
}
catch (LMDBException &e)
{
LOGERR << "Exception thrown while opening database";
LOGERR << e.what();
throw e;
}
catch (runtime_error &e)
{
LOGERR << "Exception thrown while opening database";
LOGERR << e.what();
throw e;
}
catch(...)
{
LOGERR << "Exception thrown while opening database";
closeDatabases();
throw;
}
dbIsOpen_ = true;
}
/////////////////////////////////////////////////////////////////////////////
void LMDBBlockDatabase::nukeHeadersDB(void)
{
SCOPED_TIMER("nukeHeadersDB");
LOGINFO << "Destroying headers DB, to be rebuilt.";
LMDBEnv::Transaction tx;
beginDBTransaction(&tx, HEADERS, LMDB::ReadWrite);
LMDB::Iterator begin = dbs_[HEADERS].begin();
LMDB::Iterator end = dbs_[HEADERS].end();
while(begin != end)
{
LMDB::Iterator here = begin;
++begin;
dbs_[HEADERS].erase(here.key());
}
StoredDBInfo sdbi;
sdbi.magic_ = magicBytes_;
sdbi.topBlkHgt_ = 0;
sdbi.topBlkHash_ = genesisBlkHash_;
sdbi.armoryType_ = armoryDbType_;
sdbi.pruneType_ = dbPruneType_;
putStoredDBInfo(HEADERS, sdbi);
}
/////////////////////////////////////////////////////////////////////////////
// DBs don't really need to be closed. Just delete them
void LMDBBlockDatabase::closeDatabases(void)
{
if (armoryDbType_ == ARMORY_DB_SUPER)
{
closeDatabasesSupernode();
return;
}
for(uint32_t db=0; db<COUNT; db++)
{
dbs_[(DB_SELECT)db].close();
if (dbEnv_[(DB_SELECT)db] != nullptr)
dbEnv_[(DB_SELECT)db]->close();
}
dbIsOpen_ = false;
}
/////////////////////////////////////////////////////////////////////////////
// DBs don't really need to be closed. Just delete them
void LMDBBlockDatabase::closeDatabasesSupernode(void)
{
dbs_[BLKDATA].close();
dbs_[HEADERS].close();
if (dbEnv_[BLKDATA] != nullptr)
dbEnv_[BLKDATA]->close();
dbIsOpen_ = false;
}
////////////////////////////////////////////////////////////////////////////////
void LMDBBlockDatabase::destroyAndResetDatabases(void)
{
SCOPED_TIMER("destroyAndResetDatabase");
// We want to make sure the database is restarted with the same parameters
// it was called with originally
if (armoryDbType_ == ARMORY_DB_SUPER)
{
closeDatabasesSupernode();
remove(dbBlkdataFilename().c_str());
}
else
{
closeDatabases();
remove(dbHeadersFilename().c_str());
remove(dbHistoryFilename().c_str());
remove(dbBlkdataFilename().c_str());
remove(dbTxhintsFilename().c_str());
}
// Reopen the databases with the exact same parameters as before
// The close & destroy operations shouldn't have changed any of that.
openDatabases(baseDir_, genesisBlkHash_, genesisTxHash_,
magicBytes_, armoryDbType_, dbPruneType_);
}
////////////////////////////////////////////////////////////////////////////////
BinaryData LMDBBlockDatabase::getTopBlockHash(DB_SELECT db)
{
if (armoryDbType_ != ARMORY_DB_SUPER && db == BLKDATA)
throw runtime_error("No SDBI in BLKDATA in Fullnode");
LMDBEnv::Transaction tx;
beginDBTransaction(&tx, db, LMDB::ReadOnly);
StoredDBInfo sdbi;
getStoredDBInfo(db, sdbi);
return sdbi.topBlkHash_;
}
////////////////////////////////////////////////////////////////////////////////
uint32_t LMDBBlockDatabase::getTopBlockHeight(DB_SELECT db)
{
StoredDBInfo sdbi;
getStoredDBInfo(db, sdbi);
return sdbi.topBlkHgt_;
}
/////////////////////////////////////////////////////////////////////////////
// Get value using pre-created slice
BinaryData LMDBBlockDatabase::getValue(DB_SELECT db, BinaryDataRef key) const
{
return dbs_[db].value( CharacterArrayRef(
key.getSize(), (char*)key.getPtr() ) );
}
/////////////////////////////////////////////////////////////////////////////
// Get value without resorting to a DB iterator
BinaryDataRef LMDBBlockDatabase::getValueNoCopy(DB_SELECT db,
BinaryDataRef key) const
{
CharacterArrayRef data = dbs_[db].get_NoCopy(CharacterArrayRef(
key.getSize(), (char*)key.getPtr()));
if (data.data)
return BinaryDataRef((uint8_t*)data.data, data.len);
else
return BinaryDataRef();
}
/////////////////////////////////////////////////////////////////////////////
// Get value using BinaryData object. If you have a string, you can use
// BinaryData key(string(theStr));
BinaryData LMDBBlockDatabase::getValue(DB_SELECT db,
DB_PREFIX prefix,
BinaryDataRef key) const
{
BinaryData keyFull(key.getSize()+1);
keyFull[0] = (uint8_t)prefix;
key.copyTo(keyFull.getPtr()+1, key.getSize());
try
{
return getValue(db, keyFull.getRef());
}
catch (...)
{
return BinaryData(0);
}
}
/////////////////////////////////////////////////////////////////////////////
// Get value using BinaryDataRef object. The data from the get* call is
// actually copied to a member variable, and thus the refs are valid only
// until the next get* call.
BinaryDataRef LMDBBlockDatabase::getValueRef(DB_SELECT db, BinaryDataRef key) const
{
return getValueNoCopy(db, key);
}
/////////////////////////////////////////////////////////////////////////////
// Get value using BinaryDataRef object. The data from the get* call is
// actually copied to a member variable, and thus the refs are valid only
// until the next get* call.
BinaryDataRef LMDBBlockDatabase::getValueRef(DB_SELECT db,
DB_PREFIX prefix,
BinaryDataRef key) const
{
BinaryWriter bw(key.getSize() + 1);
bw.put_uint8_t((uint8_t)prefix);
bw.put_BinaryData(key);
return getValueRef(db, bw.getDataRef());
}
/////////////////////////////////////////////////////////////////////////////
// Same as the getValueRef, in that they are only valid until the next get*
// call. These are convenience methods which basically just save us
BinaryRefReader LMDBBlockDatabase::getValueReader(
DB_SELECT db,
BinaryDataRef keyWithPrefix) const
{
return BinaryRefReader(getValueRef(db, keyWithPrefix));
}
/////////////////////////////////////////////////////////////////////////////
// Same as the getValueRef, in that they are only valid until the next get*
// call. These are convenience methods which basically just save us
BinaryRefReader LMDBBlockDatabase::getValueReader(
DB_SELECT db,
DB_PREFIX prefix,
BinaryDataRef key) const
{
return BinaryRefReader(getValueRef(db, prefix, key));
}
/////////////////////////////////////////////////////////////////////////////
// Header Key: returns header hash
// Tx Key: returns tx hash
// TxOut Key: returns serialized OutPoint
BinaryData LMDBBlockDatabase::getHashForDBKey(BinaryData dbkey)
{
uint32_t hgt;
uint8_t dup;
uint16_t txi;
uint16_t txo;
size_t sz = dbkey.getSize();
if(sz < 4 || sz > 9)
{
LOGERR << "Invalid DBKey size: " << sz << ", " << dbkey.toHexStr();
return BinaryData(0);
}
BinaryRefReader brr(dbkey);
if(dbkey.getSize() % 2 == 0)
DBUtils::readBlkDataKeyNoPrefix(brr, hgt, dup, txi, txo);
else
DBUtils::readBlkDataKey(brr, hgt, dup, txi, txo);
return getHashForDBKey(hgt, dup, txi, txo);
}
/////////////////////////////////////////////////////////////////////////////
// Header Key: returns header hash
// Tx Key: returns tx hash
// TxOut Key: returns serialized OutPoint
BinaryData LMDBBlockDatabase::getHashForDBKey(uint32_t hgt,
uint8_t dup,
uint16_t txi,
uint16_t txo)
{
if(txi==UINT16_MAX)
{
StoredHeader sbh;
getBareHeader(sbh, hgt, dup);
return sbh.thisHash_;
}
else if(txo==UINT16_MAX)
{
StoredTx stx;
getStoredTx(stx, hgt, dup, txi, false);
return stx.thisHash_;
}
else
{
StoredTx stx;
getStoredTx(stx, hgt, dup, txi, false);
OutPoint op(stx.thisHash_, txo);
return op.serialize();
}
}
/////////////////////////////////////////////////////////////////////////////
// Put value based on BinaryData key. If batch writing, pass in the batch
void LMDBBlockDatabase::putValue(DB_SELECT db,
BinaryDataRef key,
BinaryDataRef value)
{
dbs_[db].insert(
CharacterArrayRef(key.getSize(), key.getPtr()),
CharacterArrayRef(value.getSize(), value.getPtr())
);
}
/////////////////////////////////////////////////////////////////////////////
void LMDBBlockDatabase::putValue(DB_SELECT db,
BinaryData const & key,
BinaryData const & value)
{
putValue(db, key.getRef(), value.getRef());
}
/////////////////////////////////////////////////////////////////////////////
// Put value based on BinaryData key. If batch writing, pass in the batch