-
Notifications
You must be signed in to change notification settings - Fork 617
/
BlockDataViewer.cpp
1097 lines (866 loc) · 30.7 KB
/
BlockDataViewer.cpp
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 "BlockDataViewer.h"
/////////////////////////////////////////////////////////////////////////////
BlockDataViewer::BlockDataViewer(BlockDataManager_LevelDB* bdm) :
rescanZC_(false), zeroConfCont_(bdm->getIFace())
{
db_ = bdm->getIFace();
bc_ = &bdm->blockchain();
saf_ = bdm->getScrAddrFilter();
bdmPtr_ = bdm;
zcEnabled_ = false;
zcLiteMode_ = false;
groups_.push_back(WalletGroup(this, saf_));
groups_.push_back(WalletGroup(this, saf_));
flagRescanZC(false);
}
/////////////////////////////////////////////////////////////////////////////
BlockDataViewer::~BlockDataViewer()
{
groups_.clear();
}
/////////////////////////////////////////////////////////////////////////////
BtcWallet* BlockDataViewer::registerWallet(
vector<BinaryData> const& scrAddrVec, string IDstr, bool wltIsNew)
{
if (IDstr.empty())
return nullptr;
return groups_[group_wallet].registerWallet(scrAddrVec, IDstr, wltIsNew);
}
/////////////////////////////////////////////////////////////////////////////
BtcWallet* BlockDataViewer::registerLockbox(
vector<BinaryData> const & scrAddrVec, string IDstr, bool wltIsNew)
{
if (IDstr.empty())
return nullptr;
return groups_[group_lockbox].registerWallet(scrAddrVec, IDstr, wltIsNew);
}
/////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::unregisterWallet(const string& IDstr)
{
groups_[group_wallet].unregisterWallet(IDstr);
}
/////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::unregisterLockbox(const string& IDstr)
{
groups_[group_lockbox].unregisterWallet(IDstr);
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::scanWallets(uint32_t startBlock,
uint32_t endBlock, BDV_refresh forceRefresh)
{
if (startBlock == UINT32_MAX)
startBlock = lastScanned_;
if (endBlock == UINT32_MAX)
endBlock = getTopBlockHeight() + 1;
for (auto& group : groups_)
group.merge();
vector<uint32_t> startBlocks;
for (auto& group : groups_)
startBlocks.push_back(startBlock);
auto sbIter = startBlocks.begin();
if (!initialized_)
{
//out of date history, page all wallets' history
for (auto& group : groups_)
{
*sbIter = group.pageHistory();
sbIter++;
}
initialized_ = true;
}
map<BinaryData, vector<BinaryData> > invalidatedZCKeys;
if (startBlock != endBlock)
{
invalidatedZCKeys = zeroConfCont_.purge(
[this](const BinaryData& sa)->bool
{ return saf_->hasScrAddress(sa); });
}
const bool reorg = (lastScanned_ > startBlock);
sbIter = startBlocks.begin();
for (auto& group : groups_)
{
group.scanWallets(*sbIter, endBlock,
reorg, invalidatedZCKeys);
group.updateGlobalLedgerFirstPage(*sbIter, endBlock,
forceRefresh);
sbIter++;
}
zeroConfCont_.resetNewZC();
lastScanned_ = endBlock;
}
////////////////////////////////////////////////////////////////////////////////
bool BlockDataViewer::hasWallet(const BinaryData& ID) const
{
return groups_[group_wallet].hasID(ID);
}
/////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::pprintRegisteredWallets(void) const
{
groups_[group_wallet].pprintRegisteredWallets();
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::addNewZeroConfTx(BinaryData const & rawTx,
uint32_t txtime,
bool writeToFile)
{
if (!zcEnabled_)
return;
SCOPED_TIMER("addNewZeroConfTx");
if (txtime == 0)
txtime = (uint32_t)time(nullptr);
zeroConfCont_.addRawTx(rawTx, txtime);
flagRescanZC(true);
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::enableZeroConf(bool clearMempool)
{
SCOPED_TIMER("enableZeroConf");
LOGINFO << "Enabling zero-conf tracking ";
zcEnabled_ = true;
//zcLiteMode_ = zcLite;
auto zcFilter = [this](const BinaryData& scrAddr)->bool
{ return this->bdmPtr_->getScrAddrFilter()->hasScrAddress(scrAddr); };
zeroConfCont_.loadZeroConfMempool(zcFilter, clearMempool);
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::disableZeroConf(void)
{
SCOPED_TIMER("disableZeroConf");
zcEnabled_ = false;
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::purgeZeroConfPool()
{
const map<BinaryData, vector<BinaryData> > invalidatedTxIOKeys
= zeroConfCont_.purge(
[this](const BinaryData& sa)->bool { return saf_->hasScrAddress(sa); });
for (auto& group : groups_)
group.purgeZeroConfPool(invalidatedTxIOKeys);
}
////////////////////////////////////////////////////////////////////////////////
bool BlockDataViewer::parseNewZeroConfTx()
{
return zeroConfCont_.parseNewZC(
[this](const BinaryData& sa)->bool { return saf_->hasScrAddress(sa); });
}
////////////////////////////////////////////////////////////////////////////////
bool BlockDataViewer::registerAddresses(const vector<BinaryData>& saVec,
BinaryData walletID, bool areNew)
{
if (saVec.empty())
return false;
for (auto& group : groups_)
{
if (group.hasID(walletID))
return group.registerAddresses(saVec, walletID, areNew);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::registerAddressBatch(
const map < BinaryData, vector<BinaryData>>& wltNAddrMap,
bool areNew)
{
//if called from python, feed it a dict such as:
//{wltID1:[addrList1], wltID2:[addrList2]}
map<shared_ptr<BtcWallet>, vector<BinaryData>> wlt_addr;
for (auto& batch : wltNAddrMap)
{
for (auto& group : groups_)
{
auto wlt = group.getWalletByID(batch.first);
if (wlt != nullptr)
{
wlt_addr.insert(make_pair(wlt, batch.second));
break;
}
}
}
saf_->registerAddressBatch(wlt_addr, areNew);
}
////////////////////////////////////////////////////////////////////////////////
const LedgerEntry& BlockDataViewer::getTxLedgerByHash_FromWallets(
const BinaryData& txHash) const
{
checkBDMisReady();
return groups_[group_wallet].getTxLedgerByHash(txHash);
}
////////////////////////////////////////////////////////////////////////////////
const LedgerEntry& BlockDataViewer::getTxLedgerByHash_FromLockboxes(
const BinaryData& txHash) const
{
checkBDMisReady();
return groups_[group_lockbox].getTxLedgerByHash(txHash);
}
/////////////////////////////////////////////////////////////////////////////
TX_AVAILABILITY BlockDataViewer::getTxHashAvail(BinaryDataRef txHash) const
{
checkBDMisReady();
if (db_->getTxRef(txHash).isNull())
{
if (!zeroConfCont_.hasTxByHash(txHash))
return TX_DNE; // No tx at all
else
return TX_ZEROCONF; // Zero-conf tx
}
else
return TX_IN_BLOCKCHAIN; // In the blockchain already
}
/////////////////////////////////////////////////////////////////////////////
Tx BlockDataViewer::getTxByHash(HashString const & txhash) const
{
checkBDMisReady();
if (config().armoryDbType == ARMORY_DB_SUPER)
{
LMDBEnv::Transaction tx(db_->dbEnv_[BLKDATA].get(), LMDB::ReadOnly);
TxRef txrefobj = db_->getTxRef(txhash);
if (!txrefobj.isNull())
return txrefobj.attached(db_).getTxCopy();
else
{
// It's not in the blockchain, but maybe in the zero-conf tx list
return zeroConfCont_.getTxByHash(txhash);
}
}
else
{
StoredTx stx;
if (db_->getStoredTx_byHash(txhash, &stx))
return stx.getTxCopy();
else
return zeroConfCont_.getTxByHash(txhash);
}
}
bool BlockDataViewer::isTxMainBranch(const Tx &tx) const
{
checkBDMisReady();
if (!tx.hasTxRef())
return false;
return tx.getTxRef().attached(db_).isMainBranch();
}
////////////////////////////////////////////////////////////////////////////////
TxOut BlockDataViewer::getPrevTxOut(TxIn & txin) const
{
checkBDMisReady();
if (txin.isCoinbase())
return TxOut();
OutPoint op = txin.getOutPoint();
Tx theTx = getTxByHash(op.getTxHash());
if (!theTx.isInitialized())
throw runtime_error("couldn't find prev tx");
uint32_t idx = op.getTxOutIndex();
return theTx.getTxOutCopy(idx);
}
////////////////////////////////////////////////////////////////////////////////
Tx BlockDataViewer::getPrevTx(TxIn & txin) const
{
checkBDMisReady();
if (txin.isCoinbase())
return Tx();
OutPoint op = txin.getOutPoint();
return getTxByHash(op.getTxHash());
}
////////////////////////////////////////////////////////////////////////////////
HashString BlockDataViewer::getSenderScrAddr(TxIn & txin) const
{
checkBDMisReady();
if (txin.isCoinbase())
return HashString(0);
return getPrevTxOut(txin).getScrAddressStr();
}
////////////////////////////////////////////////////////////////////////////////
int64_t BlockDataViewer::getSentValue(TxIn & txin) const
{
checkBDMisReady();
if (txin.isCoinbase())
return -1;
return getPrevTxOut(txin).getValue();
}
////////////////////////////////////////////////////////////////////////////////
LMDBBlockDatabase* BlockDataViewer::getDB(void) const
{
return db_;
}
////////////////////////////////////////////////////////////////////////////////
uint32_t BlockDataViewer::getTopBlockHeight(void) const
{
checkBDMisReady();
return bc_->top().getBlockHeight();
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::reset()
{
for (auto& group : groups_)
group.reset();
rescanZC_ = false;
zcEnabled_ = false;
zcLiteMode_ = false;
zeroConfCont_.clear();
lastScanned_ = 0;
initialized_ = false;
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::scanScrAddrVector(
const map<BinaryData, ScrAddrObj>& scrAddrMap,
uint32_t startBlock, uint32_t endBlock) const
{
//create new ScrAddrFilter for the occasion
shared_ptr<ScrAddrFilter> saf(saf_->copy());
//register scrAddr with it
for (auto& scrAddrPair : scrAddrMap)
saf->regScrAddrForScan(scrAddrPair.first, startBlock);
//scan addresses
saf->applyBlockRangeToDB(startBlock, endBlock, vector<string>());
}
////////////////////////////////////////////////////////////////////////////////
size_t BlockDataViewer::getWalletsPageCount(void) const
{
checkBDMisReady();
return groups_[group_wallet].getPageCount();
}
////////////////////////////////////////////////////////////////////////////////
vector<LedgerEntry> BlockDataViewer::getWalletsHistoryPage(uint32_t pageId,
bool rebuildLedger, bool remapWallets)
{
checkBDMisReady();
return groups_[group_wallet].getHistoryPage(pageId,
rebuildLedger, remapWallets);
}
////////////////////////////////////////////////////////////////////////////////
size_t BlockDataViewer::getLockboxesPageCount(void) const
{
checkBDMisReady();
return groups_[group_lockbox].getPageCount();
}
////////////////////////////////////////////////////////////////////////////////
vector<LedgerEntry> BlockDataViewer::getLockboxesHistoryPage(uint32_t pageId,
bool rebuildLedger, bool remapWallets)
{
checkBDMisReady();
return groups_[group_lockbox].getHistoryPage(pageId,
rebuildLedger, remapWallets);
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::updateWalletsLedgerFilter(
const vector<BinaryData>& walletsList)
{
groups_[group_wallet].updateLedgerFilter(walletsList);
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::updateLockboxesLedgerFilter(
const vector<BinaryData>& walletsList)
{
groups_[group_lockbox].updateLedgerFilter(walletsList);
}
////////////////////////////////////////////////////////////////////////////////
void BlockDataViewer::flagRefresh(BDV_refresh refresh, const BinaryData& refreshID)
{
if (saf_->bdmIsRunning() == false)
return;
unique_lock<mutex> lock(refreshLock_);
if (refresh_ != BDV_refreshAndRescan)
{
if (refresh == BDV_refreshAndRescan)
refresh_ = BDV_refreshAndRescan;
else
refresh_ = BDV_refreshSkipRescan;
}
if (refreshID.getSize())
refreshIDSet_.insert(refreshID);
if (refresh == BDV_filterChanged)
refreshIDSet_.insert(BinaryData("wallet_filter_changed"));
notifyMainThread();
}
////////////////////////////////////////////////////////////////////////////////
StoredHeader BlockDataViewer::getMainBlockFromDB(uint32_t height) const
{
checkBDMisReady();
uint8_t dupID = db_->getValidDupIDForHeight(height);
return getBlockFromDB(height, dupID);
}
////////////////////////////////////////////////////////////////////////////////
StoredHeader BlockDataViewer::getBlockFromDB(uint32_t height, uint8_t dupID) const
{
StoredHeader sbh;
db_->getStoredHeader(sbh, height, dupID, true);
return sbh;
}
////////////////////////////////////////////////////////////////////////////////
bool BlockDataViewer::scrAddressIsRegistered(const BinaryData& scrAddr) const
{
return saf_->hasScrAddress(scrAddr);
}
////////////////////////////////////////////////////////////////////////////////
BlockHeader BlockDataViewer::getHeaderByHash(const BinaryData& blockHash) const
{
checkBDMisReady();
return bc_->getHeaderByHash(blockHash);
}
////////////////////////////////////////////////////////////////////////////////
vector<UnspentTxOut> BlockDataViewer::getUnspentTxoutsForAddr160List(
const vector<BinaryData>& scrAddrVec, bool ignoreZc) const
{
checkBDMisReady();
ScrAddrFilter* saf = bdmPtr_->getScrAddrFilter();
if (bdmPtr_->config().armoryDbType != ARMORY_DB_SUPER)
{
for (const auto& scrAddr : scrAddrVec)
{
if (!saf->hasScrAddress(scrAddr))
throw std::range_error("Don't have this scrAddr tracked");
}
}
vector<UnspentTxOut> UTXOs;
for (const auto& scrAddr : scrAddrVec)
{
const auto& zcTxioMap = zeroConfCont_.getZCforScrAddr(scrAddr);
StoredScriptHistory ssh;
db_->getStoredScriptHistory(ssh, scrAddr);
map<BinaryData, UnspentTxOut> scrAddrUtxoMap;
db_->getFullUTXOMapForSSH(ssh, scrAddrUtxoMap);
for (const auto& utxoPair : scrAddrUtxoMap)
{
auto zcIter = zcTxioMap.find(utxoPair.first);
if (zcIter != zcTxioMap.end())
if (zcIter->second.hasTxInZC())
continue;
UTXOs.push_back(utxoPair.second);
}
if (ignoreZc)
continue;
for (const auto& zcTxio : zcTxioMap)
{
if (!zcTxio.second.hasTxOutZC())
continue;
if (zcTxio.second.hasTxInZC())
continue;
TxOut txout = zcTxio.second.getTxOutCopy(db_);
UnspentTxOut UTXO = UnspentTxOut(db_, txout, UINT32_MAX);
UTXOs.push_back(UTXO);
}
}
return UTXOs;
}
////////////////////////////////////////////////////////////////////////////////
WalletGroup BlockDataViewer::getStandAloneWalletGroup(
const vector<BinaryData>& wltIDs, HistoryOrdering order)
{
checkBDMisReady();
WalletGroup wg(this, this->saf_);
wg.order_ = order;
auto wallets = groups_[group_wallet].getWalletMap();
auto lockboxes = groups_[group_lockbox].getWalletMap();
for (const auto& wltid : wltIDs)
{
auto wltIter = wallets.find(wltid);
if (wltIter != wallets.end())
{
shared_ptr<BtcWallet> wltCopy(
new BtcWallet(*(wltIter->second.get())));
wg.wallets_[wltid] = wltCopy;
}
else
{
auto lbIter = lockboxes.find(wltid);
if (lbIter != lockboxes.end())
{
shared_ptr<BtcWallet> lbCopy(
new BtcWallet(*(lbIter->second.get())));
wg.wallets_[wltid] = lbCopy;
}
}
}
wg.pageHistory(true);
return wg;
}
////////////////////////////////////////////////////////////////////////////////
uint32_t BlockDataViewer::getBlockTimeByHeight(uint32_t height) const
{
auto bh = blockchain().getHeaderByHeight(height);
return bh.getTimestamp();
}
////////////////////////////////////////////////////////////////////////////////
LedgerDelegate BlockDataViewer::getLedgerDelegateForWallets()
{
auto getHist = [this](uint32_t pageID)->vector<LedgerEntry>
{ return this->getWalletsHistoryPage(pageID, false, false); };
auto getBlock = [this](uint32_t block)->uint32_t
{ return this->groups_[group_wallet].getBlockInVicinity(block); };
auto getPageId = [this](uint32_t block)->uint32_t
{ return this->groups_[group_wallet].getPageIdForBlockHeight(block); };
return LedgerDelegate(getHist, getBlock, getPageId);
}
////////////////////////////////////////////////////////////////////////////////
LedgerDelegate BlockDataViewer::getLedgerDelegateForLockboxes()
{
auto getHist = [this](uint32_t pageID)->vector<LedgerEntry>
{ return this->getLockboxesHistoryPage(pageID, false, false); };
auto getBlock = [this](uint32_t block)->uint32_t
{ return this->groups_[group_lockbox].getBlockInVicinity(block); };
auto getPageId = [this](uint32_t block)->uint32_t
{ return this->groups_[group_lockbox].getPageIdForBlockHeight(block); };
return LedgerDelegate(getHist, getBlock, getPageId);
}
////////////////////////////////////////////////////////////////////////////////
LedgerDelegate BlockDataViewer::getLedgerDelegateForScrAddr(
const BinaryData& wltID, const BinaryData& scrAddr)
{
BtcWallet* wlt = nullptr;
for (auto& group : groups_)
{
ReadWriteLock::WriteLock wl(group.lock_);
auto wltIter = group.wallets_.find(wltID);
if (wltIter != group.wallets_.end())
{
wlt = wltIter->second.get();
break;
}
}
if (wlt == nullptr)
throw runtime_error("Unregistered wallet ID");
ScrAddrObj& sca = wlt->getScrAddrObjRef(scrAddr);
auto getHist = [&](uint32_t pageID)->vector<LedgerEntry>
{ return sca.getHistoryPageById(pageID); };
auto getBlock = [&](uint32_t block)->uint32_t
{ return sca.getBlockInVicinity(block); };
auto getPageId = [&](uint32_t block)->uint32_t
{ return sca.getPageIdForBlockHeight(block); };
return LedgerDelegate(getHist, getBlock, getPageId);
}
////////////////////////////////////////////////////////////////////////////////
uint32_t BlockDataViewer::getClosestBlockHeightForTime(uint32_t timestamp)
{
//get timestamp of genesis block
auto& genBlock = blockchain().getGenesisBlock();
//sanity check
if (timestamp < genBlock.getTimestamp())
return 0;
//get time diff and divide by average time per block (600 sec for Bitcoin)
uint32_t diff = timestamp - genBlock.getTimestamp();
int32_t blockHint = diff/600;
//look for a block in the hint vicinity with a timestamp lower than ours
while (blockHint > 0)
{
auto& block = blockchain().getHeaderByHeight(blockHint);
if (block.getTimestamp() < timestamp)
break;
blockHint -= 1000;
}
//another sanity check
if (blockHint < 0)
return 0;
for (uint32_t id = blockHint; id < blockchain().top().getBlockHeight() - 1; id++)
{
//not looking for a really precise block,
//anything within the an hour of the timestamp is enough
auto& block = blockchain().getHeaderByHeight(id);
if (block.getTimestamp() + 3600 > timestamp)
return block.getBlockHeight();
}
return blockchain().top().getBlockHeight() - 1;
}
////////////////////////////////////////////////////////////////////////////////
TxOut BlockDataViewer::getTxOutCopy(
const BinaryData& txHash, uint16_t index) const
{
LMDBEnv::Transaction tx;
db_->beginDBTransaction(&tx, HISTORY, LMDB::ReadOnly);
BinaryData bdkey;
db_->getStoredTx_byHash(txHash, nullptr, &bdkey);
if (bdkey.getSize() == 0)
return TxOut();
return db_->getTxOutCopy(bdkey, index);
}
////////////////////////////////////////////////////////////////////////////////
Tx BlockDataViewer::getSpenderTxForTxOut(uint32_t height, uint32_t txindex,
uint16_t txoutid) const
{
StoredTxOut stxo;
db_->getStoredTxOut(stxo, height, txindex, txoutid);
if (!stxo.isSpent())
return Tx();
TxRef txref(stxo.spentByTxInKey_.getSliceCopy(0, 6));
return txref.attached(db_).getTxCopy();
}
////////////////////////////////////////////////////////////////////////////////
//// WalletGroup
////////////////////////////////////////////////////////////////////////////////
WalletGroup::~WalletGroup()
{
for (auto& wlt : wallets_)
wlt.second->unregister();
}
////////////////////////////////////////////////////////////////////////////////
BtcWallet* WalletGroup::registerWallet(
vector<BinaryData> const& scrAddrVec, string IDstr, bool wltIsNew)
{
if (IDstr.empty())
{
return nullptr;
}
// Check if the wallet is already registered
ReadWriteLock::WriteLock wl(lock_);
BinaryData id(IDstr);
{
auto regWlt = wallets_.find(id);
if (regWlt != wallets_.end())
{
bdvPtr_->flagRefresh(BDV_refreshSkipRescan, id);
return regWlt->second.get();
}
}
shared_ptr<BtcWallet> newWallet;
{
// Main thread isnt running, just register the wallet
// Add it to the list of wallets to watch
// Instantiate the object through insert.
auto insertResult = wallets_.insert(make_pair(
id, shared_ptr<BtcWallet>(new BtcWallet(bdvPtr_, id))
));
newWallet = insertResult.first->second;
}
newWallet->addAddressBulk(scrAddrVec, wltIsNew);
//register all scrAddr in the wallet with the BDM. It doesn't matter if
//the data is overwritten
vector<BinaryData> saVec;
saVec.reserve(newWallet->getScrAddrMap().size());
for (const auto& scrAddrPair : newWallet->getScrAddrMap())
saVec.push_back(scrAddrPair.first);
saf_->registerAddresses(saVec, newWallet, wltIsNew);
//tell the wallet it is registered
newWallet->setRegistered();
return newWallet.get();
}
////////////////////////////////////////////////////////////////////////////////
void WalletGroup::unregisterWallet(const string& IDstr)
{
ReadWriteLock::WriteLock wl(lock_);
BinaryData id(IDstr);
{
auto wltIter = wallets_.find(id);
if (wltIter == wallets_.end())
return;
}
wallets_.erase(id);
bdvPtr_->notifyMainThread();
}
////////////////////////////////////////////////////////////////////////////////
bool WalletGroup::registerAddresses(const vector<BinaryData>& saVec,
BinaryData walletID, bool areNew)
{
if (saVec.empty())
return false;
ReadWriteLock::ReadLock rl(lock_);
auto wltIter = wallets_.find(walletID);
if (wltIter == wallets_.end())
return false;
return saf_->registerAddresses(saVec, wltIter->second, areNew);
}
////////////////////////////////////////////////////////////////////////////////
bool WalletGroup::hasID(const BinaryData& ID) const
{
ReadWriteLock::ReadLock rl(lock_);
return wallets_.find(ID) != wallets_.end();
}
/////////////////////////////////////////////////////////////////////////////
void WalletGroup::pprintRegisteredWallets(void) const
{
ReadWriteLock::ReadLock rl(lock_);
for (const auto& wlt : values(wallets_))
{
cout << "Wallet:";
wlt->pprintAlittle(cout);
}
}
/////////////////////////////////////////////////////////////////////////////
void WalletGroup::purgeZeroConfPool(
const map<BinaryData, vector<BinaryData> >& invalidatedTxIOKeys)
{
ReadWriteLock::ReadLock rl(lock_);
for (auto& wlt : values(wallets_))
wlt->purgeZeroConfTxIO(invalidatedTxIOKeys);
}
/////////////////////////////////////////////////////////////////////////////
const LedgerEntry& WalletGroup::getTxLedgerByHash(
const BinaryData& txHash) const
{
ReadWriteLock::ReadLock rl(lock_);
for (const auto& wlt : values(wallets_))
{
const LedgerEntry& le = wlt->getLedgerEntryForTx(txHash);
if (le.getTxTime() != 0)
return le;
}
return LedgerEntry::EmptyLedger_;
}
/////////////////////////////////////////////////////////////////////////////
void WalletGroup::reset()
{
ReadWriteLock::ReadLock rl(lock_);
for (const auto& wlt : values(wallets_))
wlt->reset();
}
////////////////////////////////////////////////////////////////////////////////
map<uint32_t, uint32_t> WalletGroup::computeWalletsSSHSummary(
bool forcePaging)
{
map<uint32_t, uint32_t> fullSummary;
ReadWriteLock::ReadLock rl(lock_);
for (auto& wlt : values(wallets_))
{
if (forcePaging)
wlt->mapPages();
if (wlt->uiFilter_ == false)
continue;
const auto& wltSummary = wlt->getSSHSummary();
for (auto summary : wltSummary)
fullSummary[summary.first] += summary.second;
}
return fullSummary;
}
////////////////////////////////////////////////////////////////////////////////
uint32_t WalletGroup::pageHistory(bool forcePaging)
{
auto computeSummary = [this](bool force)->map<uint32_t, uint32_t>
{ return this->computeWalletsSSHSummary(force); };
hist_.mapHistory(computeSummary, forcePaging);
return hist_.getPageBottom(0);
}
////////////////////////////////////////////////////////////////////////////////
vector<LedgerEntry> WalletGroup::getHistoryPage(uint32_t pageId,
bool rebuildLedger, bool remapWallets)
{
unique_lock<mutex> mu(globalLedgerLock_);
if (pageId >= hist_.getPageCount())
throw std::range_error("pageId out of range");
if (order_ == order_ascending)
pageId = hist_.getPageCount() - pageId - 1;
//if (pageId == hist_.getCurrentPage() && !rebuildLedger && !remapWallets)
//return globalLedger_;
if (rebuildLedger || remapWallets)
pageHistory(remapWallets);
hist_.setCurrentPage(pageId);
vector<LedgerEntry> vle;
{
//globalLedger_.clear();
ReadWriteLock::ReadLock rl(lock_);
for (auto& wlt : values(wallets_))
{
auto getTxio = [&wlt](uint32_t start, uint32_t end,
map<BinaryData, TxIOPair>& outMap)->void
{ return wlt->getTxioForRange(start, end, outMap); };
auto buildLedgers = [&wlt](map<BinaryData, LedgerEntry>& le,
const map<BinaryData, TxIOPair>& txioMap,
uint32_t startBlock, uint32_t endBlock)->void
{ wlt->updateWalletLedgersFromTxio(le, txioMap, startBlock, endBlock); };
if (!wlt->uiFilter_)
continue;
map<BinaryData, LedgerEntry> leMap;
hist_.getPageLedgerMap(getTxio, buildLedgers, pageId, leMap);
for (const LedgerEntry& le : values(leMap))
vle.push_back(le);
}
}
if (order_ == order_ascending)
sort(vle.begin(), vle.end());
else
{
LedgerEntry_DescendingOrder desc;
sort(vle.begin(), vle.end(), desc);
}
return vle;
}
////////////////////////////////////////////////////////////////////////////////
void WalletGroup::updateLedgerFilter(const vector<BinaryData>& walletsList)
{
ReadWriteLock::ReadLock rl(lock_);
for (auto& wlt : values(wallets_))
wlt->uiFilter_ = false;
for (auto walletID : walletsList)
wallets_[walletID]->uiFilter_ = true;