forked from trezor/blockbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrocksdb.go
2325 lines (2180 loc) · 66.2 KB
/
rocksdb.go
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
package db
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"math/big"
"os"
"path/filepath"
"sort"
"strconv"
"sync"
"time"
"unsafe"
vlq "github.com/bsm/go-vlq"
"github.com/golang/glog"
"github.com/juju/errors"
"github.com/linxGnu/grocksdb"
"github.com/trezor/blockbook/bchain"
"github.com/trezor/blockbook/common"
)
const dbVersion = 6
const packedHeightBytes = 4
const maxAddrDescLen = 1024
// iterator creates snapshot, which takes lots of resources
// when doing huge scan, it is better to close it and reopen from time to time to free the resources
const refreshIterator = 5000000
// RepairRocksDB calls RocksDb db repair function
func RepairRocksDB(name string) error {
glog.Infof("rocksdb: repair")
opts := grocksdb.NewDefaultOptions()
return grocksdb.RepairDb(name, opts)
}
type connectBlockStats struct {
txAddressesHit int
txAddressesMiss int
balancesHit int
balancesMiss int
}
// AddressBalanceDetail specifies what data are returned by GetAddressBalance
type AddressBalanceDetail int
const (
// AddressBalanceDetailNoUTXO returns address balance without utxos
AddressBalanceDetailNoUTXO = 0
// AddressBalanceDetailUTXO returns address balance with utxos
AddressBalanceDetailUTXO = 1
// addressBalanceDetailUTXOIndexed returns address balance with utxos and index for updates, used only internally
addressBalanceDetailUTXOIndexed = 2
)
// RocksDB handle
type RocksDB struct {
path string
db *grocksdb.DB
wo *grocksdb.WriteOptions
ro *grocksdb.ReadOptions
cfh []*grocksdb.ColumnFamilyHandle
chainParser bchain.BlockChainParser
is *common.InternalState
metrics *common.Metrics
cache *grocksdb.Cache
maxOpenFiles int
cbs connectBlockStats
extendedIndex bool
}
const (
cfDefault = iota
cfHeight
cfAddresses
cfBlockTxs
cfTransactions
cfFiatRates
// BitcoinType
cfAddressBalance
cfTxAddresses
__break__
// EthereumType
cfAddressContracts = iota - __break__ + cfAddressBalance - 1
cfInternalData
cfContracts
cfFunctionSignatures
cfBlockInternalDataErrors
// TODO move to common section
cfAddressAliases
)
// common columns
var cfNames []string
var cfBaseNames = []string{"default", "height", "addresses", "blockTxs", "transactions", "fiatRates"}
// type specific columns
var cfNamesBitcoinType = []string{"addressBalance", "txAddresses"}
var cfNamesEthereumType = []string{"addressContracts", "internalData", "contracts", "functionSignatures", "blockInternalDataErrors", "addressAliases"}
func openDB(path string, c *grocksdb.Cache, openFiles int) (*grocksdb.DB, []*grocksdb.ColumnFamilyHandle, error) {
// opts with bloom filter
opts := createAndSetDBOptions(10, c, openFiles)
// opts for addresses without bloom filter
// from documentation: if most of your queries are executed using iterators, you shouldn't set bloom filter
optsAddresses := createAndSetDBOptions(0, c, openFiles)
// default, height, addresses, blockTxids, transactions
cfOptions := []*grocksdb.Options{opts, opts, optsAddresses, opts, opts, opts}
// append type specific options
count := len(cfNames) - len(cfOptions)
for i := 0; i < count; i++ {
cfOptions = append(cfOptions, opts)
}
db, cfh, err := grocksdb.OpenDbColumnFamilies(opts, path, cfNames, cfOptions)
if err != nil {
return nil, nil, err
}
return db, cfh, nil
}
// NewRocksDB opens an internal handle to RocksDB environment. Close
// needs to be called to release it.
func NewRocksDB(path string, cacheSize, maxOpenFiles int, parser bchain.BlockChainParser, metrics *common.Metrics, extendedIndex bool) (d *RocksDB, err error) {
glog.Infof("rocksdb: opening %s, required data version %v, cache size %v, max open files %v", path, dbVersion, cacheSize, maxOpenFiles)
cfNames = append([]string{}, cfBaseNames...)
chainType := parser.GetChainType()
if chainType == bchain.ChainBitcoinType {
cfNames = append(cfNames, cfNamesBitcoinType...)
} else if chainType == bchain.ChainEthereumType {
cfNames = append(cfNames, cfNamesEthereumType...)
extendedIndex = false
} else {
return nil, errors.New("Unknown chain type")
}
c := grocksdb.NewLRUCache(uint64(cacheSize))
db, cfh, err := openDB(path, c, maxOpenFiles)
if err != nil {
return nil, err
}
wo := grocksdb.NewDefaultWriteOptions()
ro := grocksdb.NewDefaultReadOptions()
return &RocksDB{path, db, wo, ro, cfh, parser, nil, metrics, c, maxOpenFiles, connectBlockStats{}, extendedIndex}, nil
}
func (d *RocksDB) closeDB() error {
for _, h := range d.cfh {
h.Destroy()
}
d.db.Close()
d.db = nil
return nil
}
// Close releases the RocksDB environment opened in NewRocksDB.
func (d *RocksDB) Close() error {
if d.db != nil {
// store the internal state of the app
if d.is != nil && d.is.DbState == common.DbStateOpen {
d.is.DbState = common.DbStateClosed
if err := d.StoreInternalState(d.is); err != nil {
glog.Info("internalState: ", err)
}
}
glog.Infof("rocksdb: close")
d.closeDB()
d.wo.Destroy()
d.ro.Destroy()
}
return nil
}
// Reopen reopens the database
// It closes and reopens db, nobody can access the database during the operation!
func (d *RocksDB) Reopen() error {
err := d.closeDB()
if err != nil {
return err
}
d.db = nil
db, cfh, err := openDB(d.path, d.cache, d.maxOpenFiles)
if err != nil {
return err
}
d.db, d.cfh = db, cfh
return nil
}
func atoUint64(s string) uint64 {
i, err := strconv.Atoi(s)
if err != nil {
return 0
}
return uint64(i)
}
func (d *RocksDB) WriteBatch(wb *grocksdb.WriteBatch) error {
return d.db.Write(d.wo, wb)
}
// HasExtendedIndex returns true if the DB indexes input txids and spending data
func (d *RocksDB) HasExtendedIndex() bool {
return d.extendedIndex
}
// GetMemoryStats returns memory usage statistics as reported by RocksDB
func (d *RocksDB) GetMemoryStats() string {
var total, indexAndFilter, memtable uint64
type columnStats struct {
name string
indexAndFilter string
memtable string
}
cs := make([]columnStats, len(cfNames))
for i := 0; i < len(cfNames); i++ {
cs[i].name = cfNames[i]
cs[i].indexAndFilter = d.db.GetPropertyCF("rocksdb.estimate-table-readers-mem", d.cfh[i])
cs[i].memtable = d.db.GetPropertyCF("rocksdb.cur-size-all-mem-tables", d.cfh[i])
indexAndFilter += atoUint64(cs[i].indexAndFilter)
memtable += atoUint64(cs[i].memtable)
}
m := struct {
cacheUsage uint64
pinnedCacheUsage uint64
columns []columnStats
}{
cacheUsage: d.cache.GetUsage(),
pinnedCacheUsage: d.cache.GetPinnedUsage(),
columns: cs,
}
total = m.cacheUsage + indexAndFilter + memtable
return fmt.Sprintf("Total %d, indexAndFilter %d, memtable %d, %+v", total, indexAndFilter, memtable, m)
}
// StopIteration is returned by callback function to signal stop of iteration
type StopIteration struct{}
func (e *StopIteration) Error() string {
return ""
}
// GetTransactionsCallback is called by GetTransactions/GetAddrDescTransactions for each found tx
// indexes contain array of indexes (input negative, output positive) in tx where is given address
type GetTransactionsCallback func(txid string, height uint32, indexes []int32) error
// GetTransactions finds all input/output transactions for address
// Transaction are passed to callback function.
func (d *RocksDB) GetTransactions(address string, lower uint32, higher uint32, fn GetTransactionsCallback) (err error) {
if glog.V(1) {
glog.Infof("rocksdb: address get %s %d-%d ", address, lower, higher)
}
addrDesc, err := d.chainParser.GetAddrDescFromAddress(address)
if err != nil {
return err
}
return d.GetAddrDescTransactions(addrDesc, lower, higher, fn)
}
// GetAddrDescTransactions finds all input/output transactions for address descriptor
// Transaction are passed to callback function in the order from newest block to the oldest
func (d *RocksDB) GetAddrDescTransactions(addrDesc bchain.AddressDescriptor, lower uint32, higher uint32, fn GetTransactionsCallback) (err error) {
txidUnpackedLen := d.chainParser.PackedTxidLen()
addrDescLen := len(addrDesc)
startKey := packAddressKey(addrDesc, higher)
stopKey := packAddressKey(addrDesc, lower)
indexes := make([]int32, 0, 16)
it := d.db.NewIteratorCF(d.ro, d.cfh[cfAddresses])
defer it.Close()
for it.Seek(startKey); it.Valid(); it.Next() {
key := it.Key().Data()
if bytes.Compare(key, stopKey) > 0 {
break
}
if len(key) != addrDescLen+packedHeightBytes {
if glog.V(2) {
glog.Warningf("rocksdb: addrDesc %s - mixed with %s", addrDesc, hex.EncodeToString(key))
}
continue
}
val := it.Value().Data()
if glog.V(2) {
glog.Infof("rocksdb: addresses %s: %s", hex.EncodeToString(key), hex.EncodeToString(val))
}
_, height, err := unpackAddressKey(key)
if err != nil {
return err
}
for len(val) > txidUnpackedLen {
tx, err := d.chainParser.UnpackTxid(val[:txidUnpackedLen])
if err != nil {
return err
}
indexes = indexes[:0]
val = val[txidUnpackedLen:]
for {
index, l := unpackVarint32(val)
indexes = append(indexes, index>>1)
val = val[l:]
if index&1 == 1 {
break
} else if len(val) == 0 {
glog.Warningf("rocksdb: addresses contain incorrect data %s: %s", hex.EncodeToString(key), hex.EncodeToString(val))
break
}
}
if err := fn(tx, height, indexes); err != nil {
if _, ok := err.(*StopIteration); ok {
return nil
}
return err
}
}
if len(val) != 0 {
glog.Warningf("rocksdb: addresses contain incorrect data %s: %s", hex.EncodeToString(key), hex.EncodeToString(val))
}
}
return nil
}
const (
opInsert = 0
opDelete = 1
)
// ConnectBlock indexes addresses in the block and stores them in db
func (d *RocksDB) ConnectBlock(block *bchain.Block) error {
wb := grocksdb.NewWriteBatch()
defer wb.Destroy()
if glog.V(2) {
glog.Infof("rocksdb: insert %d %s", block.Height, block.Hash)
}
chainType := d.chainParser.GetChainType()
if err := d.writeHeightFromBlock(wb, block, opInsert); err != nil {
return err
}
addresses := make(addressesMap)
if chainType == bchain.ChainBitcoinType {
txAddressesMap := make(map[string]*TxAddresses)
balances := make(map[string]*AddrBalance)
if err := d.processAddressesBitcoinType(block, addresses, txAddressesMap, balances); err != nil {
return err
}
if err := d.storeTxAddresses(wb, txAddressesMap); err != nil {
return err
}
if err := d.storeBalances(wb, balances); err != nil {
return err
}
if err := d.storeAndCleanupBlockTxs(wb, block); err != nil {
return err
}
} else if chainType == bchain.ChainEthereumType {
addressContracts := make(map[string]*AddrContracts)
blockTxs, err := d.processAddressesEthereumType(block, addresses, addressContracts)
if err != nil {
return err
}
if err := d.storeAddressContracts(wb, addressContracts); err != nil {
return err
}
if err := d.storeInternalDataEthereumType(wb, blockTxs); err != nil {
return err
}
if err = d.storeBlockSpecificDataEthereumType(wb, block); err != nil {
return err
}
if err := d.storeAndCleanupBlockTxsEthereumType(wb, block, blockTxs); err != nil {
return err
}
} else {
return errors.New("Unknown chain type")
}
if err := d.storeAddresses(wb, block.Height, addresses); err != nil {
return err
}
if err := d.WriteBatch(wb); err != nil {
return err
}
avg := d.is.AppendBlockTime(uint32(block.Time))
if d.metrics != nil {
d.metrics.AvgBlockPeriod.Set(float64(avg))
}
return nil
}
// Addresses index
type txIndexes struct {
btxID []byte
indexes []int32
}
// addressesMap is a map of addresses in a block
// each address contains a slice of transactions with indexes where the address appears
// slice is used instead of map so that order is defined and also search in case of few items
type addressesMap map[string][]txIndexes
type outpoint struct {
btxID []byte
index int32
}
// TxInput holds input data of the transaction in TxAddresses
type TxInput struct {
AddrDesc bchain.AddressDescriptor
ValueSat big.Int
// extended index properties
Txid string
Vout uint32
}
// Addresses converts AddressDescriptor of the input to array of strings
func (ti *TxInput) Addresses(p bchain.BlockChainParser) ([]string, bool, error) {
return p.GetAddressesFromAddrDesc(ti.AddrDesc)
}
// TxOutput holds output data of the transaction in TxAddresses
type TxOutput struct {
AddrDesc bchain.AddressDescriptor
Spent bool
ValueSat big.Int
// extended index properties
SpentTxid string
SpentIndex uint32
SpentHeight uint32
}
// Addresses converts AddressDescriptor of the output to array of strings
func (to *TxOutput) Addresses(p bchain.BlockChainParser) ([]string, bool, error) {
return p.GetAddressesFromAddrDesc(to.AddrDesc)
}
// TxAddresses stores transaction inputs and outputs with amounts
type TxAddresses struct {
Height uint32
Inputs []TxInput
Outputs []TxOutput
// extended index properties
VSize uint32
}
// Utxo holds information about unspent transaction output
type Utxo struct {
BtxID []byte
Vout int32
Height uint32
ValueSat big.Int
}
// AddrBalance stores number of transactions and balances of an address
type AddrBalance struct {
Txs uint32
SentSat big.Int
BalanceSat big.Int
Utxos []Utxo
utxosMap map[string]int
}
// ReceivedSat computes received amount from total balance and sent amount
func (ab *AddrBalance) ReceivedSat() *big.Int {
var r big.Int
r.Add(&ab.BalanceSat, &ab.SentSat)
return &r
}
// addUtxo
func (ab *AddrBalance) addUtxo(u *Utxo) {
ab.Utxos = append(ab.Utxos, *u)
ab.manageUtxoMap(u)
}
func (ab *AddrBalance) manageUtxoMap(u *Utxo) {
l := len(ab.Utxos)
if l >= 16 {
if len(ab.utxosMap) == 0 {
ab.utxosMap = make(map[string]int, 32)
for i := 0; i < l; i++ {
s := string(ab.Utxos[i].BtxID)
if _, e := ab.utxosMap[s]; !e {
ab.utxosMap[s] = i
}
}
} else {
s := string(u.BtxID)
if _, e := ab.utxosMap[s]; !e {
ab.utxosMap[s] = l - 1
}
}
}
}
// on disconnect, the added utxos must be inserted in the right position so that utxosMap index works
func (ab *AddrBalance) addUtxoInDisconnect(u *Utxo) {
insert := -1
if len(ab.utxosMap) > 0 {
if i, e := ab.utxosMap[string(u.BtxID)]; e {
insert = i
}
} else {
for i := range ab.Utxos {
utxo := &ab.Utxos[i]
if *(*int)(unsafe.Pointer(&utxo.BtxID[0])) == *(*int)(unsafe.Pointer(&u.BtxID[0])) && bytes.Equal(utxo.BtxID, u.BtxID) {
insert = i
break
}
}
}
if insert > -1 {
// check if it is necessary to insert the utxo into the array
for i := insert; i < len(ab.Utxos); i++ {
utxo := &ab.Utxos[i]
// either the vout is greater than the inserted vout or it is a different tx
if utxo.Vout > u.Vout || *(*int)(unsafe.Pointer(&utxo.BtxID[0])) != *(*int)(unsafe.Pointer(&u.BtxID[0])) || !bytes.Equal(utxo.BtxID, u.BtxID) {
// found the right place, insert the utxo
ab.Utxos = append(ab.Utxos, *u)
copy(ab.Utxos[i+1:], ab.Utxos[i:])
ab.Utxos[i] = *u
// reset utxosMap after insert, the index will have to be rebuilt if needed
ab.utxosMap = nil
return
}
}
}
ab.Utxos = append(ab.Utxos, *u)
ab.manageUtxoMap(u)
}
// markUtxoAsSpent finds outpoint btxID:vout in utxos and marks it as spent
// for small number of utxos the linear search is done, for larger number there is a hashmap index
// it is much faster than removing the utxo from the slice as it would cause in memory reallocations
func (ab *AddrBalance) markUtxoAsSpent(btxID []byte, vout int32) {
if len(ab.utxosMap) == 0 {
for i := range ab.Utxos {
utxo := &ab.Utxos[i]
if utxo.Vout == vout && *(*int)(unsafe.Pointer(&utxo.BtxID[0])) == *(*int)(unsafe.Pointer(&btxID[0])) && bytes.Equal(utxo.BtxID, btxID) {
// mark utxo as spent by setting vout=-1
utxo.Vout = -1
return
}
}
} else {
if i, e := ab.utxosMap[string(btxID)]; e {
l := len(ab.Utxos)
for ; i < l; i++ {
utxo := &ab.Utxos[i]
if utxo.Vout == vout {
if bytes.Equal(utxo.BtxID, btxID) {
// mark utxo as spent by setting vout=-1
utxo.Vout = -1
return
}
break
}
}
}
}
glog.Errorf("Utxo %s:%d not found, utxosMap size %d", hex.EncodeToString(btxID), vout, len(ab.utxosMap))
}
type blockTxs struct {
btxID []byte
inputs []outpoint
}
func (d *RocksDB) resetValueSatToZero(valueSat *big.Int, addrDesc bchain.AddressDescriptor, logText string) {
ad, _, err := d.chainParser.GetAddressesFromAddrDesc(addrDesc)
if err != nil {
glog.Warningf("rocksdb: unparsable address hex '%v' reached negative %s %v, resetting to 0. Parser error %v", addrDesc, logText, valueSat.String(), err)
} else {
glog.Warningf("rocksdb: address %v hex '%v' reached negative %s %v, resetting to 0", ad, addrDesc, logText, valueSat.String())
}
valueSat.SetInt64(0)
}
// GetAndResetConnectBlockStats gets statistics about cache usage in connect blocks and resets the counters
func (d *RocksDB) GetAndResetConnectBlockStats() string {
s := fmt.Sprintf("%+v", d.cbs)
d.cbs = connectBlockStats{}
return s
}
func (d *RocksDB) processAddressesBitcoinType(block *bchain.Block, addresses addressesMap, txAddressesMap map[string]*TxAddresses, balances map[string]*AddrBalance) error {
blockTxIDs := make([][]byte, len(block.Txs))
blockTxAddresses := make([]*TxAddresses, len(block.Txs))
// first process all outputs so that inputs can refer to txs in this block
for txi := range block.Txs {
tx := &block.Txs[txi]
btxID, err := d.chainParser.PackTxid(tx.Txid)
if err != nil {
return err
}
blockTxIDs[txi] = btxID
ta := TxAddresses{Height: block.Height}
if d.extendedIndex {
if tx.VSize > 0 {
ta.VSize = uint32(tx.VSize)
} else {
ta.VSize = uint32(len(tx.Hex))
}
}
ta.Outputs = make([]TxOutput, len(tx.Vout))
txAddressesMap[string(btxID)] = &ta
blockTxAddresses[txi] = &ta
for i := range tx.Vout {
output := &tx.Vout[i]
tao := &ta.Outputs[i]
tao.ValueSat = output.ValueSat
addrDesc, err := d.chainParser.GetAddrDescFromVout(output)
if err != nil || len(addrDesc) == 0 || len(addrDesc) > maxAddrDescLen {
if err != nil {
// do not log ErrAddressMissing, transactions can be without to address (for example eth contracts)
if err != bchain.ErrAddressMissing {
glog.Warningf("rocksdb: addrDesc: %v - height %d, tx %v, output %v, error %v", err, block.Height, tx.Txid, output, err)
}
} else {
glog.V(1).Infof("rocksdb: height %d, tx %v, vout %v, skipping addrDesc of length %d", block.Height, tx.Txid, i, len(addrDesc))
}
continue
}
tao.AddrDesc = addrDesc
if d.chainParser.IsAddrDescIndexable(addrDesc) {
strAddrDesc := string(addrDesc)
balance, e := balances[strAddrDesc]
if !e {
balance, err = d.GetAddrDescBalance(addrDesc, addressBalanceDetailUTXOIndexed)
if err != nil {
return err
}
if balance == nil {
balance = &AddrBalance{}
}
balances[strAddrDesc] = balance
d.cbs.balancesMiss++
} else {
d.cbs.balancesHit++
}
balance.BalanceSat.Add(&balance.BalanceSat, &output.ValueSat)
balance.addUtxo(&Utxo{
BtxID: btxID,
Vout: int32(i),
Height: block.Height,
ValueSat: output.ValueSat,
})
counted := addToAddressesMap(addresses, strAddrDesc, btxID, int32(i))
if !counted {
balance.Txs++
}
}
}
}
// process inputs
for txi := range block.Txs {
tx := &block.Txs[txi]
spendingTxid := blockTxIDs[txi]
ta := blockTxAddresses[txi]
ta.Inputs = make([]TxInput, len(tx.Vin))
logged := false
for i := range tx.Vin {
input := &tx.Vin[i]
tai := &ta.Inputs[i]
btxID, err := d.chainParser.PackTxid(input.Txid)
if err != nil {
// do not process inputs without input txid
if err == bchain.ErrTxidMissing {
continue
}
return err
}
stxID := string(btxID)
ita, e := txAddressesMap[stxID]
if !e {
ita, err = d.getTxAddresses(btxID)
if err != nil {
return err
}
if ita == nil {
// allow parser to process unknown input, some coins may implement special handling, default is to log warning
tai.AddrDesc = d.chainParser.GetAddrDescForUnknownInput(tx, i)
continue
}
txAddressesMap[stxID] = ita
d.cbs.txAddressesMiss++
} else {
d.cbs.txAddressesHit++
}
if len(ita.Outputs) <= int(input.Vout) {
glog.Warningf("rocksdb: height %d, tx %v, input tx %v vout %v is out of bounds of stored tx", block.Height, tx.Txid, input.Txid, input.Vout)
continue
}
spentOutput := &ita.Outputs[int(input.Vout)]
if spentOutput.Spent {
glog.Warningf("rocksdb: height %d, tx %v, input tx %v vout %v is double spend", block.Height, tx.Txid, input.Txid, input.Vout)
}
tai.AddrDesc = spentOutput.AddrDesc
tai.ValueSat = spentOutput.ValueSat
// mark the output as spent in tx
spentOutput.Spent = true
if d.extendedIndex {
spentOutput.SpentTxid = tx.Txid
spentOutput.SpentIndex = uint32(i)
spentOutput.SpentHeight = block.Height
tai.Txid = input.Txid
tai.Vout = input.Vout
}
if len(spentOutput.AddrDesc) == 0 {
if !logged {
glog.V(1).Infof("rocksdb: height %d, tx %v, input tx %v vout %v skipping empty address", block.Height, tx.Txid, input.Txid, input.Vout)
logged = true
}
continue
}
if d.chainParser.IsAddrDescIndexable(spentOutput.AddrDesc) {
strAddrDesc := string(spentOutput.AddrDesc)
balance, e := balances[strAddrDesc]
if !e {
balance, err = d.GetAddrDescBalance(spentOutput.AddrDesc, addressBalanceDetailUTXOIndexed)
if err != nil {
return err
}
if balance == nil {
balance = &AddrBalance{}
}
balances[strAddrDesc] = balance
d.cbs.balancesMiss++
} else {
d.cbs.balancesHit++
}
counted := addToAddressesMap(addresses, strAddrDesc, spendingTxid, ^int32(i))
if !counted {
balance.Txs++
}
balance.BalanceSat.Sub(&balance.BalanceSat, &spentOutput.ValueSat)
balance.markUtxoAsSpent(btxID, int32(input.Vout))
if balance.BalanceSat.Sign() < 0 {
d.resetValueSatToZero(&balance.BalanceSat, spentOutput.AddrDesc, "balance")
}
balance.SentSat.Add(&balance.SentSat, &spentOutput.ValueSat)
}
}
}
return nil
}
// addToAddressesMap maintains mapping between addresses and transactions in one block
// the method assumes that outputs in the block are processed before the inputs
// the return value is true if the tx was processed before, to not to count the tx multiple times
func addToAddressesMap(addresses addressesMap, strAddrDesc string, btxID []byte, index int32) bool {
// check that the address was already processed in this block
// if not found, it has certainly not been counted
at, found := addresses[strAddrDesc]
if found {
// if the tx is already in the slice, append the index to the array of indexes
for i, t := range at {
if bytes.Equal(btxID, t.btxID) {
at[i].indexes = append(t.indexes, index)
return true
}
}
}
addresses[strAddrDesc] = append(at, txIndexes{
btxID: btxID,
indexes: []int32{index},
})
return false
}
func (d *RocksDB) getTxIndexesForAddressAndBlock(addrDesc bchain.AddressDescriptor, height uint32) ([]txIndexes, error) {
key := packAddressKey(addrDesc, height)
val, err := d.db.GetCF(d.ro, d.cfh[cfAddresses], key)
if err != nil {
return nil, err
}
defer val.Free()
// nil data means the key was not found in DB
if val.Data() == nil {
return nil, nil
}
rv, err := d.unpackTxIndexes(val.Data())
if err != nil {
return nil, err
}
return rv, nil
}
func (d *RocksDB) storeAddresses(wb *grocksdb.WriteBatch, height uint32, addresses addressesMap) error {
for addrDesc, txi := range addresses {
ba := bchain.AddressDescriptor(addrDesc)
key := packAddressKey(ba, height)
val := d.packTxIndexes(txi)
wb.PutCF(d.cfh[cfAddresses], key, val)
}
return nil
}
func (d *RocksDB) storeTxAddresses(wb *grocksdb.WriteBatch, am map[string]*TxAddresses) error {
varBuf := make([]byte, maxPackedBigintBytes)
buf := make([]byte, 1024)
for txID, ta := range am {
buf = d.packTxAddresses(ta, buf, varBuf)
wb.PutCF(d.cfh[cfTxAddresses], []byte(txID), buf)
}
return nil
}
func (d *RocksDB) storeBalances(wb *grocksdb.WriteBatch, abm map[string]*AddrBalance) error {
// allocate buffer initial buffer
buf := make([]byte, 1024)
varBuf := make([]byte, maxPackedBigintBytes)
for addrDesc, ab := range abm {
// balance with 0 transactions is removed from db - happens on disconnect
if ab == nil || ab.Txs <= 0 {
wb.DeleteCF(d.cfh[cfAddressBalance], bchain.AddressDescriptor(addrDesc))
} else {
buf = packAddrBalance(ab, buf, varBuf)
wb.PutCF(d.cfh[cfAddressBalance], bchain.AddressDescriptor(addrDesc), buf)
}
}
return nil
}
func (d *RocksDB) cleanupBlockTxs(wb *grocksdb.WriteBatch, block *bchain.Block) error {
keep := d.chainParser.KeepBlockAddresses()
// cleanup old block address
if block.Height > uint32(keep) {
for rh := block.Height - uint32(keep); rh > 0; rh-- {
key := packUint(rh)
val, err := d.db.GetCF(d.ro, d.cfh[cfBlockTxs], key)
if err != nil {
return err
}
// nil data means the key was not found in DB
if val.Data() == nil {
break
}
val.Free()
d.db.DeleteCF(d.wo, d.cfh[cfBlockTxs], key)
}
}
return nil
}
func (d *RocksDB) storeAndCleanupBlockTxs(wb *grocksdb.WriteBatch, block *bchain.Block) error {
pl := d.chainParser.PackedTxidLen()
buf := make([]byte, 0, pl*len(block.Txs))
varBuf := make([]byte, vlq.MaxLen64)
zeroTx := make([]byte, pl)
for i := range block.Txs {
tx := &block.Txs[i]
o := make([]outpoint, len(tx.Vin))
for v := range tx.Vin {
vin := &tx.Vin[v]
btxID, err := d.chainParser.PackTxid(vin.Txid)
if err != nil {
// do not process inputs without input txid
if err == bchain.ErrTxidMissing {
btxID = zeroTx
} else {
return err
}
}
o[v].btxID = btxID
o[v].index = int32(vin.Vout)
}
btxID, err := d.chainParser.PackTxid(tx.Txid)
if err != nil {
return err
}
buf = append(buf, btxID...)
l := packVaruint(uint(len(o)), varBuf)
buf = append(buf, varBuf[:l]...)
buf = append(buf, d.packOutpoints(o)...)
}
key := packUint(block.Height)
wb.PutCF(d.cfh[cfBlockTxs], key, buf)
return d.cleanupBlockTxs(wb, block)
}
func (d *RocksDB) getBlockTxs(height uint32) ([]blockTxs, error) {
pl := d.chainParser.PackedTxidLen()
val, err := d.db.GetCF(d.ro, d.cfh[cfBlockTxs], packUint(height))
if err != nil {
return nil, err
}
defer val.Free()
buf := val.Data()
bt := make([]blockTxs, 0, 8)
for i := 0; i < len(buf); {
if len(buf)-i < pl {
glog.Error("rocksdb: Inconsistent data in blockTxs ", hex.EncodeToString(buf))
return nil, errors.New("Inconsistent data in blockTxs")
}
txid := append([]byte(nil), buf[i:i+pl]...)
i += pl
o, ol, err := d.unpackNOutpoints(buf[i:])
if err != nil {
glog.Error("rocksdb: Inconsistent data in blockTxs ", hex.EncodeToString(buf))
return nil, errors.New("Inconsistent data in blockTxs")
}
bt = append(bt, blockTxs{
btxID: txid,
inputs: o,
})
i += ol
}
return bt, nil
}
// GetAddrDescBalance returns AddrBalance for given addrDesc
func (d *RocksDB) GetAddrDescBalance(addrDesc bchain.AddressDescriptor, detail AddressBalanceDetail) (*AddrBalance, error) {
val, err := d.db.GetCF(d.ro, d.cfh[cfAddressBalance], addrDesc)
if err != nil {
return nil, err
}
defer val.Free()
buf := val.Data()
// 3 is minimum length of addrBalance - 1 byte txs, 1 byte sent, 1 byte balance
if len(buf) < 3 {
return nil, nil
}
return unpackAddrBalance(buf, d.chainParser.PackedTxidLen(), detail)
}
// GetAddressBalance returns address balance for an address or nil if address not found
func (d *RocksDB) GetAddressBalance(address string, detail AddressBalanceDetail) (*AddrBalance, error) {
addrDesc, err := d.chainParser.GetAddrDescFromAddress(address)
if err != nil {
return nil, err
}
return d.GetAddrDescBalance(addrDesc, detail)
}
func (d *RocksDB) getTxAddresses(btxID []byte) (*TxAddresses, error) {
val, err := d.db.GetCF(d.ro, d.cfh[cfTxAddresses], btxID)
if err != nil {
return nil, err
}
defer val.Free()
buf := val.Data()
// 2 is minimum length of addrBalance - 1 byte height, 1 byte inputs len, 1 byte outputs len
if len(buf) < 3 {
return nil, nil
}
return d.unpackTxAddresses(buf)
}
// GetTxAddresses returns TxAddresses for given txid or nil if not found
func (d *RocksDB) GetTxAddresses(txid string) (*TxAddresses, error) {
btxID, err := d.chainParser.PackTxid(txid)
if err != nil {
return nil, err
}
return d.getTxAddresses(btxID)
}
// AddrDescForOutpoint is a function that returns address descriptor and value for given outpoint or nil if outpoint not found
func (d *RocksDB) AddrDescForOutpoint(outpoint bchain.Outpoint) (bchain.AddressDescriptor, *big.Int) {
ta, err := d.GetTxAddresses(outpoint.Txid)
if err != nil || ta == nil {
return nil, nil
}
if outpoint.Vout < 0 {
vin := ^outpoint.Vout
if len(ta.Inputs) <= int(vin) {
return nil, nil
}
return ta.Inputs[vin].AddrDesc, &ta.Inputs[vin].ValueSat
}
if len(ta.Outputs) <= int(outpoint.Vout) {
return nil, nil
}
return ta.Outputs[outpoint.Vout].AddrDesc, &ta.Outputs[outpoint.Vout].ValueSat
}
func (d *RocksDB) packTxAddresses(ta *TxAddresses, buf []byte, varBuf []byte) []byte {
buf = buf[:0]
l := packVaruint(uint(ta.Height), varBuf)
buf = append(buf, varBuf[:l]...)
if d.extendedIndex {
l = packVaruint(uint(ta.VSize), varBuf)
buf = append(buf, varBuf[:l]...)
}
l = packVaruint(uint(len(ta.Inputs)), varBuf)
buf = append(buf, varBuf[:l]...)
for i := range ta.Inputs {
buf = d.appendTxInput(&ta.Inputs[i], buf, varBuf)
}
l = packVaruint(uint(len(ta.Outputs)), varBuf)
buf = append(buf, varBuf[:l]...)
for i := range ta.Outputs {