forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockUtils.cpp
More file actions
3311 lines (2824 loc) · 112 KB
/
BlockUtils.cpp
File metadata and controls
3311 lines (2824 loc) · 112 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-2012, Alan C. Reiner <alan.reiner@gmail.com> //
// Distributed under the GNU Affero General Public License (AGPL v3) //
// See LICENSE or http://www.gnu.org/licenses/agpl.html //
// //
////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <time.h>
#include <stdio.h>
#include "BlockUtils.h"
BlockDataManager_MMAP* BlockDataManager_MMAP::theOnlyBDM_ = NULL;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// TxIOPair Methods
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
TxIOPair::TxIOPair(void) :
amount_(0),
txPtrOfOutput_(NULL),
indexOfOutput_(0),
txPtrOfInput_(NULL),
indexOfInput_(0),
txPtrOfOutputZC_(NULL),
indexOfOutputZC_(0),
txPtrOfInputZC_(NULL),
indexOfInputZC_(0),
isTxOutFromSelf_(false),
isFromCoinbase_(false) {}
//////////////////////////////////////////////////////////////////////////////
TxIOPair::TxIOPair(uint64_t amount) :
amount_(amount),
txPtrOfOutput_(NULL),
indexOfOutput_(0),
txPtrOfInput_(NULL),
indexOfInput_(0),
txPtrOfOutputZC_(NULL),
indexOfOutputZC_(0),
txPtrOfInputZC_(NULL),
indexOfInputZC_(0) ,
isTxOutFromSelf_(false),
isFromCoinbase_(false) {}
//////////////////////////////////////////////////////////////////////////////
TxIOPair::TxIOPair(TxRef* txPtrO, uint32_t txoutIndex) :
amount_(0),
txPtrOfInput_(NULL),
indexOfInput_(0) ,
txPtrOfOutputZC_(NULL),
indexOfOutputZC_(0),
txPtrOfInputZC_(NULL),
indexOfInputZC_(0),
isTxOutFromSelf_(false),
isFromCoinbase_(false)
{
setTxOutRef(txPtrO, txoutIndex);
}
//////////////////////////////////////////////////////////////////////////////
TxIOPair::TxIOPair(TxRef* txPtrO,
uint32_t txoutIndex,
TxRef* txPtrI,
uint32_t txinIndex) :
amount_(0),
txPtrOfOutputZC_(NULL),
indexOfOutputZC_(0),
txPtrOfInputZC_(NULL),
indexOfInputZC_(0),
isTxOutFromSelf_(false),
isFromCoinbase_(false)
{
setTxOutRef(txPtrO, txoutIndex);
setTxInRef (txPtrI, txinIndex );
}
//////////////////////////////////////////////////////////////////////////////
HashString TxIOPair::getTxHashOfOutput(void)
{
if(!hasTxOut())
return BtcUtils::EmptyHash_;
else
return txPtrOfOutput_->getThisHash();
}
//////////////////////////////////////////////////////////////////////////////
HashString TxIOPair::getTxHashOfInput(void)
{
if(!hasTxIn())
return BtcUtils::EmptyHash_;
else
return txPtrOfInput_->getThisHash();
}
TxOutRef TxIOPair::getTxOutRef(void) const
{
// I actually want this to segfault when there is no TxOutRef...
// we should't ever be trying to access it without checking it
// first in the calling code
if(hasTxOut())
return txPtrOfOutput_->getTxOutRef(indexOfOutput_);
else
return getTxOutRefZC();
}
TxInRef TxIOPair::getTxInRef(void) const
{
if(hasTxIn())
return txPtrOfInput_->getTxInRef(indexOfInput_);
else
return getTxInRefZC();
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::setTxInRef(TxRef* txref, uint32_t index, bool isZeroConf)
{
if(isZeroConf)
{
if(hasTxInInMain() || hasTxInZC())
return false;
else
{
txPtrOfInput_ = NULL;
indexOfInput_ = 0;
txPtrOfInputZC_ = txref;
indexOfInputZC_ = index;
}
}
else
{
txPtrOfInput_ = txref;
indexOfInput_ = index;
txPtrOfInputZC_ = NULL;
indexOfInputZC_ = 0;
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::setTxOutRef(TxRef* txref, uint32_t index, bool isZeroConf)
{
if(isZeroConf)
{
if(hasTxOutInMain() || hasTxOutZC())
return false;
else
{
txPtrOfOutput_ = NULL;
indexOfOutput_ = 0;
txPtrOfOutputZC_ = txref;
indexOfOutputZC_ = index;
if(hasTxOutZC())
amount_ = getTxOutRefZC().getValue();
}
}
else
{
txPtrOfOutput_ = txref;
indexOfOutput_ = index;
txPtrOfOutputZC_ = NULL;
indexOfOutputZC_ = 0;
if(hasTxOut())
amount_ = getTxOutRef().getValue();
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::isStandardTxOutScript(void)
{
if(hasTxOut())
return getTxOutRef().isStandard();
return false;
}
//////////////////////////////////////////////////////////////////////////////
pair<bool,bool> TxIOPair::reassessValidity(void)
{
pair<bool,bool> result;
result.first = hasTxOutInMain();
result.second = hasTxInInMain();
return result;
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::isSpent(void)
{
// Not sure whether we should verify hasTxOut. It wouldn't make much
// sense to have TxIn but not TxOut, but there might be a preferred
// behavior in such awkward circumstances
return (hasTxInInMain() || hasTxInZC());
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::isUnspent(void)
{
return ( (hasTxOut() || hasTxOutZC()) && !isSpent());
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::isSpendable(uint32_t currBlk)
{
// Spendable TxOuts are ones with at least 1 confirmation, or zero-conf
// TxOuts that were sent-to-self. Obviously, they should be unspent, too
if( hasTxInInMain() || hasTxInZC() )
return false;
if( hasTxOutInMain() )
{
uint32_t nConf = currBlk - txPtrOfOutput_->getBlockHeight() + 1;
if(isFromCoinbase_ && nConf<=COINBASE_MATURITY)
return false;
else
return true;
}
if( hasTxOutZC() && isTxOutFromSelf() )
return true;
return false;
}
//////////////////////////////////////////////////////////////////////////////
bool TxIOPair::isMineButUnconfirmed(uint32_t currBlk)
{
// All TxOuts that were from our own transactions are always confirmed
if(isTxOutFromSelf())
return false;
if( (hasTxIn() && txPtrOfInput_->isMainBranch()) || hasTxInZC() )
return false;
if(hasTxOutInMain())
{
uint32_t nConf = currBlk - txPtrOfOutput_->getBlockHeight() + 1;
if(isFromCoinbase_)
return (nConf<COINBASE_MATURITY);
else
return (nConf<MIN_CONFIRMATIONS);
}
else if( hasTxOutZC() && !isTxOutFromSelf() )
return true;
return false;
}
bool TxIOPair::hasTxOutInMain(void) const
{
return (hasTxOut() && txPtrOfOutput_->isMainBranch());
}
bool TxIOPair::hasTxInInMain(void) const
{
return (hasTxIn() && txPtrOfInput_->isMainBranch());
}
void TxIOPair::clearZCFields(void)
{
txPtrOfOutputZC_ = NULL;
txPtrOfInputZC_ = NULL;
indexOfOutputZC_ = 0;
indexOfInputZC_ = 0;
isTxOutFromSelf_ = false;
}
void TxIOPair::pprintOneLine(void)
{
printf(" Val:(%0.3f)\t (STS, O,I, Omb,Imb, Oz,Iz) %d %d%d %d%d %d%d\n",
(double)getValue()/1e8,
(isTxOutFromSelf() ? 1 : 0),
(hasTxOut() ? 1 : 0),
(hasTxIn() ? 1 : 0),
(hasTxOutInMain() ? 1 : 0),
(hasTxInInMain() ? 1 : 0),
(hasTxOutZC() ? 1 : 0),
(hasTxInZC() ? 1 : 0));
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// LedgerEntry
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool LedgerEntry::operator<(LedgerEntry const & le2) const
{
if( blockNum_ != le2.blockNum_)
return blockNum_ < le2.blockNum_;
else if( index_ != le2.index_)
return index_ < le2.index_;
else
return false;
}
//////////////////////////////////////////////////////////////////////////////
bool LedgerEntry::operator==(LedgerEntry const & le2) const
{
return (blockNum_ == le2.blockNum_ && index_ == le2.index_);
}
void LedgerEntry::pprint(void)
{
cout << "LedgerEntry: " << endl;
cout << " Addr20 : " << getAddrStr20().toHexStr() << endl;
cout << " Value : " << getValue()/1e8 << endl;
cout << " BlkNum : " << getBlockNum() << endl;
cout << " TxHash : " << getTxHash().toHexStr() << endl;
cout << " TxIndex : " << getIndex() << endl;
cout << " isValid : " << (isValid() ? 1 : 0) << endl;
cout << " sentSelf: " << (isSentToSelf() ? 1 : 0) << endl;
cout << " isChange: " << (isChangeBack() ? 1 : 0) << endl;
cout << endl;
}
void LedgerEntry::pprintOneLine(void)
{
printf(" Addr:%s Tx:%s:%02d BTC:%0.3f Blk:%06d\n",
" ",
getTxHash().getSliceCopy(0,8).toHexStr().c_str(),
getIndex(),
getValue()/1e8,
getBlockNum());
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// BtcAddress Methods
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
BtcAddress::BtcAddress(HashString addr,
uint32_t firstBlockNum,
uint32_t firstTimestamp,
uint32_t lastBlockNum,
uint32_t lastTimestamp) :
address20_(addr),
firstBlockNum_(firstBlockNum),
firstTimestamp_(firstTimestamp),
lastBlockNum_(lastBlockNum),
lastTimestamp_(lastTimestamp)
{
relevantTxIOPtrs_.clear();
relevantTxIOPtrsZC_.clear();
}
////////////////////////////////////////////////////////////////////////////////
uint64_t BtcAddress::getSpendableBalance(uint32_t currBlk)
{
uint64_t balance = 0;
for(uint32_t i=0; i<relevantTxIOPtrs_.size(); i++)
{
if(relevantTxIOPtrs_[i]->isSpendable())
balance += relevantTxIOPtrs_[i]->getValue();
}
for(uint32_t i=0; i<relevantTxIOPtrsZC_.size(); i++)
{
if(relevantTxIOPtrsZC_[i]->isSpendable())
balance += relevantTxIOPtrsZC_[i]->getValue();
}
return balance;
}
////////////////////////////////////////////////////////////////////////////////
uint64_t BtcAddress::getUnconfirmedBalance(uint32_t currBlk)
{
uint64_t balance = 0;
for(uint32_t i=0; i<relevantTxIOPtrs_.size(); i++)
{
if(relevantTxIOPtrs_[i]->isMineButUnconfirmed(currBlk))
balance += relevantTxIOPtrs_[i]->getValue();
}
for(uint32_t i=0; i<relevantTxIOPtrsZC_.size(); i++)
{
if(relevantTxIOPtrsZC_[i]->isMineButUnconfirmed(currBlk))
balance += relevantTxIOPtrsZC_[i]->getValue();
}
return balance;
}
////////////////////////////////////////////////////////////////////////////////
uint64_t BtcAddress::getFullBalance(void)
{
uint64_t balance = 0;
for(uint32_t i=0; i<relevantTxIOPtrs_.size(); i++)
{
TxIOPair & txio = *relevantTxIOPtrs_[i];
if(txio.isUnspent())
balance += txio.getValue();
}
for(uint32_t i=0; i<relevantTxIOPtrsZC_.size(); i++)
{
TxIOPair & txio = *relevantTxIOPtrsZC_[i];
if(txio.isUnspent())
balance += txio.getValue();
}
return balance;
}
////////////////////////////////////////////////////////////////////////////////
vector<UnspentTxOut> BtcAddress::getSpendableTxOutList(uint32_t blkNum)
{
vector<UnspentTxOut> utxoList(0);
for(uint32_t i=0; i<relevantTxIOPtrs_.size(); i++)
{
TxIOPair & txio = *relevantTxIOPtrs_[i];
if(txio.isSpendable(blkNum))
{
TxOutRef txoutref = txio.getTxOutRef();
utxoList.push_back( UnspentTxOut(txoutref, blkNum) );
}
}
for(uint32_t i=0; i<relevantTxIOPtrsZC_.size(); i++)
{
TxIOPair & txio = *relevantTxIOPtrsZC_[i];
if(txio.isSpendable(blkNum))
{
TxOutRef txoutref = txio.getTxOutRef();
utxoList.push_back( UnspentTxOut(txoutref, blkNum) );
}
}
return utxoList;
}
////////////////////////////////////////////////////////////////////////////////
vector<UnspentTxOut> BtcAddress::getFullTxOutList(uint32_t blkNum)
{
vector<UnspentTxOut> utxoList(0);
for(uint32_t i=0; i<relevantTxIOPtrs_.size(); i++)
{
TxIOPair & txio = *relevantTxIOPtrs_[i];
if(txio.isUnspent())
{
TxOutRef txoutref = txio.getTxOutRef();
utxoList.push_back( UnspentTxOut(txoutref, blkNum) );
}
}
for(uint32_t i=0; i<relevantTxIOPtrsZC_.size(); i++)
{
TxIOPair & txio = *relevantTxIOPtrsZC_[i];
if(txio.isUnspent())
{
TxOutRef txoutref = txio.getTxOutRef();
utxoList.push_back( UnspentTxOut(txoutref, blkNum) );
}
}
return utxoList;
}
////////////////////////////////////////////////////////////////////////////////
uint32_t BtcAddress::removeInvalidEntries(void)
{
vector<LedgerEntry> newLedger(0);
uint32_t leRemoved = 0;
for(uint32_t i=0; i<ledger_.size(); i++)
{
if(!ledger_[i].isValid())
leRemoved++;
else
newLedger.push_back(ledger_[i]);
}
ledger_.clear();
ledger_ = newLedger;
return leRemoved;
}
////////////////////////////////////////////////////////////////////////////////
void BtcAddress::sortLedger(void)
{
sort(ledger_.begin(), ledger_.end());
}
////////////////////////////////////////////////////////////////////////////////
void BtcAddress::addLedgerEntry(LedgerEntry const & le, bool isZeroConf)
{
if(isZeroConf)
ledgerZC_.push_back(le);
else
ledger_.push_back(le);
}
////////////////////////////////////////////////////////////////////////////////
void BtcAddress::addTxIO(TxIOPair * txio, bool isZeroConf)
{
if(isZeroConf)
relevantTxIOPtrsZC_.push_back(txio);
else
relevantTxIOPtrs_.push_back(txio);
}
////////////////////////////////////////////////////////////////////////////////
void BtcAddress::addTxIO(TxIOPair & txio, bool isZeroConf)
{
if(isZeroConf)
relevantTxIOPtrsZC_.push_back(&txio);
else
relevantTxIOPtrs_.push_back(&txio);
}
////////////////////////////////////////////////////////////////////////////////
void BtcAddress::pprintLedger(void)
{
cout << "Address Ledger: " << getAddrStr20().toHexStr() << endl;
for(uint32_t i=0; i<ledger_.size(); i++)
ledger_[i].pprintOneLine();
for(uint32_t i=0; i<ledgerZC_.size(); i++)
ledgerZC_[i].pprintOneLine();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// BtcWallet Methods
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// If the wallet is not registered with the BDM, the following two methods do
// the exact same thing. The only difference is to tell the BDM whether it
// should do a rescan of the blockchain, or if we know there's nothing to find
// so don't bother (perhaps because we just created the address)...
void BtcWallet::addAddress(HashString addr,
uint32_t firstTimestamp,
uint32_t firstBlockNum,
uint32_t lastTimestamp,
uint32_t lastBlockNum)
{
BtcAddress* addrPtr = &(addrMap_[addr]);
*addrPtr = BtcAddress(addr, firstTimestamp, firstBlockNum,
lastTimestamp, lastBlockNum);
addrPtrVect_.push_back(addrPtr);
// Default behavior is "don't know, must rescan" if no firstBlk is spec'd
if(bdmPtr_!=NULL)
bdmPtr_->registerImportedAddress(addr, firstBlockNum);
}
/////////////////////////////////////////////////////////////////////////////
void BtcWallet::addNewAddress(HashString addr)
{
// TODO: figure out how I might intelligently synchronize
BtcAddress* addrPtr = &(addrMap_[addr]);
*addrPtr = BtcAddress(addr, 0,0, 0,0);
addrPtrVect_.push_back(addrPtr);
if(bdmPtr_!=NULL)
bdmPtr_->registerNewAddress(addr);
}
/////////////////////////////////////////////////////////////////////////////
void BtcWallet::addAddress(BtcAddress const & newAddr)
{
if(newAddr.getAddrStr20().getSize() > 0)
{
BtcAddress * addrPtr = &(addrMap_[newAddr.getAddrStr20()]);
*addrPtr = newAddr;
addrPtrVect_.push_back(addrPtr);
}
if(bdmPtr_!=NULL)
bdmPtr_->registerImportedAddress(newAddr.getAddrStr20(),
newAddr.getFirstBlockNum());
}
/////////////////////////////////////////////////////////////////////////////
// SWIG has some serious problems with typemaps and variable arg lists
// Here I just create some extra functions that sidestep all the problems
// but it would be nice to figure out "typemap typecheck" in SWIG...
void BtcWallet::addAddress_BtcAddress_(BtcAddress const & newAddr)
{
addAddress(newAddr);
}
/////////////////////////////////////////////////////////////////////////////
void BtcWallet::addAddress_1_(HashString addr)
{
PDEBUG("Adding address to BtcWallet");
addAddress(addr);
}
/////////////////////////////////////////////////////////////////////////////
void BtcWallet::addAddress_3_(HashString addr,
uint32_t firstTimestamp,
uint32_t firstBlockNum)
{
addAddress(addr, firstBlockNum, firstTimestamp);
}
/////////////////////////////////////////////////////////////////////////////
void BtcWallet::addAddress_5_(HashString addr,
uint32_t firstTimestamp,
uint32_t firstBlockNum,
uint32_t lastTimestamp,
uint32_t lastBlockNum)
{
addAddress(addr, firstBlockNum, firstTimestamp, lastBlockNum, lastTimestamp);
}
/////////////////////////////////////////////////////////////////////////////
bool BtcWallet::hasAddr(HashString const & addr20)
{
return addrMap_.find(addr20) != addrMap_.end();
}
/////////////////////////////////////////////////////////////////////////////
// Determine, as fast as possible, whether this tx is relevant to us
// Return <IsOurs, InputIsOurs>
pair<bool,bool> BtcWallet::isMineBulkFilter( TxRef & tx )
{
// Since 99.999%+ of all transactions are not ours, let's do the
// fastest bulk filter possible, even though it will add
// redundant computation to the tx that are ours. In fact,
// we will skip the TxInRef/TxOutRef convenience methods and follow the
// pointers directly the data we want
uint8_t const * txStartPtr = tx.getPtr();
for(uint32_t iin=0; iin<tx.getNumTxIn(); iin++)
{
// We have the txin, now check if it contains one of our TxOuts
static OutPoint op;
op.unserialize(txStartPtr + tx.getTxInOffset(iin));
if(txioMap_.find(op) != txioMap_.end())
return pair<bool,bool>(true,true);
}
// TxOuts are a little more complicated, because we have to process each
// different type separately. Nonetheless, 99% of transactions use the
// 25-byte repr which is ridiculously fast
for(uint32_t iout=0; iout<tx.getNumTxOut(); iout++)
{
static uint8_t scriptLenFirstByte;
static HashString addr20(20);
uint8_t const * ptr = (txStartPtr + tx.getTxOutOffset(iout) + 8);
scriptLenFirstByte = *(uint8_t*)ptr;
if(scriptLenFirstByte == 25)
{
// Std TxOut with 25-byte script
addr20.copyFrom(ptr+4, 20);
if( hasAddr(addr20) )
return pair<bool,bool>(true,false);
}
else if(scriptLenFirstByte==67)
{
// Std spend-coinbase TxOut script
static HashString addr20(20);
BtcUtils::getHash160_NoSafetyCheck(ptr+2, 65, addr20);
if( hasAddr(addr20) )
return pair<bool,bool>(true,false);
}
else
{
//TxOutRef txout = tx.getTxOutRef(iout);
//for(uint32_t i=0; i<addrPtrVect_.size(); i++)
//{
//BtcAddress & thisAddr = *(addrPtrVect_[i]);
//HashString const & addr20 = thisAddr.getAddrStr20();
//if(txout.getScriptRef().find(thisAddr.getAddrStr20()) > -1)
//scanNonStdTx(0, 0, tx, iout, thisAddr);
//continue;
//}
//break;
}
}
// If we got here, it's either non std or not ours
return pair<bool,bool>(false,false);
}
/////////////////////////////////////////////////////////////////////////////
// This method is used in the registeredAddrScan to conditionally create and
// insert a transaction into the registered list
void BlockDataManager_MMAP::insertRegisteredTxIfNew(HashString txHash)
{
// .insert() function returns pair<iter,bool> with bool true if inserted
if(registeredTxSet_.insert(txHash).second == true)
{
TxRef* tx_ptr = getTxByHash(txHash);
uint32_t tx_blknum = tx_ptr->getBlockHeight();
uint32_t tx_blkidx = tx_ptr->getBlockTxIndex();
RegisteredTx regTx(txHash, tx_blknum, tx_blkidx);
registeredTxList_.push_back(regTx);
}
}
/////////////////////////////////////////////////////////////////////////////
// This basically does the same thing as the bulk filter, but it's for the
// BDM to collect data on registered wallets/addresses during the initial
// blockchain scan. It needs to track relevant OutPoints and produce a
// list of transactions that are relevant to the registered wallets.
void BlockDataManager_MMAP::registeredAddrScan( TxRef & tx )
{
if(registeredAddrMap_.size() == 0)
return;
uint8_t const * txStartPtr = tx.getPtr();
for(uint32_t iin=0; iin<tx.getNumTxIn(); iin++)
{
// We have the txin, now check if it contains one of our TxOuts
static OutPoint op;
op.unserialize(txStartPtr + tx.getTxInOffset(iin));
if(registeredOutPoints_.count(op) > 0)
{
insertRegisteredTxIfNew(tx.getThisHash());
break; // we only care if ANY txIns are ours, not which ones
}
}
// We have to scan all TxOuts regardless, to make sure our list of
// registeredOutPoints_ is up-to-date so that we can identify TxIns that are
// ours on future to-be-scanned transactions
for(uint32_t iout=0; iout<tx.getNumTxOut(); iout++)
{
static uint8_t scriptLenFirstByte;
static HashString addr20(20);
uint8_t const * ptr = (txStartPtr + tx.getTxOutOffset(iout) + 8);
scriptLenFirstByte = *(uint8_t*)ptr;
if(scriptLenFirstByte == 25)
{
// Std TxOut with 25-byte script
addr20.copyFrom(ptr+4, 20);
if( addressIsRegistered(addr20) )
{
HashString txHash = tx.getThisHash();
insertRegisteredTxIfNew(txHash);
registeredOutPoints_.insert(OutPoint(txHash, iout));
}
}
else if(scriptLenFirstByte==67)
{
// Std spend-coinbase TxOut script
static HashString addr20(20);
BtcUtils::getHash160_NoSafetyCheck(ptr+2, 65, addr20);
if( addressIsRegistered(addr20) )
{
HashString txHash = tx.getThisHash();
insertRegisteredTxIfNew(txHash);
registeredOutPoints_.insert(OutPoint(txHash, iout));
}
}
else
{
/* TODO: Right now we will just ignoring non-std tx
I don't do anything with them right now, anyway
TxOutRef txout = tx.getTxOutRef(iout);
for(uint32_t i=0; i<addrPtrVect_.size(); i++)
{
BtcAddress & thisAddr = *(addrPtrVect_[i]);
HashString const & addr20 = thisAddr.getAddrStr20();
if(txout.getScriptRef().find(thisAddr.getAddrStr20()) > -1)
scanNonStdTx(0, 0, tx, iout, thisAddr);
continue;
}
//break;
*/
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Pass this wallet a TxRef and current time/blknumber. I used to just pass
// in the BlockHeaderRef with it, but this may be a Tx not in a block yet,
// but I still need the time/num
//
// You must clear the zero-conf pool for this address, before you do a
// rescan of the wallet (it's done in rescanWalletZeroConf)
void BtcWallet::scanTx(TxRef & tx,
uint32_t txIndex,
uint32_t txtime,
uint32_t blknum)
{
int64_t totalLedgerAmt = 0;
bool isZeroConf = blknum==UINT32_MAX;
vector<bool> thisTxOutIsOurs(tx.getNumTxOut(), false);
pair<bool,bool> boolPair = isMineBulkFilter(tx);
bool txIsRelevant = boolPair.first;
bool anyTxInIsOurs = boolPair.second;
if( !txIsRelevant )
return;
// We distinguish "any" from "anyNew" because we want to avoid re-adding
// transactions/TxIOPairs that are already part of the our tx list/ledger
// but we do need to determine if this was sent-to-self, regardless of
// whether it was new.
bool anyNewTxInIsOurs = false;
bool anyNewTxOutIsOurs = false;
bool isCoinbaseTx = false;
for(uint32_t i=0; i<addrPtrVect_.size(); i++)
{
BtcAddress & thisAddr = *(addrPtrVect_[i]);
HashString const & addr20 = thisAddr.getAddrStr20();
///// LOOP OVER ALL TXIN IN BLOCK /////
for(uint32_t iin=0; iin<tx.getNumTxIn(); iin++)
{
TxInRef txin = tx.getTxInRef(iin);
OutPoint outpt = txin.getOutPoint();
// Empty hash in Outpoint means it's a COINBASE tx --> no addr inputs
if(outpt.getTxHashRef() == BtcUtils::EmptyHash_)
{
isCoinbaseTx = true;
continue;
}
// We have the txin, now check if it contains one of our TxOuts
map<OutPoint, TxIOPair>::iterator txioIter = txioMap_.find(outpt);
bool txioWasInMapAlready = (txioIter != txioMap_.end());
if(txioWasInMapAlready)
{
// If we are here, we know that this input is spending an
// output owned by this wallet (though this address may not
// be the one affected)
// We need to make sure the ledger entry makes sense, and make
// sure we update TxIO objects appropriately
TxIOPair & txio = txioIter->second;
TxOutRef const & txout = txio.getTxOutRef();
// Skip if this TxIO is not for this address
if(!(txout.getRecipientAddr()==thisAddr.getAddrStr20()))
continue;
int64_t thisVal = (int64_t)txout.getValue();
totalLedgerAmt -= thisVal;
// Skip, if this is a zero-conf-spend, but it's already got a zero-conf
if( isZeroConf && txio.hasTxInZC() )
return; // this tx can't be valid, might as well bail now
if( !txio.hasTxInInMain() && !(isZeroConf && txio.hasTxInZC()) )
{
// isValidNew only identifies whether this set-call succeeded
// If it didn't, it's because this is from a zero-conf tx but this
// TxIn already exists in the blockchain spending the same output.
// (i.e. we have a ref to the prev output, but it's been spent!)
bool isValidNew = txio.setTxInRef(&tx, iin, isZeroConf);
if(!isValidNew)
continue;
anyNewTxInIsOurs = true;
LedgerEntry newEntry(addr20,
-(int64_t)thisVal,
blknum,
tx.getThisHash(),
iin,
txtime,
false, // SentToSelf is meaningless for addr ledger
false); // "isChangeBack" is meaningless for TxIn
thisAddr.addLedgerEntry(newEntry, isZeroConf);
// Update last seen on the network
thisAddr.setLastTimestamp(txtime);
thisAddr.setLastBlockNum(blknum);
}
}
else
{
// Lots of txins that we won't have, this is a normal conditional
// But we should check the non-std txio list since it may actually
// be there
if(nonStdTxioMap_.find(outpt) != nonStdTxioMap_.end())
{
nonStdTxioMap_[outpt].setTxInRef(&tx, iin, isZeroConf);
nonStdUnspentOutPoints_.erase(outpt);
}
}
} // loop over TxIns
///// LOOP OVER ALL TXOUT IN TX /////
for(uint32_t iout=0; iout<tx.getNumTxOut(); iout++)
{
TxOutRef txout = tx.getTxOutRef(iout);
if( txout.getScriptType() == TXOUT_SCRIPT_UNKNOWN )
{
if(txout.getScriptRef().find(thisAddr.getAddrStr20()) > -1)
scanNonStdTx(blknum, txIndex, tx, iout, thisAddr);
continue;
}
if( txout.getRecipientAddr() == thisAddr.getAddrStr20() )
{
// If we got here, at least this TxOut is for this address.
// But we still need to find out if it's new and update
// ledgers/TXIOs appropriately
// TODO: Verify this logic is correct: totalLedgerAmt will
// be used in the wallet-level ledgerEntry. There are
// a variety of conditions under which we skip processing
// the addr-level LE, but we probably still need to keep
// an accurate totalLedgerAmt for this tx as a whole
int64_t thisVal = (int64_t)(txout.getValue());
totalLedgerAmt += thisVal;
OutPoint outpt(tx.getThisHash(), iout);
map<OutPoint, TxIOPair>::iterator txioIter = txioMap_.find(outpt);
bool txioWasInMapAlready = (txioIter != txioMap_.end());
bool doAddLedgerEntry = false;
if(txioWasInMapAlready)
{
if(isZeroConf)
{
// This is a real txOut, in the blockchain
if(txioIter->second.hasTxOutZC() || txioIter->second.hasTxOutInMain())
continue;
// If we got here, somehow the Txio existed already, but
// there was no existing TxOut referenced by it. Probably,
// there was, but that TxOut was invalidated due to reorg
// and now being re-added
txioIter->second.setTxOutRef(&tx, iout, isZeroConf);
thisAddr.addTxIO( txioIter->second, isZeroConf);
doAddLedgerEntry = true;
}
else
{
if(txioIter->second.hasTxOutInMain()) // ...but we already have one
continue;
// If we got here, we have a in-blockchain TxOut that is
// replacing a zero-conf txOut. Reset the txio to have
// only this real TxOut, blank ZC TxOut. And the addr
// relevantTxIOPtrs_ does not have this yet so it needs
// to be added (it's already part of the relevantTxIOPtrsZC_
// but that will be removed)
txioIter->second.setTxOutRef(&tx, iout, isZeroConf);
thisAddr.addTxIO( txioIter->second, isZeroConf);
doAddLedgerEntry = true;
}
}
else
{
// TxIO is not in the map yet -- create and add it
TxIOPair newTxio;
newTxio.setTxOutRef(&tx, iout, isZeroConf);
pair<OutPoint, TxIOPair> toBeInserted(outpt, newTxio);
txioIter = txioMap_.insert(toBeInserted).first;
thisAddr.addTxIO( txioIter->second, isZeroConf);
doAddLedgerEntry = true;
}
if(anyTxInIsOurs)
txioIter->second.setTxOutFromSelf();
if(isCoinbaseTx)
txioIter->second.setFromCoinbase();
anyNewTxOutIsOurs = true;
thisTxOutIsOurs[iout] = true;
if(doAddLedgerEntry)
{
LedgerEntry newLedger(addr20,
thisVal,
blknum,
tx.getThisHash(),
iout,
txtime,
false, // sentToSelf meaningless for addr ledger
false); // we don't actually know