forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockWriteBatcher.cpp
More file actions
1552 lines (1271 loc) · 46.3 KB
/
BlockWriteBatcher.cpp
File metadata and controls
1552 lines (1271 loc) · 46.3 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 "BlockWriteBatcher.h"
#include "StoredBlockObj.h"
#include "BlockDataManagerConfig.h"
#include "lmdb_wrapper.h"
#include "Progress.h"
#include "util.h"
#ifdef _MSC_VER
#include "win32_posix.h"
#endif
////////////////////////////////////////////////////////////////////////////////
static void updateBlkDataHeader(
const BlockDataManagerConfig &config,
LMDBBlockDatabase* iface,
StoredHeader const & sbh
)
{
iface->putValue(
BLKDATA, sbh.getDBKey(),
serializeDBValue(sbh, BLKDATA, config.armoryDbType, config.pruneType)
);
}
////////////////////////////////////////////////////////////////////////////////
// This avoids having to do the double-lookup when fetching by hash.
// We still pass in the hash anyway, because the map is indexed by the hash,
// and we'd like to not have to do a lookup for the hash if only provided
// {hgt, dup, idx}
StoredTxOut* BlockWriteBatcher::makeSureSTXOInMap(
LMDBBlockDatabase* iface,
const BinaryData& txHash,
uint16_t txoId)
{
// Get the existing STX in RAM and move it to the stxo vector
// or grab it from DB
BinaryData hashAndId = txHash;
hashAndId.append(WRITE_UINT16_BE(txoId));
auto stxoIter = utxoMap_.find(hashAndId);
if (stxoIter != utxoMap_.end())
{
stxoToUpdate_.push_back(stxoIter->second);
utxoMap_.erase(stxoIter);
return stxoToUpdate_.back().get();
}
stxoIter = utxoMapBackup_.find(hashAndId);
if (stxoIter != utxoMapBackup_.end())
{
stxoToUpdate_.push_back(stxoIter->second);
utxoMapBackup_.erase(stxoIter);
return stxoToUpdate_.back().get();
}
shared_ptr<StoredTxOut> stxo(new StoredTxOut);
BinaryData dbKey;
iface->getStoredTx_byHash(txHash, nullptr, &dbKey);
dbKey.append(WRITE_UINT16_BE(txoId));
iface->getStoredTxOut(*stxo, dbKey);
dbUpdateSize_ += sizeof(StoredTxOut) + stxo->dataCopy_.getSize();
stxoToUpdate_.push_back(move(stxo));
return stxoToUpdate_.back().get();
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::moveStxoToUTXOMap(
const shared_ptr<StoredTxOut>& thisTxOut)
{
stxoToUpdate_.push_back(thisTxOut);
dbUpdateSize_ += sizeof(StoredTxOut)+thisTxOut->dataCopy_.getSize();
utxoMap_[thisTxOut->hashAndId_] = thisTxOut;
}
////////////////////////////////////////////////////////////////////////////////
StoredTxOut* BlockWriteBatcher::lookForUTXOInMap(const BinaryData& txHash,
const uint16_t& txoId)
{
auto utxoIter = utxoMap_.find(txHash);
if (utxoIter != utxoMap_.end())
{
stxoToUpdate_.push_back(utxoIter->second);
if (config_.armoryDbType != ARMORY_DB_SUPER)
utxoMap_.erase(utxoIter);
return stxoToUpdate_.back().get();
}
utxoIter = utxoMapBackup_.find(txHash);
if (utxoIter != utxoMapBackup_.end())
{
stxoToUpdate_.push_back(utxoIter->second);
if (config_.armoryDbType != ARMORY_DB_SUPER)
utxoMap_.erase(utxoIter);
return stxoToUpdate_.back().get();
}
if (config_.armoryDbType == ARMORY_DB_SUPER)
{
shared_ptr<StoredTxOut> stxo(new StoredTxOut);
BinaryData dbKey;
iface_->getStoredTx_byHash(txHash.getSliceRef(0, 32), nullptr, &dbKey);
dbKey.append(WRITE_UINT16_BE(txoId));
iface_->getStoredTxOut(*stxo, dbKey);
dbUpdateSize_ += sizeof(StoredTxOut)+stxo->dataCopy_.getSize();
stxoToUpdate_.push_back(stxo);
return stxoToUpdate_.back().get();
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::resetSshHeader(
StoredScriptHistory& ssh, const BinaryData& uniqKey) const
{
ssh.uniqueKey_ = uniqKey;
ssh.alreadyScannedUpToBlk_ = 0;
ssh.totalTxioCount_ = 0;
ssh.totalUnspent_ = 0;
}
////////////////////////////////////////////////////////////////////////////////
StoredSubHistory& BlockWriteBatcher::makeSureSubSSHInMap(
const BinaryData& uniqKey,
const BinaryData& hgtX)
{
auto& subsshmap = subSshMap_[uniqKey];
auto& subssh = subsshmap[hgtX];
if (subssh.hgtX_.getSize() == 0)
{
if (subSshMapToWrite_.size() != 0)
{
auto sshIter = subSshMapToWrite_.find(uniqKey);
if (sshIter != subSshMapToWrite_.end())
{
auto subsshIter = sshIter->second.find(hgtX);
if (subsshIter != sshIter->second.end())
{
subssh = subsshIter->second;
return subssh;
}
}
}
subssh.hgtX_ = hgtX;
BinaryData key(uniqKey);
key.append(hgtX);
BinaryRefReader brr = iface_->getValueReader(historyDB_, DB_PREFIX_SCRIPT, key);
if (brr.getSize() > 0)
subssh.unserializeDBValue(brr);
dbUpdateSize_ += UPDATE_BYTES_SUBSSH;
}
return subssh;
}
////////////////////////////////////////////////////////////////////////////////
StoredSubHistory& BlockWriteBatcher::makeSureSubSSHInMap_IgnoreDB(
const BinaryData& uniqKey,
const BinaryData& hgtX,
const uint32_t& currentBlockHeight)
{
auto& subsshmap = subSshMap_[uniqKey];
auto& subssh = subsshmap[hgtX];
if (subssh.hgtX_.getSize() == 0)
{
uint32_t fetchHeight = DBUtils::hgtxToHeight(hgtX);
subssh.hgtX_ = hgtX;
if (fetchHeight < currentBlockHeight)
{
BinaryData key(uniqKey);
key.append(hgtX);
BinaryRefReader brr = iface_->getValueReader(
historyDB_, DB_PREFIX_SCRIPT, key);
if (brr.getSize() > 0)
subssh.unserializeDBValue(brr);
}
dbUpdateSize_ += UPDATE_BYTES_SUBSSH;
}
return subssh;
}
////////////////////////////////////////////////////////////////////////////////
StoredScriptHistory& BlockWriteBatcher::makeSureSSHInMap(
const BinaryData& uniqKey)
{
auto& ssh = (*sshToModify_)[uniqKey];
if (!ssh.isInitialized())
{
iface_->getStoredScriptHistorySummary(ssh, uniqKey);
ssh.uniqueKey_ = uniqKey;
}
return ssh;
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::insertSpentTxio(
const TxIOPair& txio,
StoredSubHistory& inHgtSubSsh,
const BinaryData& txOutKey,
const BinaryData& txInKey)
{
auto& mirrorTxio = inHgtSubSsh.txioMap_[txOutKey];
mirrorTxio = txio;
mirrorTxio.setTxIn(txInKey);
dbUpdateSize_ += UPDATE_BYTES_KEY;
}
////////////////////////////////////////////////////////////////////////////////
BlockWriteBatcher::BlockWriteBatcher(
const BlockDataManagerConfig &config,
LMDBBlockDatabase* iface,
bool forCommit
)
: config_(config), iface_(iface),
mostRecentBlockApplied_(0), isForCommit_(forCommit),
dataToCommit_(config.armoryDbType)
{
if (config.armoryDbType == ARMORY_DB_SUPER)
historyDB_ = BLKDATA;
else
historyDB_ = HISTORY;
parent_ = this;
}
BlockWriteBatcher::~BlockWriteBatcher()
{
//a BWB meant for commit doesn't need to run commit() on dtor
if (isForCommit_)
{
clearTransactions();
return;
}
//call final commit, force it
thread committhread = commit(true);
//join on the thread, don't want the destuctor to return until the data has
//been commited
committhread.join();
clearTransactions();
}
BinaryData BlockWriteBatcher::applyBlockToDB(shared_ptr<PulledBlock> pb,
ScrAddrFilter& scrAddrData)
{
//TIMER_START("applyBlockToDBinternal");
if(iface_->getValidDupIDForHeight(pb->blockHeight_) != pb->duplicateID_)
{
LOGERR << "Dup requested is not the main branch for the given height!";
return BinaryData();
}
else
pb->isMainBranch_ = true;
mostRecentBlockApplied_ = pb->blockHeight_;
// We will accumulate undoData as we apply the tx
StoredUndoData sud;
sud.blockHash_ = pb->thisHash_;
sud.blockHeight_ = pb->blockHeight_;
sud.duplicateID_ = pb->duplicateID_;
sbhToUpdate_.push_back(move(*pb));
auto& block = sbhToUpdate_.back();
// Apply all the tx to the update data
for (auto& stx : block.stxMap_)
{
if (stx.second.dataCopy_.getSize() == 0)
{
LOGERR << "bad STX data in applyBlockToDB at height " << block.blockHeight_;
throw std::range_error("bad STX data while applying blocks");
}
applyTxToBatchWriteData(stx.second, &sud, scrAddrData);
}
// At this point we should have a list of STX and SSH with all the correct
// modifications (or creations) to represent this block. Let's apply it.
BinaryData scannedBlockHash = block.thisHash_;
block.blockAppliedToDB_ = true;
dbUpdateSize_ += block.numBytes_;
if (dbUpdateSize_ > UPDATE_BYTES_THRESH)
{
thread committhread = commit();
if (committhread.joinable())
committhread.detach();
}
return scannedBlockHash;
}
void BlockWriteBatcher::reorgApplyBlock(uint32_t hgt, uint8_t dup,
ScrAddrFilter& scrAddrData)
{
forceUpdateSsh_ = true;
resetTransactions();
prepareSshToModify(scrAddrData);
shared_ptr<PulledBlock> pb(new PulledBlock());
{
LMDBEnv::Transaction blockTx(iface_->dbEnv_[BLKDATA].get(), LMDB::ReadOnly);
if (!pullBlockFromDB(*pb, hgt, dup))
{
//Should notify UI before returning
LOGERR << "Failed to load block " << hgt << "," << dup;
return;
}
}
applyBlockToDB(pb, scrAddrData);
thread writeThread = commit(true);
if (writeThread.joinable())
writeThread.join();
clearTransactions();
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::undoBlockFromDB(StoredUndoData & sud,
ScrAddrFilter& scrAddrData)
{
if (resetTxn_ > 0)
clearSubSshMap(resetTxn_);
prepareSshToModify(scrAddrData);
resetTransactions();
PulledBlock pb;
{
LMDBEnv::Transaction blkdataTx(iface_->dbEnv_[BLKDATA].get(), LMDB::ReadOnly);
pullBlockFromDB(pb, sud.blockHeight_, sud.duplicateID_);
}
mostRecentBlockApplied_ = sud.blockHeight_ -1;
///// Put the STXOs back into the DB which were removed by this block
// Process the stxOutsRemovedByBlock_ in reverse order
// Use int32_t index so that -1 != UINT32_MAX and we go into inf loop
for(int32_t i=(int32_t)sud.stxOutsRemovedByBlock_.size()-1; i>=0; i--)
{
StoredTxOut & sudStxo = sud.stxOutsRemovedByBlock_[i];
const uint16_t stxoIdx = sudStxo.txOutIndex_;
if (config_.armoryDbType != ARMORY_DB_SUPER)
{
if (!scrAddrData.hasScrAddress(sudStxo.getScrAddress()))
continue;
}
StoredTxOut* stxoPtr = makeSureSTXOInMap(
iface_,
sudStxo.parentHash_,
stxoIdx);
{
////// Finished updating STX, now update the SSH in the DB
// Updating the SSH objects works the same regardless of pruning
BinaryData uniqKey = stxoPtr->getScrAddress();
BinaryData hgtX = stxoPtr->getHgtX();
StoredSubHistory& subssh =
makeSureSubSSHInMap(uniqKey, hgtX);
// Readd the unspent at TxOut hgtX TxIOPair in the StoredScriptHistory
subssh.markTxOutUnspent(
stxoPtr->getDBKey(false),
dbUpdateSize_,
stxoPtr->getValue(),
stxoPtr->isCoinbase_,
false
);
auto& ssh = makeSureSSHInMap(uniqKey);
ssh.totalUnspent_ += stxoPtr->getValue();
//delete the spent subssh at TxIn hgtX
if (stxoPtr->spentness_ == TXOUT_SPENT)
{
hgtX = stxoPtr->spentByTxInKey_.getSliceCopy(0, 4);
StoredSubHistory& subsshAtInHgt =
makeSureSubSSHInMap(uniqKey, hgtX);
subsshAtInHgt.eraseTxio(stxoPtr->getDBKey(false));
ssh.totalTxioCount_--;
}
}
if (config_.pruneType == DB_PRUNE_NONE)
{
// If full/super, we have the TxOut in DB, just need mark it unspent
if (stxoPtr->spentness_ == TXOUT_UNSPENT ||
stxoPtr->spentByTxInKey_.getSize() == 0)
{
LOGERR << "STXO needs to be re-added/marked-unspent but it";
LOGERR << "was already declared unspent in the DB";
}
stxoPtr->spentness_ = TXOUT_UNSPENT;
stxoPtr->spentByTxInKey_ = BinaryData(0);
}
else
{
// If we're pruning, we should have the Tx in the DB, but without the
// TxOut because it had been pruned by this block on the forward op
stxoPtr->spentness_ = TXOUT_UNSPENT;
stxoPtr->spentByTxInKey_ = BinaryData(0);
}
}
// The OutPoint list is every new, unspent TxOut created by this block.
// When they were added, we updated all the StoredScriptHistory objects
// to include references to them. We need to remove them now.
// Use int32_t index so that -1 != UINT32_MAX and we go into inf loop
//for(int16_t itx=pb.numTx_-1; itx>=0; itx--)
for (auto& stx : pb.stxMap_)
{
for (auto& stxo : values(stx.second.stxoMap_))
{
BinaryData stxoKey = stxo->getDBKey(false);
// Then fetch the StoredScriptHistory of the StoredTxOut scraddress
BinaryData uniqKey = stxo->getScrAddress();
if (config_.armoryDbType != ARMORY_DB_SUPER)
{
if (!scrAddrData.hasScrAddress(uniqKey))
continue;
}
BinaryData hgtX = stxo->getHgtX();
StoredSubHistory& subssh =
makeSureSubSSHInMap(uniqKey, hgtX);
subssh.eraseTxio(stxoKey);
auto& ssh = makeSureSSHInMap(uniqKey);
ssh.totalTxioCount_--;
ssh.totalUnspent_ -= stxo->getValue();
// Now remove any multisig entries that were added due to this TxOut
if(uniqKey[0] == SCRIPT_PREFIX_MULTISIG)
{
vector<BinaryData> addr160List;
BtcUtils::getMultisigAddrList(stxo->getScriptRef(), addr160List);
for(uint32_t a=0; a<addr160List.size(); a++)
{
// Get the individual address obj for this multisig piece
BinaryData uniqKey = HASH160PREFIX + addr160List[a];
if (scrAddrData.armoryDbType_ != ARMORY_DB_SUPER)
{
if (!scrAddrData.hasScrAddress(uniqKey))
continue;
}
StoredSubHistory& sshms =
makeSureSubSSHInMap(uniqKey, hgtX);
sshms.eraseTxio(stxoKey);
auto& ssh = makeSureSSHInMap(uniqKey);
ssh.totalTxioCount_--;
}
}
}
}
// Finally, mark this block as UNapplied.
pb.blockAppliedToDB_ = false;
sbhToUpdate_.push_back(move(pb));
clearTransactions();
if (dbUpdateSize_ > UPDATE_BYTES_THRESH)
{
thread committhread = commit();
if (committhread.joinable())
committhread.join();
}
}
bool BlockWriteBatcher::parseTxIns(
PulledTx& thisSTX,
StoredUndoData * sud,
ScrAddrFilter& scrAddrData)
{
bool txIsMine = false;
for (uint32_t iin = 0; iin < thisSTX.txInIndexes_.size() - 1; iin++)
{
// Get the OutPoint data of TxOut being spent
BinaryData opTxHashAndId =
thisSTX.dataCopy_.getSliceCopy(thisSTX.txInIndexes_[iin], 32);
if (opTxHashAndId == BtcUtils::EmptyHash_)
continue;
const uint32_t opTxoIdx =
READ_UINT32_LE(thisSTX.dataCopy_.getPtr() + thisSTX.txInIndexes_[iin] + 32);
opTxHashAndId.append(WRITE_UINT16_BE(opTxoIdx));
//For scanning a predefined set of addresses, check if this txin
//consumes one of our utxo
//leveraging the stxo in RAM
StoredTxOut* stxoPtr = nullptr;
stxoPtr = lookForUTXOInMap(opTxHashAndId, opTxoIdx);
if (config_.armoryDbType != ARMORY_DB_SUPER)
{
if (stxoPtr == nullptr)
continue;
}
txIsMine = true;
const BinaryData& uniqKey = stxoPtr->getScrAddress();
BinaryData stxoKey = stxoPtr->getDBKey(false);
// Need to modify existing UTXOs, so that we can delete or mark as spent
stxoPtr->spentByTxInKey_ = thisSTX.getDBKeyOfChild(iin, false);
stxoPtr->spentness_ = TXOUT_SPENT;
////// Now update the SSH to show this TxIOPair was spent
// Same story as stxToModify above, except this will actually create a new
// SSH if it doesn't exist in the map or the DB
BinaryData& hgtX = stxoPtr->getHgtX();
StoredSubHistory& subssh = makeSureSubSSHInMap(uniqKey, hgtX);
StoredSubHistory& mirrorsubssh =
makeSureSubSSHInMap_IgnoreDB(
uniqKey,
stxoPtr->spentByTxInKey_.getSliceRef(0, 4),
0);
// update the txio in its subSSH
bool fixed = false;
const TxIOPair* txio = nullptr;
while (nullptr == (txio = subssh.markTxOutSpent(stxoKey)))
{
LOGERR << "missing txio! let's fix this";
subssh.markTxOutUnspent(stxoKey, dbUpdateSize_,
stxoPtr->getValue(), stxoPtr->isCoinbase_, false);
fixed = true;
}
//Mirror the spent txio at txin height
insertSpentTxio(*txio, mirrorsubssh, stxoKey, stxoPtr->spentByTxInKey_);
if (fixed)
{
TxIOPair& mirrorTxio = mirrorsubssh.txioMap_[stxoKey];
mirrorTxio.flagged = true;
}
}
return txIsMine;
}
bool BlockWriteBatcher::parseTxOuts(
PulledTx& thisSTX,
StoredUndoData * sud,
ScrAddrFilter& scrAddrData)
{
bool txIsMine = false;
for (auto& stxoPair : thisSTX.stxoMap_)
{
auto& stxoToAdd = *stxoPair.second;
const BinaryData& uniqKey = stxoToAdd.getScrAddress();
BinaryData hgtX = stxoToAdd.getHgtX();
if (config_.armoryDbType != ARMORY_DB_SUPER)
{
if (!scrAddrData.hasScrAddress(uniqKey))
continue;
auto height = (*sshToModify_)[uniqKey].alreadyScannedUpToBlk_;
if (height >= thisSTX.blockHeight_ && height != 0)
continue;
txIsMine = true;
}
stxoToAdd.spentness_ = TXOUT_UNSPENT;
StoredSubHistory& subssh = makeSureSubSSHInMap_IgnoreDB(
uniqKey,
hgtX,
thisSTX.blockHeight_);
// Add reference to the next STXO to the respective SSH object
if (config_.armoryDbType == ARMORY_DB_SUPER)
{
auto& txio = thisSTX.preprocessedUTXO_[stxoPair.first];
subssh.txioMap_[txio.getDBKeyOfOutput()] = txio;
dbUpdateSize_ += sizeof(TxIOPair)+8;
}
else
{
subssh.markTxOutUnspent(
stxoToAdd.getDBKey(false),
dbUpdateSize_,
stxoToAdd.getValue(),
stxoToAdd.isCoinbase_,
false);
}
// If this was a multisig address, add a ref to each individual scraddr
if (uniqKey[0] == SCRIPT_PREFIX_MULTISIG)
{
vector<BinaryData> addr160List;
BtcUtils::getMultisigAddrList(stxoToAdd.getScriptRef(), addr160List);
for (uint32_t a = 0; a<addr160List.size(); a++)
{
// Get the existing SSH or make a new one
BinaryData uniqKey = HASH160PREFIX + addr160List[a];
if (config_.armoryDbType != ARMORY_DB_SUPER)
{
//do not maintain multisig activity on related scrAddr unless
//in supernode
if (!scrAddrData.hasScrAddress(uniqKey))
continue;
}
StoredSubHistory& sshms = makeSureSubSSHInMap_IgnoreDB(
uniqKey,
hgtX,
thisSTX.blockHeight_);
sshms.markTxOutUnspent(
stxoToAdd.getDBKey(false),
dbUpdateSize_,
stxoToAdd.getValue(),
stxoToAdd.isCoinbase_,
true);
}
}
moveStxoToUTXOMap(stxoPair.second);
}
return txIsMine;
}
////////////////////////////////////////////////////////////////////////////////
// Assume that stx.blockHeight_ and .duplicateID_ are set correctly.
// We created the maps and sets outside this function, because we need to keep
// a master list of updates induced by all tx in this block.
// TODO: Make sure that if Tx5 spends an input from Tx2 in the same
// block that it is handled correctly, etc.
void BlockWriteBatcher::applyTxToBatchWriteData(
PulledTx& thisSTX,
StoredUndoData * sud,
ScrAddrFilter& scrAddrData)
{
bool txIsMine = parseTxOuts(thisSTX, sud, scrAddrData);
txIsMine |= parseTxIns( thisSTX, sud, scrAddrData);
if (config_.armoryDbType != ARMORY_DB_SUPER && txIsMine)
{
auto& countAndHint = txCountAndHint_[thisSTX.getDBKey(true)];
countAndHint.count_ = thisSTX.numTxOut_;
countAndHint.hash_ = thisSTX.thisHash_;
}
}
////////////////////////////////////////////////////////////////////////////////
thread BlockWriteBatcher::commit(bool finalCommit)
{
bool isCommiting = false;
unique_lock<mutex> l(writeLock_, try_to_lock);
if (!l.owns_lock())
{
// lock_ is held if commit() is running, but if we have
// accumulated too much data we can't return from this function
// to accumulate some more, so do a commit() anyway at the end
// of this function. lock_ is used as a flag to indicate
// commitThread is running.
if (!finalCommit && dbUpdateSize_ < UPDATE_BYTES_THRESH * 2)
return thread();
isCommiting = true;
}
else
l.unlock();
//create a BWB for commit (pass true to the constructor)
auto bwbWriteObj = shared_ptr<BlockWriteBatcher>(
new BlockWriteBatcher(config_, iface_, true));
if (forceUpdateSsh_)
{
bwbWriteObj->dataToCommit_.forceUpdateSshAtHeight_ =
mostRecentBlockApplied_ -1;
}
bwbWriteObj->commitId_ = commitId_++;
bwbWriteObj->sbhToUpdate_ = std::move(sbhToUpdate_);
bwbWriteObj->stxoToUpdate_ = std::move(stxoToUpdate_);
bwbWriteObj->txCountAndHint_ = std::move(txCountAndHint_);
bwbWriteObj->mostRecentBlockApplied_ = mostRecentBlockApplied_;
bwbWriteObj->parent_ = this;
if (config_.armoryDbType == ARMORY_DB_SUPER &&
utxoMap_.size() > UTXO_THRESHOLD)
{
utxoMapBackup_.clear();
utxoMapBackup_ = std::move(utxoMap_);
haveFullUTXOList_ = false;
}
if (isCommiting)
{
//the write thread is already running and we cumulated enough data in the
//read thread for the next write. Let's use that idle time to serialize
//the data to commit ahead of time
bwbWriteObj->serializeData(subSshMap_);
}
deleteId_++;
bwbWriteObj->dbUpdateSize_ = dbUpdateSize_;
bwbWriteObj->updateSDBI_ = updateSDBI_;
bwbWriteObj->deleteId_ = deleteId_;
dbUpdateSize_ = 0;
l.lock();
subSshMapToWrite_ = std::move(subSshMap_);
commitingObject_ = bwbWriteObj;
if (isCommiting)
resetTransactions();
thread committhread(writeToDB, bwbWriteObj);
return committhread;
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::prepareSshToModify(const ScrAddrFilter& sasd)
{
//In fullnode, the sshToModify_ container is not wiped after each commit.
//Instead, all SSH for tracked scrAddr, since we know they're the onyl one
//that will get any traffic, and in order to update all alreadyScannedUpToBlk_
//members each commit
//pass a 0 size BinaryData to avoid loading any subSSH
if (sshToModify_)
return;
sshToModify_ = shared_ptr<map<BinaryData, StoredScriptHistory>>(
new map<BinaryData, StoredScriptHistory>);
if (config_.armoryDbType == ARMORY_DB_SUPER)
return;
BinaryData hgtX(0);
uint32_t utxoCount=0;
LMDBEnv::Transaction tx;
iface_->beginDBTransaction(&tx, HISTORY, LMDB::ReadOnly);
/*StoredDBInfo sdbi;
iface_->getStoredDBInfo(HISTORY, sdbi);
utxoFromHeight_ = sdbi.topBlkHgt_;*/
for (auto saPair : sasd.getScrAddrMap())
{
auto& ssh = (*sshToModify_)[saPair.first];
iface_->getStoredScriptHistorySummary(ssh, saPair.first);
if (ssh.totalTxioCount_ != 0)
{
BinaryWriter bwKey(saPair.first.getSize() + 1);
bwKey.put_uint8_t((uint8_t)DB_PREFIX_SCRIPT);
bwKey.put_BinaryData(saPair.first);
LDBIter dbIter = iface_->getIterator(HISTORY);
dbIter.seekToExact(bwKey.getDataRef());
while (dbIter.getKeyRef().startsWith(bwKey.getDataRef()))
{
if (dbIter.getKeyRef().getSize()==bwKey.getSize() +4)
{
//grab subssh
StoredSubHistory subssh;
subssh.hgtX_ = dbIter.getKeyRef().getSliceRef(-4, 4);
subssh.unserializeDBValue(dbIter.getValueReader());
//load all UTXOs listed
//if (utxoCount < UTXO_THRESHOLD)
{
for (auto txio : subssh.txioMap_)
{
if (txio.second.isUTXO())
{
BinaryData dbKey = txio.second.getDBKeyOfOutput();
shared_ptr<StoredTxOut> stxo(new StoredTxOut);
iface_->getStoredTxOut(*stxo, dbKey);
BinaryData txHash = iface_->getTxHashForLdbKey(dbKey.getSliceRef(0, 6));
BinaryWriter bwUtxoKey(34);
bwUtxoKey.put_BinaryData(txHash);
bwUtxoKey.put_uint16_t(stxo->txOutIndex_, BE);
utxoMap_[bwUtxoKey.getDataRef()] = stxo;
utxoCount++;
}
}
}
}
dbIter.advanceAndRead(DB_PREFIX_SCRIPT);
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::writeToDB(shared_ptr<BlockWriteBatcher> bwb)
{
unique_lock<mutex> lock(bwb->parent_->writeLock_);
LMDBBlockDatabase *db = bwb->iface_;
bwb->dataToCommit_.serializeData(*bwb, bwb->parent_->subSshMapToWrite_);
{
bwb->dataToCommit_.putSSH(db);
bwb->dataToCommit_.putSTX(db);
bwb->dataToCommit_.putSBH(db);
bwb->dataToCommit_.deleteEmptyKeys(db);
if (bwb->mostRecentBlockApplied_ != 0 && bwb->updateSDBI_ == true)
bwb->dataToCommit_.updateSDBI(db);
//final commit
bwb->parent_->commitingObject_.reset();
}
BlockWriteBatcher* bwbParent = bwb->parent_;
//signal the readonly transaction to reset
bwbParent->resetTxn_ = bwb->deleteId_;
//signal DB is ready for new commit
lock.unlock();
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::resetTransactions(void)
{
resetTxn_ = 0;
txn_.commit();
txn_.open(iface_->dbEnv_[historyDB_].get(), LMDB::ReadOnly);
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::clearTransactions(void)
{
txn_.commit();
}
////////////////////////////////////////////////////////////////////////////////
void BlockWriteBatcher::grabBlocksFromDB(shared_ptr<LoadedBlockData> blockData,
LMDBBlockDatabase* db)
{
/***
Grab blocks from the DB, put each block in the current block's nextBlock_
***/
//TIMER_START("grabBlocksFromDB");
uint32_t hgt = blockData->topLoadedBlock_;
//find last block
shared_ptr<PulledBlock> *lastBlock = &blockData->block_;
unique_lock<mutex> grabLock(blockData->grabLock_);
while (1)
{
//create read only db txn within main loop, so that it is rewed
//after each sleep period
LMDBEnv::Transaction tx(db->dbEnv_[BLKDATA].get(), LMDB::ReadOnly);
LDBIter ldbIter = db->getIterator(BLKDATA);
uint8_t dupID = db->getValidDupIDForHeight(hgt);
if (!ldbIter.seekToExact(DBUtils::getBlkDataKey(hgt, dupID)))
{
unique_lock<mutex> assignLock(blockData->assignLock_);
*lastBlock = blockData->interruptBlock_;
LOGERR << "Header heigh&dup is not in BLKDATA DB";
LOGERR << "(" << hgt << ", " << dupID << ")";
return;
}
while (blockData->bufferLoad_.load(memory_order_acquire)
< UPDATE_BYTES_THRESH)
{
if (hgt > blockData->endBlock_)
return;
uint8_t dupID = db->getValidDupIDForHeight(hgt);
if (dupID == UINT8_MAX)
{
unique_lock<mutex> assignLock(blockData->assignLock_);
*lastBlock = blockData->interruptBlock_;
LOGERR << "No block in DB at height " << hgt;
return;
}
//make sure iterator is at the right position
auto expected = DBUtils::heightAndDupToHgtx(hgt, dupID);
auto key = ldbIter.getKeyRef().getSliceRef(1, 4);
if (key != expected)
{
//in case the iterator is not at the right key, set it
if (!ldbIter.seekToExact(DBUtils::getBlkDataKey(hgt, dupID)))
{
unique_lock<mutex> assignLock(blockData->assignLock_);
*lastBlock = blockData->interruptBlock_;
LOGERR << "Header heigh&dup is not in BLKDATA DB";
LOGERR << "(" << hgt << ", " << dupID << ")";
return;
}
}
shared_ptr<PulledBlock> pb(new PulledBlock());
if (!pullBlockAtIter(*pb, ldbIter, db))
{
unique_lock<mutex> assignLock(blockData->assignLock_);
*lastBlock = blockData->interruptBlock_;
LOGERR << "No block in DB at height " << hgt;
return;
}
//increment bufferLoad
blockData->bufferLoad_.fetch_add(
pb->numBytes_, memory_order_release);
//assign newly grabbed block to shared_ptr
{
unique_lock<mutex> assignLock(blockData->assignLock_);
*lastBlock = pb;
//let's try to wake up the scan thread
unique_lock<mutex> mu(blockData->scanLock_, defer_lock);
if (mu.try_lock())
blockData->scanCV_.notify_all();
}
//set shared_ptr to next empty block
lastBlock = &pb->nextBlock_;