forked from decred/dcrdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgblockchain.go
1784 lines (1583 loc) · 56.6 KB
/
pgblockchain.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
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package dcrpg
import (
"bytes"
"database/sql"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"time"
"github.com/chappjc/trylock"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/rpcclient"
"github.com/decred/dcrd/wire"
apitypes "github.com/decred/dcrdata/api/types"
"github.com/decred/dcrdata/blockdata"
"github.com/decred/dcrdata/db/dbtypes"
"github.com/decred/dcrdata/explorer"
"github.com/decred/dcrdata/stakedb"
humanize "github.com/dustin/go-humanize"
)
var (
zeroHash = chainhash.Hash{}
zeroHashStringBytes = []byte(chainhash.Hash{}.String())
)
// DevFundBalance is a block-stamped wrapper for explorer.AddressBalance. It is
// intended to be used for the project address.
type DevFundBalance struct {
sync.RWMutex
*explorer.AddressBalance
updating trylock.Mutex
Height int64
Hash chainhash.Hash
}
// BlockHash is a thread-safe accessor for the block hash.
func (d *DevFundBalance) BlockHash() chainhash.Hash {
d.RLock()
defer d.RUnlock()
return d.Hash
}
// BlockHeight is a thread-safe accessor for the block height.
func (d *DevFundBalance) BlockHeight() int64 {
d.RLock()
defer d.RUnlock()
return d.Height
}
// Balance is a thread-safe accessor for the explorer.AddressBalance.
func (d *DevFundBalance) Balance() *explorer.AddressBalance {
d.RLock()
defer d.RUnlock()
return d.AddressBalance
}
// ChainDB provides an interface for storing and manipulating extracted
// blockchain data in a PostgreSQL database.
type ChainDB struct {
db *sql.DB
chainParams *chaincfg.Params
devAddress string
dupChecks bool
bestBlock int64
lastBlock map[chainhash.Hash]uint64
addressCounts *addressCounter
stakeDB *stakedb.StakeDatabase
unspentTicketCache *TicketTxnIDGetter
DevFundBalance *DevFundBalance
devPrefetch bool
InBatchSync bool
}
// ChainDBRPC provides an interface for storing and manipulating extracted and
// includes the RPC Client blockchain data in a PostgreSQL database.
type ChainDBRPC struct {
ChainDB *ChainDB
Client *rpcclient.Client
}
// NewChainDBRPC contains ChainDB and RPC client parameters. By default,
// duplicate row checks on insertion are enabled. also enables rpc client
func NewChainDBRPC(chaindb *ChainDB, cl *rpcclient.Client) (*ChainDBRPC, error) {
return &ChainDBRPC{chaindb, cl}, nil
}
// addressCounter provides a cache for address balances.
type addressCounter struct {
sync.RWMutex
validHeight int64
balance map[string]explorer.AddressBalance
}
func makeAddressCounter() *addressCounter {
return &addressCounter{
validHeight: 0,
balance: make(map[string]explorer.AddressBalance),
}
}
// TicketTxnIDGetter provides a cache for DB row IDs of tickets.
type TicketTxnIDGetter struct {
sync.RWMutex
idCache map[string]uint64
db *sql.DB
}
// TxnDbID fetches DB row ID for the ticket specified by the input transaction
// hash. A cache is checked first. In the event of a cache hit, the DB ID is
// returned and deleted from the internal cache. In the event of a cache miss,
// the database is queried. If the database query fails, the error is non-nil.
func (t *TicketTxnIDGetter) TxnDbID(txid string, expire bool) (uint64, error) {
if t == nil {
panic("You're using an uninitialized TicketTxnIDGetter")
}
t.RLock()
dbID, ok := t.idCache[txid]
t.RUnlock()
if ok {
if expire {
t.Lock()
delete(t.idCache, txid)
t.Unlock()
}
return dbID, nil
}
return RetrieveTicketIDByHash(t.db, txid)
}
// Set stores the (transaction hash, DB row ID) pair a map for future access.
func (t *TicketTxnIDGetter) Set(txid string, txDbID uint64) {
if t == nil {
return
}
t.Lock()
defer t.Unlock()
t.idCache[txid] = txDbID
}
// SetN stores several (transaction hash, DB row ID) pairs in the map.
func (t *TicketTxnIDGetter) SetN(txid []string, txDbID []uint64) {
if t == nil {
return
}
t.Lock()
defer t.Unlock()
for i := range txid {
t.idCache[txid[i]] = txDbID[i]
}
}
// NewTicketTxnIDGetter constructs a new TicketTxnIDGetter with an empty cache.
func NewTicketTxnIDGetter(db *sql.DB) *TicketTxnIDGetter {
return &TicketTxnIDGetter{
db: db,
idCache: make(map[string]uint64),
}
}
// DBInfo holds the PostgreSQL database connection information.
type DBInfo struct {
Host, Port, User, Pass, DBName string
}
// NewChainDB constructs a ChainDB for the given connection and Decred network
// parameters. By default, duplicate row checks on insertion are enabled.
func NewChainDB(dbi *DBInfo, params *chaincfg.Params, stakeDB *stakedb.StakeDatabase,
devPrefetch bool) (*ChainDB, error) {
// Connect to the PostgreSQL daemon and return the *sql.DB
db, err := Connect(dbi.Host, dbi.Port, dbi.User, dbi.Pass, dbi.DBName)
if err != nil {
return nil, err
}
// Attempt to get DB best block height from tables, but if the tables are
// empty or not yet created, it is not an error.
bestHeight, _, _, err := RetrieveBestBlockHeight(db)
if err != nil && !(err == sql.ErrNoRows ||
strings.HasSuffix(err.Error(), "does not exist")) {
return nil, err
}
// Development subsidy address of the current network
var devSubsidyAddress string
if devSubsidyAddress, err = dbtypes.DevSubsidyAddress(params); err != nil {
log.Warnf("ChainDB.NewChainDB: %v", err)
}
if err = setupTables(db); err != nil {
log.Warnf("ATTENTION! %v", err)
// TODO: Actually handle the upgrades/reindexing somewhere.
return nil, err
}
log.Infof("Pre-loading unspent ticket info for InsertVote optimization.")
unspentTicketCache := NewTicketTxnIDGetter(db)
unspentTicketDbIDs, unspentTicketHashes, err := RetrieveUnspentTickets(db)
if err != nil && err != sql.ErrNoRows && !strings.HasSuffix(err.Error(), "does not exist") {
return nil, err
}
if len(unspentTicketDbIDs) != 0 {
log.Infof("Storing data for %d unspent tickets in cache.", len(unspentTicketDbIDs))
unspentTicketCache.SetN(unspentTicketHashes, unspentTicketDbIDs)
}
return &ChainDB{
db: db,
chainParams: params,
devAddress: devSubsidyAddress,
dupChecks: true,
bestBlock: int64(bestHeight),
lastBlock: make(map[chainhash.Hash]uint64),
addressCounts: makeAddressCounter(),
stakeDB: stakeDB,
unspentTicketCache: unspentTicketCache,
DevFundBalance: new(DevFundBalance),
devPrefetch: devPrefetch,
}, nil
}
// Close closes the underlying sql.DB connection to the database.
func (pgb *ChainDB) Close() error {
return pgb.db.Close()
}
// UseStakeDB is used to assign a stakedb.StakeDatabase for ticket tracking.
// This may be useful when it is necessary to construct a ChainDB prior to
// creating or loading a StakeDatabase, such as when dropping tables.
func (pgb *ChainDB) UseStakeDB(stakeDB *stakedb.StakeDatabase) {
pgb.stakeDB = stakeDB
}
// EnableDuplicateCheckOnInsert specifies whether SQL insertions should check
// for row conflicts (duplicates), and avoid adding or updating.
func (pgb *ChainDB) EnableDuplicateCheckOnInsert(dupCheck bool) {
pgb.dupChecks = dupCheck
}
// SetupTables creates the required tables and type, and prints table versions
// stored in the table comments when debug level logging is enabled.
func (pgb *ChainDB) SetupTables() error {
return setupTables(pgb.db)
}
func setupTables(db *sql.DB) error {
if err := CreateTypes(db); err != nil {
return err
}
return CreateTables(db)
}
// VersionCheck checks the current version of all known tables and notifies when
// an upgrade is required. Since there is presently no automatic upgrade, an
// error is returned when any table is not of the correct version.
func (pgb *ChainDB) VersionCheck() error {
vers := TableVersions(pgb.db)
for tab, ver := range vers {
log.Debugf("Table %s: v%s", tab, ver)
}
if tableUpgrades := TableUpgradesRequired(vers); len(tableUpgrades) > 0 {
for _, u := range tableUpgrades {
log.Warnf(u.String())
}
return fmt.Errorf("table maintenance required")
}
return nil
}
// DropTables drops (deletes) all of the known dcrdata tables.
func (pgb *ChainDB) DropTables() {
DropTables(pgb.db)
}
// HeightDB queries the DB for the best block height.
func (pgb *ChainDB) HeightDB() (uint64, error) {
bestHeight, _, _, err := RetrieveBestBlockHeight(pgb.db)
return bestHeight, err
}
// HashDB queries the DB for the best block's hash.
func (pgb *ChainDB) HashDB() (string, error) {
_, bestHash, _, err := RetrieveBestBlockHeight(pgb.db)
return bestHash, err
}
// Height uses the last stored height.
func (pgb *ChainDB) Height() uint64 {
return uint64(pgb.bestBlock)
}
// VotesInBlock returns the number of votes mined in the block with the
// specified hash.
func (pgb *ChainDB) VotesInBlock(hash string) (int16, error) {
voters, err := RetrieveBlockVoteCount(pgb.db, hash)
if err != nil {
log.Errorf("Unable to get block voter count for hash %s: %v", hash, err)
return -1, err
}
return voters, nil
}
// SpendingTransactions retrieves all transactions spending outpoints from the
// specified funding transaction. The spending transaction hashes, the spending
// tx input indexes, and the corresponding funding tx output indexes, and an
// error value are returned.
func (pgb *ChainDB) SpendingTransactions(fundingTxID string) ([]string, []uint32, []uint32, error) {
_, spendingTxns, vinInds, voutInds, err := RetrieveSpendingTxsByFundingTx(pgb.db, fundingTxID)
return spendingTxns, vinInds, voutInds, err
}
// SpendingTransaction returns the transaction that spends the specified
// transaction outpoint, if it is spent. The spending transaction hash, input
// index, tx tree, and an error value are returned.
func (pgb *ChainDB) SpendingTransaction(fundingTxID string,
fundingTxVout uint32) (string, uint32, int8, error) {
_, spendingTx, vinInd, tree, err := RetrieveSpendingTxByTxOut(pgb.db, fundingTxID, fundingTxVout)
return spendingTx, vinInd, tree, err
}
// BlockTransactions retrieves all transactions in the specified block, their
// indexes in the block, their tree, and an error value.
func (pgb *ChainDB) BlockTransactions(blockHash string) ([]string, []uint32, []int8, error) {
_, blockTransactions, blockInds, trees, err := RetrieveTxsByBlockHash(pgb.db, blockHash)
return blockTransactions, blockInds, trees, err
}
// BlockMissedVotes retrieves the ticket IDs for all missed votes in the
// specified block, and an error value.
func (pgb *ChainDB) BlockMissedVotes(blockHash string) ([]string, error) {
return RetrieveMissedVotesInBlock(pgb.db, blockHash)
}
// PoolStatusForTicket retrieves the specified ticket's spend status and ticket
// pool status, and an error value.
func (pgb *ChainDB) PoolStatusForTicket(txid string) (dbtypes.TicketSpendType, dbtypes.TicketPoolStatus, error) {
_, spendType, poolStatus, err := RetrieveTicketStatusByHash(pgb.db, txid)
return spendType, poolStatus, err
}
// VoutValue retrieves the value of the specified transaction outpoint in atoms.
func (pgb *ChainDB) VoutValue(txID string, vout uint32) (uint64, error) {
// txDbID, _, _, err := RetrieveTxByHash(pgb.db, txID)
// if err != nil {
// return 0, fmt.Errorf("RetrieveTxByHash: %v", err)
// }
voutValue, err := RetrieveVoutValue(pgb.db, txID, vout)
if err != nil {
return 0, fmt.Errorf("RetrieveVoutValue: %v", err)
}
return voutValue, nil
}
// VoutValues retrieves the values of each outpoint of the specified
// transaction. The corresponding indexes in the block and tx trees of the
// outpoints, and an error value are also returned.
func (pgb *ChainDB) VoutValues(txID string) ([]uint64, []uint32, []int8, error) {
// txDbID, _, _, err := RetrieveTxByHash(pgb.db, txID)
// if err != nil {
// return nil, fmt.Errorf("RetrieveTxByHash: %v", err)
// }
voutValues, txInds, txTrees, err := RetrieveVoutValues(pgb.db, txID)
if err != nil {
return nil, nil, nil, fmt.Errorf("RetrieveVoutValues: %v", err)
}
return voutValues, txInds, txTrees, nil
}
// TransactionBlock retrieves the hash of the block containing the specified
// transaction. The index of the transaction within the block, the transaction
// index, and an error value are also returned.
func (pgb *ChainDB) TransactionBlock(txID string) (string, uint32, int8, error) {
_, blockHash, blockInd, tree, err := RetrieveTxByHash(pgb.db, txID)
return blockHash, blockInd, tree, err
}
// AddressTransactions retrieves a slice of *dbtypes.AddressRow for a given
// address and transaction type (i.e. all, credit, or debit) from the DB. Only
// the first N transactions starting from the offset element in the set of all
// txnType transactions.
func (pgb *ChainDB) AddressTransactions(address string, N, offset int64,
txnType dbtypes.AddrTxnType) (addressRows []*dbtypes.AddressRow, err error) {
var addrFunc func(*sql.DB, string, int64, int64) ([]uint64, []*dbtypes.AddressRow, error)
switch txnType {
case dbtypes.AddrTxnCredit:
//addrFunc = RetrieveAddressCreditTxns
fallthrough // retrieved address rows may also have spends
case dbtypes.AddrTxnAll:
// The organization address occurs very frequently, so use the regular
// (non sub-query) select as it is much more efficient.
if address == pgb.devAddress {
addrFunc = RetrieveAddressTxnsAlt
} else {
addrFunc = RetrieveAddressTxns
}
case dbtypes.AddrTxnDebit:
addrFunc = RetrieveAddressDebitTxns
default:
return nil, fmt.Errorf("unknown AddrTxnType %v", txnType)
}
_, addressRows, err = addrFunc(pgb.db, address, N, offset)
return
}
// AddressHistoryAll queries the database for all rows of the addresses table
// for the given address.
func (pgb *ChainDB) AddressHistoryAll(address string, N, offset int64) ([]*dbtypes.AddressRow, *explorer.AddressBalance, error) {
return pgb.AddressHistory(address, N, offset, dbtypes.AddrTxnAll)
}
// retrieveDevBalance retrieves a new DevFundBalance without regard to the cache
func (pgb *ChainDB) retrieveDevBalance() (*DevFundBalance, error) {
bb, hash, _, err := RetrieveBestBlockHeight(pgb.db)
if err != nil {
return nil, err
}
blockHeight := int64(bb)
blockHash, err := chainhash.NewHashFromStr(hash)
if err != nil {
return nil, err
}
_, devBalance, err := pgb.AddressHistoryAll(pgb.devAddress, 1, 0)
balance := &DevFundBalance{
AddressBalance: devBalance,
Height: blockHeight,
Hash: *blockHash,
}
return balance, err
}
// UpdateDevBalance forcibly updates the cached development/project fund balance
// via DB queries. The bool output inidcates if the cached balance was updated
// (if it was stale).
func (pgb *ChainDB) UpdateDevBalance() (bool, error) {
// See if a DB query is already running
okToUpdate := pgb.DevFundBalance.updating.TryLock()
// Wait on readers and possibly a writer regardless so the response will not
// be stale even when this call doesn't call updateDevBalance.
pgb.DevFundBalance.Lock()
defer pgb.DevFundBalance.Unlock()
// If we got the trylock, do an actual query for the balance
if okToUpdate {
defer pgb.DevFundBalance.updating.Unlock()
return pgb.updateDevBalance()
}
// Otherwise the other call will have just updated the balance, and we
// should not waste the cycles doing it again.
return false, nil
}
func (pgb *ChainDB) updateDevBalance() (bool, error) {
// Query for current balance.
balance, err := pgb.retrieveDevBalance()
if err != nil {
return false, err
}
// If cache is stale, update it's fields.
if balance.Hash != pgb.DevFundBalance.Hash || pgb.DevFundBalance.AddressBalance == nil {
pgb.DevFundBalance.AddressBalance = balance.AddressBalance
pgb.DevFundBalance.Height = balance.Height
pgb.DevFundBalance.Hash = balance.Hash
return true, nil
}
// Cache was not stale
return false, nil
}
// DevBalance returns the current development/project fund balance, updating the
// cached balance if it is stale.
func (pgb *ChainDB) DevBalance() (*explorer.AddressBalance, error) {
hash, err := pgb.HashDB()
if err != nil {
return nil, err
}
// Update cache if stale
if pgb.DevFundBalance.BlockHash().String() != hash || pgb.DevFundBalance.Balance() == nil {
if _, err = pgb.UpdateDevBalance(); err != nil {
return nil, err
}
}
bal := pgb.DevFundBalance.Balance()
if bal == nil {
return nil, fmt.Errorf("failed to update dev balance")
}
// return a copy of AddressBalance
balCopy := *bal
return &balCopy, nil
}
// addressBalance attempts to retrieve the explorer.AddressBalance from cache,
// and if cache is stale or missing data for the address, a DB query is used. A
// successful DB query will freshen the cache.
func (pgb *ChainDB) addressBalance(address string) (*explorer.AddressBalance, error) {
bb, err := pgb.HeightDB()
if err != nil {
return nil, err
}
bestBlock := int64(bb)
totals := pgb.addressCounts
totals.Lock()
defer totals.Unlock()
var balanceInfo explorer.AddressBalance
var fresh bool
if totals.validHeight == bestBlock {
balanceInfo, fresh = totals.balance[address]
} else {
// StoreBlock should do this, but the idea is to clear the old cached
// results when a new block is encountered.
log.Debugf("Address receive counter stale, at block %d when best is %d.",
totals.validHeight, bestBlock)
totals.balance = make(map[string]explorer.AddressBalance)
totals.validHeight = bestBlock
balanceInfo.Address = address
}
if !fresh {
var numSpent, numUnspent, totalSpent, totalUnspent int64
numSpent, numUnspent, totalSpent, totalUnspent, err =
RetrieveAddressSpentUnspent(pgb.db, address)
if err != nil {
return nil, err
}
balanceInfo = explorer.AddressBalance{
Address: address,
NumSpent: numSpent,
NumUnspent: numUnspent,
TotalSpent: totalSpent,
TotalUnspent: totalUnspent,
}
totals.balance[address] = balanceInfo
}
return &balanceInfo, nil
}
// AddressHistory queries the database for rows of the addresses table
// containing values for a certain type of transaction (all, credits, or debits)
// for the given address.
func (pgb *ChainDB) AddressHistory(address string, N, offset int64,
txnType dbtypes.AddrTxnType) ([]*dbtypes.AddressRow, *explorer.AddressBalance, error) {
bb, err := pgb.HeightDB()
if err != nil {
return nil, nil, err
}
bestBlock := int64(bb)
// See if address count cache includes a fresh count for this address.
totals := pgb.addressCounts
totals.Lock()
var balanceInfo explorer.AddressBalance
var fresh bool
if totals.validHeight == bestBlock {
balanceInfo, fresh = totals.balance[address]
} else {
// StoreBlock should do this, but the idea is to clear the old cached
// results when a new block is encountered.
log.Debugf("Address receive counter stale, at block %d when best is %d.",
totals.validHeight, bestBlock)
totals.balance = make(map[string]explorer.AddressBalance)
totals.validHeight = bestBlock
balanceInfo.Address = address
}
totals.Unlock()
// Retrieve relevant transactions
addressRows, err := pgb.AddressTransactions(address, N, offset, txnType)
if err != nil {
return nil, nil, err
}
if fresh {
return addressRows, &balanceInfo, nil
}
// If the address receive count was not cached, compute it and store it in
// the cache.
addrInfo := explorer.ReduceAddressHistory(addressRows)
if addrInfo == nil {
return addressRows, nil, fmt.Errorf("ReduceAddressHistory failed. len(addressRows) = %d", len(addressRows))
}
// N is a limit on NumFundingTxns, so this checks if we have them all.
if addrInfo.NumFundingTxns < N && offset == 0 && txnType == dbtypes.AddrTxnAll {
balanceInfo = explorer.AddressBalance{
Address: address,
NumSpent: addrInfo.NumSpendingTxns,
NumUnspent: addrInfo.NumFundingTxns - addrInfo.NumSpendingTxns,
TotalSpent: int64(addrInfo.AmountSent),
TotalUnspent: int64(addrInfo.AmountUnspent),
}
} else {
var numSpent, numUnspent, totalSpent, totalUnspent int64
numSpent, numUnspent, totalSpent, totalUnspent, err =
RetrieveAddressSpentUnspent(pgb.db, address)
if err != nil {
return nil, nil, err
}
balanceInfo = explorer.AddressBalance{
Address: address,
NumSpent: numSpent,
NumUnspent: numUnspent,
TotalSpent: totalSpent,
TotalUnspent: totalUnspent,
}
}
log.Infof("%s: %d spent totalling %f DCR, %d unspent totalling %f DCR",
address, balanceInfo.NumSpent, dcrutil.Amount(balanceInfo.TotalSpent).ToCoin(),
balanceInfo.NumUnspent, dcrutil.Amount(balanceInfo.TotalUnspent).ToCoin())
log.Infof("Caching address receive count for address %s: "+
"count = %d at block %d.", address,
balanceInfo.NumSpent+balanceInfo.NumUnspent, bestBlock)
totals.Lock()
totals.balance[address] = balanceInfo
totals.Unlock()
return addressRows, &balanceInfo, nil
}
// FillAddressTransactions is used to fill out the transaction details in an
// explorer.AddressInfo generated by explorer.ReduceAddressHistory, usually from
// the output of AddressHistory. This function also sets the number of
// unconfirmed transactions for the current best block in the database.
func (pgb *ChainDB) FillAddressTransactions(addrInfo *explorer.AddressInfo) error {
if addrInfo == nil {
return nil
}
var numUnconfirmed int64
for _, txn := range addrInfo.Transactions {
_, dbTx, err := RetrieveDbTxByHash(pgb.db, txn.TxID)
if err != nil {
return err
}
txn.Size = dbTx.Size
txn.FormattedSize = humanize.Bytes(uint64(dbTx.Size))
txn.Total = dcrutil.Amount(dbTx.Sent).ToCoin()
txn.Time = dbTx.BlockTime
if dbTx.BlockTime > 0 {
txn.Confirmations = pgb.Height() - uint64(dbTx.BlockHeight) + 1
} else {
numUnconfirmed++
txn.Confirmations = 0
}
txn.FormattedTime = time.Unix(dbTx.BlockTime, 0).Format("2006-01-02 15:04:05")
}
addrInfo.NumUnconfirmed = numUnconfirmed
return nil
}
// AddressTotals queries for the following totals: amount spent, amount unspent,
// number of unspent transaction outputs and number spent.
func (pgb *ChainDB) AddressTotals(address string) (*apitypes.AddressTotals, error) {
// Fetch address totals
var err error
var ab *explorer.AddressBalance
if address == pgb.devAddress {
ab, err = pgb.DevBalance()
} else {
ab, err = pgb.addressBalance(address)
}
if err != nil || ab == nil {
return nil, err
}
bestHeight, bestHash, _, err := RetrieveBestBlockHeight(pgb.db)
if err != nil {
return nil, err
}
return &apitypes.AddressTotals{
Address: address,
BlockHeight: bestHeight,
BlockHash: bestHash,
NumSpent: ab.NumSpent,
NumUnspent: ab.NumUnspent,
CoinsSpent: dcrutil.Amount(ab.TotalSpent).ToCoin(),
CoinsUnspent: dcrutil.Amount(ab.TotalUnspent).ToCoin(),
}, nil
}
func (pgb *ChainDB) addressInfo(addr string, count, skip int64,
txnType dbtypes.AddrTxnType) (*explorer.AddressInfo, *explorer.AddressBalance, error) {
address, err := dcrutil.DecodeAddress(addr)
if err != nil {
log.Infof("Invalid address %s: %v", addr, err)
return nil, nil, err
}
// Get rows from the addresses table for the address
addrHist, balance, errH := pgb.AddressHistory(addr, count, skip, txnType)
if errH != nil {
log.Errorf("Unable to get address %s history: %v", address, errH)
return nil, nil, errH
}
// Generate AddressInfo skeleton from the address table rows
addrData := explorer.ReduceAddressHistory(addrHist)
if addrData == nil {
// Empty history is not expected for credit txnType with any txns.
if txnType != dbtypes.AddrTxnDebit && (balance.NumSpent+balance.NumUnspent) > 0 {
return nil, nil, fmt.Errorf("empty address history (%s): n=%d&start=%d", address, count, skip)
}
// No mined transactions. Return Address with nil Transactions slice.
return nil, balance, nil
}
// Transactions to fetch with FillAddressTransactions. This should be a
// noop if AddressHistory/ReduceAddressHistory are working right.
switch txnType {
case dbtypes.AddrTxnAll:
case dbtypes.AddrTxnCredit:
addrData.Transactions = addrData.TxnsFunding
case dbtypes.AddrTxnDebit:
addrData.Transactions = addrData.TxnsSpending
default:
// shouldn't happen because AddressHistory does this check
return nil, nil, fmt.Errorf("unknown address transaction type: %v", txnType)
}
// Query database for transaction details
err = pgb.FillAddressTransactions(addrData)
if err != nil {
return nil, balance, fmt.Errorf("Unable to fill address %s transactions: %v", address, err)
}
return addrData, balance, nil
}
// AddressTransactionDetails returns an apitypes.Address with at most the last
// count transactions of type txnType in which the address was involved,
// starting after skip transactions. This does NOT include unconfirmed
// transactions.
func (pgb *ChainDB) AddressTransactionDetails(addr string, count, skip int64,
txnType dbtypes.AddrTxnType) (*apitypes.Address, error) {
// Fetch address history for given transaction range and type
addrData, _, err := pgb.addressInfo(addr, count, skip, txnType)
if err != nil {
return nil, err
}
// Convert each explorer.AddressTx to apitypes.AddressTxShort
txs := addrData.Transactions
txsShort := make([]*apitypes.AddressTxShort, 0, len(txs))
for i := range txs {
txsShort = append(txsShort, &apitypes.AddressTxShort{
TxID: txs[i].TxID,
Time: txs[i].Time,
Value: txs[i].Total,
Confirmations: int64(txs[i].Confirmations),
Size: int32(txs[i].Size),
})
}
// put a bow on it
return &apitypes.Address{
Address: addr,
Transactions: txsShort,
}, nil
}
// TODO: finish
func (pgb *ChainDB) AddressTransactionRawDetails(addr string, count, skip int64,
txnType dbtypes.AddrTxnType) ([]*apitypes.AddressTxRaw, error) {
addrData, _, err := pgb.addressInfo(addr, count, skip, txnType)
if err != nil {
return nil, err
}
// Convert each explorer.AddressTx to apitypes.AddressTxRaw
txs := addrData.Transactions
txsRaw := make([]*apitypes.AddressTxRaw, 0, len(txs))
for i := range txs {
txsRaw = append(txsRaw, &apitypes.AddressTxRaw{
Size: int32(txs[i].Size),
TxID: txs[i].TxID,
// Version
// LockTime
// Vin
// Vout
//
Confirmations: int64(txs[i].Confirmations),
//BlockHash: txs[i].
Time: txs[i].Time,
//Blocktime:
})
}
return txsRaw, nil
}
// Store satisfies BlockDataSaver
func (pgb *ChainDB) Store(blockData *blockdata.BlockData, msgBlock *wire.MsgBlock) error {
if pgb == nil {
return nil
}
_, _, err := pgb.StoreBlock(msgBlock, blockData.WinningTickets, true, true, true)
return err
}
func (pgb *ChainDB) DeleteDuplicates() error {
var err error
// Remove duplicate vins
log.Info("Finding and removing duplicate vins entries...")
var numVinsRemoved int64
if numVinsRemoved, err = pgb.DeleteDuplicateVins(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateVins failed: %v", err)
}
log.Infof("Removed %d duplicate vins entries.", numVinsRemoved)
// Remove duplicate vouts
log.Info("Finding and removing duplicate vouts entries before indexing...")
var numVoutsRemoved int64
if numVoutsRemoved, err = pgb.DeleteDuplicateVouts(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateVouts failed: %v", err)
}
log.Infof("Removed %d duplicate vouts entries.", numVoutsRemoved)
// Remove duplicate transactions
log.Info("Finding and removing duplicate transactions entries before indexing...")
var numTxnsRemoved int64
if numTxnsRemoved, err = pgb.DeleteDuplicateTxns(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateTxns failed: %v", err)
}
log.Infof("Removed %d duplicate transactions entries.", numTxnsRemoved)
// TODO: remove entries from addresses table that reference removed
// vins/vouts.
return err
}
func (pgb *ChainDB) DeleteDuplicatesRecovery() error {
var err error
// Remove duplicate vins
log.Info("Finding and removing duplicate vins entries...")
var numVinsRemoved int64
if numVinsRemoved, err = pgb.DeleteDuplicateVins(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateVins failed: %v", err)
}
log.Infof("Removed %d duplicate vins entries.", numVinsRemoved)
// Remove duplicate vouts
log.Info("Finding and removing duplicate vouts entries before indexing...")
var numVoutsRemoved int64
if numVoutsRemoved, err = pgb.DeleteDuplicateVouts(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateVouts failed: %v", err)
}
log.Infof("Removed %d duplicate vouts entries.", numVoutsRemoved)
// TODO: remove entries from addresses table that reference removed
// vins/vouts.
// Remove duplicate transactions
log.Info("Finding and removing duplicate transactions entries before indexing...")
var numTxnsRemoved int64
if numTxnsRemoved, err = pgb.DeleteDuplicateTxns(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateTxns failed: %v", err)
}
log.Infof("Removed %d duplicate transactions entries.", numTxnsRemoved)
// Remove duplicate tickets
log.Info("Finding and removing duplicate tickets entries before indexing...")
if numTxnsRemoved, err = pgb.DeleteDuplicateTickets(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateTickets failed: %v", err)
}
log.Infof("Removed %d duplicate tickets entries.", numTxnsRemoved)
// Remove duplicate votes
log.Info("Finding and removing duplicate votes entries before indexing...")
if numTxnsRemoved, err = pgb.DeleteDuplicateVotes(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateVotes failed: %v", err)
}
log.Infof("Removed %d duplicate votes entries.", numTxnsRemoved)
// Remove duplicate misses
log.Info("Finding and removing duplicate misses entries before indexing...")
if numTxnsRemoved, err = pgb.DeleteDuplicateMisses(); err != nil {
return fmt.Errorf("dcrpg.DeleteDuplicateMisses failed: %v", err)
}
log.Infof("Removed %d duplicate misses entries.", numTxnsRemoved)
return err
}
func (pgb *ChainDB) DeleteDuplicateVins() (int64, error) {
return DeleteDuplicateVins(pgb.db)
}
func (pgb *ChainDB) DeleteDuplicateVouts() (int64, error) {
return DeleteDuplicateVouts(pgb.db)
}
func (pgb *ChainDB) DeleteDuplicateTxns() (int64, error) {
return DeleteDuplicateTxns(pgb.db)
}
func (pgb *ChainDB) DeleteDuplicateTickets() (int64, error) {
return DeleteDuplicateTickets(pgb.db)
}
func (pgb *ChainDB) DeleteDuplicateVotes() (int64, error) {
return DeleteDuplicateVotes(pgb.db)
}
func (pgb *ChainDB) DeleteDuplicateMisses() (int64, error) {
return DeleteDuplicateMisses(pgb.db)
}
// DeindexAll drops all of the indexes in all tables
func (pgb *ChainDB) DeindexAll() error {
var err, errAny error
if err = DeindexBlockTableOnHash(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexTransactionTableOnHashes(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexTransactionTableOnBlockIn(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexVinTableOnVins(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexVinTableOnPrevOuts(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexVoutTableOnTxHashIdx(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
// if err = DeindexVoutTableOnTxHash(pgb.db); err != nil {
// warnUnlessNotExists(err)
// errAny = err
// }
if err = DeindexAddressTableOnAddress(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexAddressTableOnVoutID(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexAddressTableOnTxHash(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = pgb.DeindexTicketsTable(); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexVotesTableOnCandidate(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexVotesTableOnHash(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexVotesTableOnVoteVersion(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
if err = DeindexMissesTableOnHash(pgb.db); err != nil {
warnUnlessNotExists(err)
errAny = err
}
return errAny
}
// IndexAll creates all of the indexes in all tables
func (pgb *ChainDB) IndexAll() error {