forked from goatpig/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseBuilder.cpp
More file actions
1471 lines (1181 loc) · 42 KB
/
DatabaseBuilder.cpp
File metadata and controls
1471 lines (1181 loc) · 42 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) 2016, goatpig. //
// Distributed under the MIT license //
// See LICENSE-MIT or https://opensource.org/licenses/MIT //
// //
////////////////////////////////////////////////////////////////////////////////
#include "DatabaseBuilder.h"
#include "BlockUtils.h"
#include "BlockchainScanner.h"
#include "BlockchainScanner_Super.h"
#include "ScrAddrFilter.h"
#include "Transactions.h"
/////////////////////////////////////////////////////////////////////////////
DatabaseBuilder::DatabaseBuilder(BlockFiles& blockFiles,
BlockDataManager& bdm,
const ProgressCallback &progress,
bool forceRescanSSH)
: blockFiles_(blockFiles), db_(bdm.getIFace()),
bdmConfig_(bdm.config()), blockchain_(bdm.blockchain()),
scrAddrFilter_(bdm.getScrAddrFilter()),
progress_(progress),
magicBytes_(db_->getMagicBytes()), topBlockOffset_(0, 0),
forceRescanSSH_(forceRescanSSH)
{}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::init()
{
if (bdmConfig_.checkChain_)
{
verifyChain();
return;
}
TIMER_START("initdb");
//list all files in block data folder
blockFiles_.detectAllBlockFiles();
//read all blocks already in DB and populate blockchain
topBlockOffset_ = loadBlockHeadersFromDB(progress_);
if (bdmConfig_.reportProgress_)
progress_(BDMPhase_OrganizingChain, 0, UINT32_MAX, 0);
auto&& initialReorgState = blockchain_->forceOrganize();
blockchain_->updateBranchingMaps(db_, initialReorgState);
try
{
//rewind the top block offset to catch on missed blocks for db init
auto topBlock = blockchain_->top();
auto rewindHeight = topBlock->getBlockHeight();
if (rewindHeight > 100)
rewindHeight -= 100;
else
rewindHeight = 1;
auto rewindBlock = blockchain_->getHeaderByHeight(rewindHeight);
topBlockOffset_.fileID_ = rewindBlock->getBlockFileNum();
topBlockOffset_.offset_ = rewindBlock->getOffset();
LOGINFO << "Rewinding 100 blocks";
}
catch (exception&)
{}
//update db
TIMER_START("updateblocksindb");
LOGINFO << "updating HEADERS db";
auto reorgState = updateBlocksInDB(
progress_, bdmConfig_.reportProgress_,
BlockDataManagerConfig::getDbType() == ARMORY_DB_SUPER);
TIMER_STOP("updateblocksindb");
double updatetime = TIMER_READ_SEC("updateblocksindb");
LOGINFO << "updated HEADERS db in " << updatetime << "s";
cycleDatabases();
int scanFrom = -1;
bool reset = false;
if (BlockDataManagerConfig::getDbType() != ARMORY_DB_SUPER)
{
verifyTxFilters();
//blockchain object now has the longest chain, update address history
//retrieve all tracked addresses from DB
scrAddrFilter_->getAllScrAddrInDB();
//don't scan without any registered addresses
if (scrAddrFilter_->getScrAddrMap()->size() == 0)
return;
//determine from which block to start scanning
scrAddrFilter_->getScrAddrCurrentSyncState();
scanFrom = scrAddrFilter_->scanFrom();
//DatabaseBuilder objects always operate on sdbi index 0
//BlockchainScanner object depend on the underlying ScrAddrFilter uniqueID
auto&& subsshSdbi = db_->getStoredDBInfo(SUBSSH, 0);
auto&& sshsdbi = db_->getStoredDBInfo(SSH, 0);
//check merkle of registered addresses vs what's in the DB
if (!scrAddrFilter_->hasNewAddresses())
{
//no new addresses were registered in between runs.
if (subsshSdbi.topBlkHgt_ > sshsdbi.topBlkHgt_)
{
//SUBSSH db has scanned ahead of SSH db, no point rescanning these
//blocks
scanFrom = subsshSdbi.topBlkHgt_;
}
}
else
{
//we have newly registered addresses this run, force a full rescan
resetHistory();
scanFrom = -1;
reset = true;
}
}
if (!reorgState.prevTopStillValid_ && !reset)
{
//reorg
undoHistory(reorgState);
scanFrom = min(
scanFrom, (int)reorgState.reorgBranchPoint_->getBlockHeight() + 1);
}
TIMER_START("scanning");
while (1)
{
auto topScannedBlockHash = initTransactionHistory(scanFrom);
cycleDatabases();
if (topScannedBlockHash == blockchain_->top()->getThisHash())
break;
//if we got this far the scan failed, diagnose the DB and repair it
LOGWARN << "topScannedBlockHash does match the hash of the current top";
LOGWARN << "current top is height #" << blockchain_->top()->getBlockHeight();
try
{
auto topscannedblock = blockchain_->getHeaderByHash(topScannedBlockHash);
LOGWARN << "topScannedBlockHash is height #" << topscannedblock->getBlockHeight();
}
catch (...)
{
LOGWARN << "topScannedBlockHash is invalid";
}
LOGINFO << "repairing DB";
//grab top scanned height from SUBSSH DB
auto&& sdbi = db_->getStoredDBInfo(SUBSSH, 0);
//get fileID for height
auto topHeader = blockchain_->getHeaderByHeight(sdbi.topBlkHgt_);
int fileID = topHeader->getBlockFileNum();
//rewind 5 blk files for the good measure
fileID -= 5;
if (fileID < 0)
fileID = 0;
//reparse these blk files
if (!reparseBlkFiles(fileID))
{
LOGERR << "failed to repair DB, aborting";
throw runtime_error("failed to repair DB");
}
}
TIMER_STOP("scanning");
double scanning = TIMER_READ_SEC("scanning");
LOGINFO << "scanned new blocks in " << scanning << "s";
TIMER_STOP("initdb");
double timeSpent = TIMER_READ_SEC("initdb");
LOGINFO << "init db in " << timeSpent << "s";
}
/////////////////////////////////////////////////////////////////////////////
BlockOffset DatabaseBuilder::loadBlockHeadersFromDB(
const ProgressCallback &progress)
{
//TODO: preload the headers db file to speed process up
LOGINFO << "Reading headers from db";
blockchain_->clear();
unsigned counter = 0;
BlockOffset topBlockOffet(0, 0);
const unsigned howManyBlocks = [&]() -> unsigned
{
const time_t btcEpoch = 1230963300; // genesis block ts
const time_t now = time(nullptr);
// every ten minutes we get a block, how many blocks exist?
const unsigned blocks = (now - btcEpoch) / 60 / 10;
return blocks;
}();
ProgressCalculator calc(howManyBlocks);
map<BinaryData, shared_ptr<BlockHeader>> headerMap;
const auto callback = [&](shared_ptr<BlockHeader> h, uint32_t height, uint8_t dup)
{
h->setBlockHeight(height);
h->setDuplicateID(dup);
headerMap.insert(make_pair(h->getThisHash(), h));
BlockOffset currblock(h->getBlockFileNum(), h->getOffset());
if (currblock > topBlockOffet)
topBlockOffet = currblock;
if ((counter++ % 50000) != 0)
return;
if (!bdmConfig_.reportProgress_)
return;
calc.advance(counter);
progress(BDMPhase_DBHeaders,
calc.fractionCompleted(), calc.remainingSeconds(), counter);
};
db_->readAllHeaders(callback);
blockchain_->addBlocksInBulk(headerMap, false);
LOGINFO << "Found " << headerMap.size() << " headers in db";
return topBlockOffet;
}
/////////////////////////////////////////////////////////////////////////////
Blockchain::ReorganizationState DatabaseBuilder::updateBlocksInDB(
const ProgressCallback &progress, bool verbose, bool fullHints)
{
//preload and prefetch
BlockDataLoader bdl(blockFiles_.folderPath());
unsigned threadcount = min(bdmConfig_.threadCount_,
blockFiles_.fileCount() - topBlockOffset_.fileID_);
mutex progressMutex;
unsigned baseID = topBlockOffset_.fileID_;
//init progress
ProgressCalculator calc(blockFiles_.fileCount());
if (verbose)
{
calc.init(baseID);
auto val = calc.fractionCompleted();
progress(BDMPhase_BlockData,
calc.fractionCompleted(), UINT32_MAX,
baseID);
}
auto addblocks = [&](uint16_t fileID, size_t startOffset,
shared_ptr<BlockOffset> bo, bool _verbose)->void
{
while (1)
{
if (!addBlocksToDB(bdl, fileID, startOffset, bo, fullHints))
return;
if (_verbose)
{
unique_lock<mutex> lock(progressMutex, defer_lock);
if (lock.try_lock() && fileID >= baseID)
{
LOGINFO << "parsed block file #" << fileID;
calc.advance(fileID);
progress(BDMPhase_BlockData,
calc.fractionCompleted(), calc.remainingSeconds(),
fileID);
baseID = fileID;
}
}
//reset startOffset for the next file
startOffset = 0;
fileID += threadcount;
}
};
vector<thread> tIDs;
vector<shared_ptr<BlockOffset>> boVec;
for (unsigned i = 1; i < threadcount; i++)
{
boVec.push_back(make_shared<BlockOffset>(topBlockOffset_));
tIDs.push_back(thread(addblocks, topBlockOffset_.fileID_ + i, 0,
boVec.back(), verbose));
}
boVec.push_back(make_shared<BlockOffset>(topBlockOffset_));
addblocks(topBlockOffset_.fileID_, topBlockOffset_.offset_,
boVec.back(), verbose);
for (auto& tID : tIDs)
{
if (tID.joinable())
tID.join();
}
for (auto& blockoffset : boVec)
{
if (*blockoffset > topBlockOffset_)
topBlockOffset_ = *blockoffset;
}
//done parsing new blocks, reorg and add to DB
if (verbose)
progress_(BDMPhase_OrganizingChain, 0, UINT32_MAX, 0);
auto&& reorgState = blockchain_->organize(verbose);
blockchain_->putNewBareHeaders(db_);
return reorgState;
}
/////////////////////////////////////////////////////////////////////////////
bool DatabaseBuilder::addBlocksToDB(BlockDataLoader& bdl,
uint16_t fileID, size_t startOffset, shared_ptr<BlockOffset> bo,
bool fullHints)
{
auto&& blockfilemappointer = bdl.get(fileID);
auto ptr = blockfilemappointer->getPtr();
//ptr is null if we're out of block files
if (ptr == nullptr)
return false;
map<uint32_t, BlockData> bdMap;
auto getID = [&](const BinaryData&)->uint32_t
{
return blockchain_->getNewUniqueID();
};
auto tallyBlocks =
[&](const uint8_t* data, size_t size, size_t offset)->bool
{
//deser full block, check merkle
BlockData bd;
BinaryRefReader brr(data, size);
try
{
bd.deserialize(data, size, nullptr,
getID, true, fullHints);
}
catch (BlockDeserializingException &e)
{
LOGERR << "block deser except: " << e.what();
LOGERR << "block fileID: " << fileID;
return false;
}
catch (exception &e)
{
LOGERR << "exception: " << e.what();
return false;
}
catch (...)
{
//deser failed, ignore this block
LOGERR << "unknown exception";
return false;
}
//block is valid, add to container
bd.setFileID(fileID);
bd.setOffset(offset);
BlockOffset blockoffset(fileID, offset + bd.size());
if (blockoffset > *bo)
*bo = blockoffset;
bdMap.insert(move(make_pair(bd.uniqueID(), move(bd))));
return true;
};
parseBlockFile(ptr, blockfilemappointer->size(),
startOffset, tallyBlocks);
//done parsing, add the headers to the blockchain object
//convert BlockData vector to BlockHeader map first
map<HashString, shared_ptr<BlockHeader>> bhmap;
for (auto& bd : bdMap)
{
auto bh = bd.second.createBlockHeader();
bhmap.insert(move(make_pair(bh->getThisHash(), move(bh))));
}
//add in bulk
auto&& insertedBlocks = blockchain_->addBlocksInBulk(bhmap, true);
if (!fullHints)
{
//process filters
if (BlockDataManagerConfig::getDbType() == ARMORY_DB_FULL)
{
//pull existing file filter bucket from db (if any)
auto&& pool = db_->getFilterPoolForFileNum<TxFilterType>(fileID);
if (insertedBlocks.size() == 0)
{
if (pool.isValid())
{
//this block has a filter pool and there is no data to append,
//we can return
return true;
}
//if we got this far, this block file does not add any new blocks
//to the chain, but it still needs an empty filter pool for the
//resolver to fetch. we simply let it run on an empty block set
}
//tally all block filters
set<TxFilter<TxFilterType>> allFilters;
for (auto& bdId : insertedBlocks)
{
allFilters.insert(move(bdMap[bdId].getTxFilter()));
}
//update bucket
pool.update(allFilters);
//update db entry
db_->putFilterPoolForFileNum(fileID, pool);
}
}
else
{
commitAllTxHints(bdMap, insertedBlocks);
if (BlockDataManagerConfig::getDbType() == ARMORY_DB_SUPER)
commitAllStxos(blockfilemappointer, bdMap, insertedBlocks);
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::parseBlockFile(
const uint8_t* fileMap, size_t fileSize, size_t startOffset,
function<bool(const uint8_t* data, size_t size, size_t offset)> callback)
{
//check magic bytes at start of file
auto magicBytesSize = magicBytes_.getSize();
if (fileSize < magicBytesSize)
{
stringstream ss;
ss << "Block data file size is " << fileSize << "bytes long";
throw runtime_error(ss.str());
}
BinaryDataRef dataMagic(fileMap, magicBytesSize);
if (dataMagic != magicBytes_)
throw runtime_error("Unexpected network magic bytes found in block data file");
//set pointer to start offset
fileMap += startOffset;
//parse the file
size_t progress = startOffset;
while (progress + magicBytesSize < fileSize)
{
size_t localProgress = magicBytesSize;
BinaryDataRef magic(fileMap, magicBytesSize);
if (magic != magicBytes_)
{
//no magic byte trailing the last valid file offset, let's look for one
BinaryDataRef theFile(fileMap + localProgress,
fileSize - progress - localProgress);
int32_t foundOffset = theFile.find(magicBytes_);
if (foundOffset == -1)
return;
LOGINFO << "Found next block after skipping " << foundOffset - 4 << "bytes";
localProgress += foundOffset;
magic.setRef(fileMap + localProgress, magicBytesSize);
if (magic != magicBytes_)
throw runtime_error("parsing for magic byte failed");
localProgress += 4;
}
if (progress + localProgress + 4 >= fileSize)
return;
BinaryDataRef blockSize(fileMap + localProgress, 4);
localProgress += 4;
size_t thisBlkSize = READ_UINT32_LE(blockSize.getPtr());
if (progress + localProgress + thisBlkSize > fileSize)
return;
fileMap += localProgress;
progress += localProgress;
if (callback(
fileMap, thisBlkSize, progress))
{
//only advance for the whole blockSize if callback returned true
fileMap += thisBlkSize;
progress += thisBlkSize;
}
}
}
/////////////////////////////////////////////////////////////////////////////
BinaryData DatabaseBuilder::initTransactionHistory(int32_t startHeight)
{
//Scan history
auto topScannedBlockHash =
scanHistory(startHeight, bdmConfig_.reportProgress_, true);
//return the hash of the last scanned block
return topScannedBlockHash;
}
/////////////////////////////////////////////////////////////////////////////
BinaryData DatabaseBuilder::scanHistory(int32_t startHeight,
bool reportprogress, bool init)
{
if (BlockDataManagerConfig::getDbType() != ARMORY_DB_SUPER)
{
LOGINFO << "scanning new blocks from #" << startHeight << " to #" <<
blockchain_->top()->getBlockHeight();
BlockchainScanner bcs(blockchain_, db_, scrAddrFilter_.get(),
blockFiles_, bdmConfig_.threadCount_, bdmConfig_.ramUsage_,
progress_, reportprogress);
bcs.scan(startHeight);
bcs.updateSSH(forceRescanSSH_, startHeight);
unsigned count = 0;
while (!bcs.resolveTxHashes())
{
++count;
verifyTxFilters();
if (count > 5)
{
LOGERR << "failed to fix filters after 5 attempts";
break;
}
}
return bcs.getTopScannedBlockHash();
}
else
{
BlockchainScanner_Super bcs(
blockchain_, db_,
blockFiles_, init,
bdmConfig_.threadCount_, bdmConfig_.ramUsage_,
progress_, reportprogress);
bcs.scan();
bcs.updateSSH(forceRescanSSH_ & init);
return bcs.getTopScannedBlockHash();
}
}
/////////////////////////////////////////////////////////////////////////////
Blockchain::ReorganizationState DatabaseBuilder::update(void)
{
unique_lock<mutex> lock(scrAddrFilter_->mergeLock_);
//list all files in block data folder
blockFiles_.detectAllBlockFiles();
//update db
auto&& reorgState = updateBlocksInDB(progress_, false,
BlockDataManagerConfig::getDbType() == ARMORY_DB_SUPER);
if (!reorgState.hasNewTop_)
return reorgState;
uint32_t prevTop = reorgState.prevTop_->getBlockHeight();
uint32_t startHeight = reorgState.prevTop_->getBlockHeight() + 1;
if (!reorgState.prevTopStillValid_)
{
//reorg, undo blocks up to branch point
undoHistory(reorgState);
startHeight = reorgState.reorgBranchPoint_->getBlockHeight() + 1;
}
//scan new blocks
BinaryData&& topScannedHash = scanHistory(startHeight, false, false);
if (topScannedHash != blockchain_->top()->getThisHash())
throw runtime_error("scan failure during DatabaseBuilder::update");
//TODO: recover from failed scan
return reorgState;
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::undoHistory(
Blockchain::ReorganizationState& reorgState)
{
if (BlockDataManagerConfig::getDbType() != ARMORY_DB_SUPER)
{
BlockchainScanner bcs(blockchain_, db_, scrAddrFilter_.get(),
blockFiles_, bdmConfig_.threadCount_, bdmConfig_.ramUsage_,
progress_, false);
bcs.undo(reorgState);
}
else
{
BlockchainScanner_Super bcs(blockchain_, db_,
blockFiles_, false,
bdmConfig_.threadCount_, bdmConfig_.ramUsage_,
progress_, false);
bcs.undo(reorgState);
}
blockchain_->updateBranchingMaps(db_, reorgState);
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::resetHistory()
{
//nuke SSH, SUBSSH, TXHINT and STXO DBs
LOGINFO << "reseting history in DB";
db_->resetHistoryDatabases();
}
/////////////////////////////////////////////////////////////////////////////
bool DatabaseBuilder::reparseBlkFiles(unsigned fromID)
{
mutex mu;
map<BinaryData, shared_ptr<BlockHeader>> headerMap;
BlockDataLoader bdl(blockFiles_.folderPath());
auto assessLambda = [&](unsigned fileID)->void
{
while (fileID < blockFiles_.fileCount())
{
auto&& hmap = assessBlkFile(bdl, fileID);
fileID += bdmConfig_.threadCount_;
if (hmap.size() == 0)
continue;
unique_lock<mutex> lock(mu);
headerMap.insert(hmap.begin(), hmap.end());
}
};
unsigned threadcount = min(bdmConfig_.threadCount_,
blockFiles_.fileCount() - topBlockOffset_.fileID_);
vector<thread> tIDs;
for (unsigned i = 1; i < threadcount; i++)
tIDs.push_back(thread(assessLambda, fromID + i));
assessLambda(fromID);
for (auto& tID : tIDs)
{
if (tID.joinable())
tID.join();
}
//headerMap contains blocks that are either missing from our blockchain
//object or are recorded under invalid fileID/offset. Lets forcefully add
//them to the blockchain object, then force a full reorg
if (headerMap.size() == 0)
{
LOGWARN << "did not find any damaged and/or missings blocks";
return false;
}
blockchain_->forceAddBlocksInBulk(headerMap);
blockchain_->forceOrganize();
blockchain_->putNewBareHeaders(db_);
//TODO: edge case: all the new blocks found were orphans, nothing was added
//to the db, will run into the same blocks next run
return true;
}
/////////////////////////////////////////////////////////////////////////////
map<BinaryData, shared_ptr<BlockHeader>> DatabaseBuilder::assessBlkFile(
BlockDataLoader& bdl, unsigned fileID)
{
map<BinaryData, shared_ptr<BlockHeader>> returnMap;
auto&& blockfilemappointer = bdl.get(fileID);
auto ptr = blockfilemappointer->getPtr();
//ptr is null if we're out of block files
if (ptr == nullptr)
return returnMap;
vector<BlockData> bdVec;
auto tallyBlocks = [&](const uint8_t* data, size_t size, size_t offset)->bool
{
//deser full block, check merkle
BlockData bd;
BinaryRefReader brr(data, size);
auto getID = [this](const BinaryData&)->uint32_t
{ return blockchain_->getNewUniqueID(); };
try
{
bd.deserialize(data, size, nullptr, getID, true, false);
}
catch (...)
{
//deser failed, ignore this block
return false;
}
bd.setFileID(fileID);
bd.setOffset(offset);
//query blockchain object for block by hash
BlockHeader* bhPtr = nullptr;
try
{
blockchain_->getHeaderByHash(bd.getHash());
}
catch (range_error&)
{
//catch and continue
}
//add the block either if we don't have it in our blockchain object,
//or if the offsets and/or fileID mismatch
if (bhPtr != nullptr)
{
if (bhPtr->getBlockFileNum() == fileID &&
bhPtr->getOffset() == offset)
return true;
}
bdVec.push_back(move(bd));
return true;
};
parseBlockFile(ptr, blockfilemappointer->size(), 0, tallyBlocks);
//done parsing, add the headers to the blockchain object
//convert BlockData vector to BlockHeader map first
map<HashString, shared_ptr<BlockHeader>> bhmap;
for (auto& bd : bdVec)
{
auto bh = bd.createBlockHeader();
bhmap.insert(make_pair(bh->getThisHash(), bh));
}
return returnMap;
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::verifyChain()
{
/*
builds db (no scanning) with full txhints, then verifies all tx
(consensus and sigs).
*/
//list all files in block data folder
blockFiles_.detectAllBlockFiles();
//read all blocks already in DB and populate blockchain
topBlockOffset_ = loadBlockHeadersFromDB(progress_);
if (bdmConfig_.reportProgress_)
progress_(BDMPhase_OrganizingChain, 0, UINT32_MAX, 0);
auto initialReorgState = blockchain_->forceOrganize();
blockchain_->updateBranchingMaps(db_, initialReorgState);
//update db
LOGINFO << "updating HEADERS db";
auto reorgState = updateBlocksInDB(
progress_, bdmConfig_.reportProgress_, true);
LOGINFO << "updated HEADERS db";
//verify transactions
verifyTransactions();
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::commitAllTxHints(
const map<uint32_t, BlockData>& bdMap,
const set<unsigned>& insertedBlocks)
{
map<BinaryData, StoredTxHints> txHints;
auto addTxHint =
[&](StoredTxHints& stxh, const BinaryData& txkey)->void
{
//make sure key isn't already in there
for (auto& key : stxh.dbKeyList_)
{
if (key == txkey)
return;
}
stxh.dbKeyList_.push_back(txkey);
};
//The readwrite db transactions makes sure only one thread is batching
//txhints at a time. This is relevant, as hints are first pulled from
//disk then updated. In case 2 different blocks commit to the same
//hint, one will likely overwrite the other.
auto&& hintdbtx = db_->beginTransaction(TXHINTS, LMDB::ReadWrite);
{
auto addTxHintMap =
[&](shared_ptr<BCTX> txn, const BinaryData& txkey)->void
{
auto&& txHashPrefix = txn->getHash().getSliceCopy(0, 4);
StoredTxHints& stxh = txHints[txHashPrefix];
//pull txHint from memory first, don't want to override
//existing hints
if (stxh.isNull())
db_->getStoredTxHints(stxh, txHashPrefix);
addTxHint(stxh, txkey);
stxh.preferredDBKey_ = stxh.dbKeyList_.front();
};
for (auto& id : insertedBlocks)
{
auto block_iter = bdMap.find(id);
if (block_iter == bdMap.end())
{
LOGERR << "missing block id in bdmap";
throw runtime_error("missing block id in bdmap");
}
auto& block = block_iter->second;
auto& txns = block.getTxns();
auto nTxn = txns.size();
for (unsigned i=0; i < nTxn; i++)
{
auto& txn = txns[i];
auto&& txkey = DBUtils::getBlkDataKeyNoPrefix(id, 0xFF, i);
addTxHintMap(txn, txkey);
}
}
}
map<BinaryData, BinaryWriter> serializedHints;
//serialize
for (auto& txhint : txHints)
{
auto& bw = serializedHints[txhint.second.getDBKey()];
txhint.second.serializeDBValue(bw);
}
//write
{
for (auto& txhint : serializedHints)
{
db_->putValue(TXHINTS,
txhint.first.getRef(),
txhint.second.getDataRef());
}
}
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::commitAllStxos(
shared_ptr<BlockDataFileMap> blockDataPtr,
const map<uint32_t, BlockData>& bdMap,
const set<unsigned>& insertedBlocks)
{
if (BlockDataManagerConfig::getDbType() != ARMORY_DB_SUPER)
throw runtime_error("invalid db mode");
auto blockPtr = blockDataPtr->getPtr();
vector<pair<BinaryData, BinaryWriter>> serializedStxos;
for (auto& id : insertedBlocks)
{
auto block_iter = bdMap.find(id);
if (block_iter == bdMap.end())
{
LOGERR << "missing block id in bdmap";
throw runtime_error("missing block id in bdmap");
}
BinaryDataRef emptyRef;
auto& block = block_iter->second;
auto& txns = block.getTxns();
for (unsigned i = 0; i < txns.size(); i++)
{
auto& hash = txns[i]->getHash();
auto& txouts = txns[i]->txouts_;
bool isCoinbase = (i == 0);
//commit stxo count
pair<BinaryData, BinaryWriter> stxocount;
stxocount.first = move(DBUtils::getBlkDataKeyNoPrefix(id, 0xFF, i));
stxocount.second.put_var_int(txouts.size());
serializedStxos.push_back(move(stxocount));
for (unsigned y = 0; y < txouts.size(); y++)
{
pair<BinaryData, BinaryWriter> bwPair;
bwPair.first =
move(DBUtils::getBlkDataKeyNoPrefix(id, 0xFF, i, y));
auto txoutDataRef = txns[i]->getTxOutRef(y);
StoredTxOut::serializeDBValue(bwPair.second, ARMORY_DB_SUPER, false,
0, isCoinbase, TXOUT_SPENTUNK, txoutDataRef,
emptyRef, hash.getRef(), y);
serializedStxos.push_back(move(bwPair));
}
}
}
auto&& tx = db_->beginTransaction(STXO, LMDB::ReadWrite);
for (auto& bwPair : serializedStxos)
db_->putValue(
STXO, bwPair.first.getRef(), bwPair.second.getDataRef());
}
/////////////////////////////////////////////////////////////////////////////
void DatabaseBuilder::verifyTransactions()
{
struct ParserState
{
atomic<unsigned> blockHeight_;
atomic<unsigned> unknownErrors_;
atomic<unsigned> unsupportedSigHash_;
atomic<unsigned> unresolvedHashes_;
atomic<unsigned> parsedCount_;
mutex mu_;
ParserState()
{
blockHeight_.store(0);
unknownErrors_.store(0);
unsupportedSigHash_.store(0);
unresolvedHashes_.store(0);
parsedCount_.store(0);
}
};
TIMER_START("10blocks");
//dont preload, prefetch
BlockDataLoader bdl(blockFiles_.folderPath());
auto stateStruct = make_shared<ParserState>();
auto verifyBlockTx = [&bdl, this, stateStruct](void)->void
{