/
pgblockchain.go
2421 lines (2131 loc) · 83.3 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) 2018, The Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package dcrpg
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"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/v3/api/types"
"github.com/decred/dcrdata/v3/blockdata"
"github.com/decred/dcrdata/v3/db/dbtypes"
"github.com/decred/dcrdata/v3/db/dcrpg/internal"
"github.com/decred/dcrdata/v3/explorer"
"github.com/decred/dcrdata/v3/rpcutils"
"github.com/decred/dcrdata/v3/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
}
// ticketPoolDataCache stores the most recent ticketpool graphs information
// fetched to minimize the possibility of making multiple queries to the db
// fetching the same information.
type ticketPoolDataCache struct {
sync.RWMutex
Height map[dbtypes.ChartGrouping]uint64
// BarGraphsCache persists data for the Ticket purchase distribution chart
// and Ticket Price Distribution chart
BarGraphsCache map[dbtypes.ChartGrouping][]*dbtypes.PoolTicketsData
// DonutGraphCache persist data for the Number of tickets outputs pie chart.
DonutGraphCache map[dbtypes.ChartGrouping]*dbtypes.PoolTicketsData
}
// ticketPoolGraphsCache persists the latest ticketpool data queried from the db.
var ticketPoolGraphsCache = &ticketPoolDataCache{
Height: make(map[dbtypes.ChartGrouping]uint64),
BarGraphsCache: make(map[dbtypes.ChartGrouping][]*dbtypes.PoolTicketsData),
DonutGraphCache: make(map[dbtypes.ChartGrouping]*dbtypes.PoolTicketsData),
}
// TicketPoolData is a thread-safe way to access the ticketpool graphs data
// stored in the cache.
func TicketPoolData(interval dbtypes.ChartGrouping, height uint64) (barGraphs []*dbtypes.PoolTicketsData,
donutChart *dbtypes.PoolTicketsData, actualHeight uint64, intervalFound, isStale bool) {
ticketPoolGraphsCache.RLock()
defer ticketPoolGraphsCache.RUnlock()
var found bool
barGraphs, intervalFound = ticketPoolGraphsCache.BarGraphsCache[interval]
donutChart, found = ticketPoolGraphsCache.DonutGraphCache[interval]
intervalFound = intervalFound && found
actualHeight = ticketPoolGraphsCache.Height[interval]
isStale = ticketPoolGraphsCache.Height[interval] != height
return
}
// UpdateTicketPoolData updates the ticket pool cache with the latest data fetched.
// This is a thread-safe way to update ticket pool cache data. TryLock helps avoid
// stacking calls to update the cache.
func UpdateTicketPoolData(interval dbtypes.ChartGrouping, barGraphs []*dbtypes.PoolTicketsData,
donutcharts *dbtypes.PoolTicketsData, height uint64) {
ticketPoolGraphsCache.Lock()
defer ticketPoolGraphsCache.Unlock()
ticketPoolGraphsCache.Height[interval] = height
ticketPoolGraphsCache.BarGraphsCache[interval] = barGraphs
ticketPoolGraphsCache.DonutGraphCache[interval] = donutcharts
}
// UTXOData stores an address and value associated with a transaction output.
type UTXOData struct {
Address string
Value int64
}
// utxoStore provides a UTXOData cache with thread-safe get/set methods.
type utxoStore struct {
sync.Mutex
c map[string]map[uint32]*UTXOData
}
// newUtxoStore constructs a new utxoStore.
func newUtxoStore(prealloc int) utxoStore {
return utxoStore{
c: make(map[string]map[uint32]*UTXOData, prealloc),
}
}
// Get attempts to locate UTXOData for the specified outpoint. If the data is
// not in the cache, a nil pointer and false are returned. If the data is
// located, the data and true are returned, and the data is evicted from cache.
func (u *utxoStore) Get(txHash string, txIndex uint32) (*UTXOData, bool) {
u.Lock()
defer u.Unlock()
utxoData, ok := u.c[txHash][txIndex]
if ok {
u.c[txHash][txIndex] = nil
delete(u.c[txHash], txIndex)
if len(u.c[txHash]) == 0 {
delete(u.c, txHash)
}
}
return utxoData, ok
}
// Set stores the address and amount in a UTXOData entry in the cache for the
// given outpoint.
func (u *utxoStore) Set(txHash string, txIndex uint32, addr string, val int64) {
u.Lock()
defer u.Unlock()
txUTXOVals, ok := u.c[txHash]
if !ok {
u.c[txHash] = map[uint32]*UTXOData{
txIndex: &UTXOData{
Address: addr,
Value: val,
},
}
} else {
txUTXOVals[txIndex] = &UTXOData{
Address: addr,
Value: val,
}
}
}
// Size returns the size of the utxo cache in number of UTXOs.
func (u *utxoStore) Size() (sz int) {
u.Lock()
defer u.Unlock()
for _, m := range u.c {
sz += len(m)
}
return
}
// ChainDB provides an interface for storing and manipulating extracted
// blockchain data in a PostgreSQL database.
type ChainDB struct {
ctx context.Context
db *sql.DB
chainParams *chaincfg.Params
devAddress string
dupChecks bool
bestBlock int64
bestBlockHash string
lastBlock map[chainhash.Hash]uint64
addressCounts *addressCounter
stakeDB *stakedb.StakeDatabase
unspentTicketCache *TicketTxnIDGetter
DevFundBalance *DevFundBalance
devPrefetch bool
InBatchSync bool
InReorg bool
tpUpdatePermission map[dbtypes.ChartGrouping]*trylock.Mutex
utxoCache utxoStore
}
// ChainDBRPC provides an interface for storing and manipulating extracted and
// includes the RPC Client blockchain data in a PostgreSQL database.
type ChainDBRPC struct {
*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
}
// SyncChainDBAsync calls (*ChainDB).SyncChainDBAsync after a nil pointer check
// on the ChainDBRPC receiver.
func (db *ChainDBRPC) SyncChainDBAsync(ctx context.Context, res chan dbtypes.SyncResult,
client rpcutils.MasterBlockGetter, updateAllAddresses, updateAllVotes, newIndexes bool,
updateExplorer chan *chainhash.Hash, barLoad chan *dbtypes.ProgressBarLoad) {
// Allowing db to be nil simplifies logic in caller.
if db == nil {
res <- dbtypes.SyncResult{
Height: -1,
Error: fmt.Errorf("ChainDB (psql) disabled"),
}
return
}
db.ChainDB.SyncChainDBAsync(ctx, res, client, updateAllAddresses,
updateAllVotes, newIndexes, updateExplorer, barLoad)
}
// Store satisfies BlockDataSaver. Blocks stored this way are considered valid
// and part of mainchain. This calls (*ChainDB).Store after a nil pointer check
// on the ChainDBRPC receiver
func (db *ChainDBRPC) Store(blockData *blockdata.BlockData, msgBlock *wire.MsgBlock) error {
// Allowing db to be nil simplifies logic in caller.
if db == nil {
return nil
}
return db.ChainDB.Store(blockData, msgBlock)
}
// MissingSideChainBlocks identifies side chain blocks that are missing from the
// DB. Side chains known to dcrd are listed via the getchaintips RPC. Each block
// presence in the postgres DB is checked, and any missing block is returned in
// a SideChain along with a count of the total number of missing blocks.
func (db *ChainDBRPC) MissingSideChainBlocks() ([]dbtypes.SideChain, int, error) {
// First get the side chain tips (head blocks).
tips, err := rpcutils.SideChains(db.Client)
if err != nil {
return nil, 0, fmt.Errorf("unable to get chain tips from node: %v", err)
}
nSideChains := len(tips)
// Build a list of all the blocks in each side chain that are not
// already in the database.
blocksToStore := make([]dbtypes.SideChain, nSideChains)
var nSideChainBlocks int
for it := range tips {
sideHeight := tips[it].Height
log.Tracef("Getting full side chain with tip %s at %d.", tips[it].Hash, sideHeight)
sideChain, err := rpcutils.SideChainFull(db.Client, tips[it].Hash)
if err != nil {
return nil, 0, fmt.Errorf("unable to get side chain blocks for chain tip %s: %v",
tips[it].Hash, err)
}
// Starting height is the lowest block in the side chain.
sideHeight -= int64(len(sideChain)) - 1
// For each block in the side chain, check if it already stored.
for is := range sideChain {
// Check for the block hash in the DB.
sideHeightDB, err := db.BlockHeight(sideChain[is])
if err == sql.ErrNoRows {
// This block is NOT already in the DB.
blocksToStore[it].Hashes = append(blocksToStore[it].Hashes, sideChain[is])
blocksToStore[it].Heights = append(blocksToStore[it].Heights, sideHeight)
nSideChainBlocks++
} else if err == nil {
// This block is already in the DB.
log.Tracef("Found block %s in postgres at height %d.",
sideChain[is], sideHeightDB)
if sideHeight != sideHeightDB {
log.Errorf("Side chain block height %d, expected %d.",
sideHeightDB, sideHeight)
}
} else /* err != nil && err != sql.ErrNoRows */ {
// Unexpected error
log.Errorf("Failed to retrieve block %s: %v", sideChain[is], err)
}
// Next block
sideHeight++
}
}
return blocksToStore, nSideChainBlocks, 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
}
// Cache miss. Get the row id by hash from the tickets table.
log.Tracef("Cache miss for %s.", txid)
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
}
// NewChainDBWithCancel constructs a cancellation-capable ChainDB for the given
// connection and Decred network parameters. By default, duplicate row checks on
// insertion are enabled.
func NewChainDBWithCancel(ctx context.Context, dbi *DBInfo, params *chaincfg.Params,
stakeDB *stakedb.StakeDatabase, devPrefetch bool) (*ChainDB, error) {
chainDB, err := NewChainDB(dbi, params, stakeDB, devPrefetch)
if err != nil {
return nil, err
}
chainDB.ctx = ctx
return chainDB, nil
}
// 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, bestHash, _, 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)
}
// For each chart grouping type create a non-blocking updater mutex.
tpUpdatePermissions := make(map[dbtypes.ChartGrouping]*trylock.Mutex)
for g := range dbtypes.ChartGroupings {
tpUpdatePermissions[g] = new(trylock.Mutex)
}
return &ChainDB{
ctx: context.Background(),
db: db,
chainParams: params,
devAddress: devSubsidyAddress,
dupChecks: true,
bestBlock: int64(bestHeight),
bestBlockHash: bestHash,
lastBlock: make(map[chainhash.Hash]uint64),
addressCounts: makeAddressCounter(),
stakeDB: stakeDB,
unspentTicketCache: unspentTicketCache,
DevFundBalance: new(DevFundBalance),
devPrefetch: devPrefetch,
tpUpdatePermission: tpUpdatePermissions,
utxoCache: newUtxoStore(2e4),
}, 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. If there is no automatic upgrade supported, an error
// is returned when any table is not of the correct version.
// A smart client is passed to implement the supported upgrades if need be.
func (pgb *ChainDB) VersionCheck(client *rpcclient.Client) 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 {
if tableUpgrades[0].UpgradeType == "upgrade" || tableUpgrades[0].UpgradeType == "reindex" {
// CheckForAuxDBUpgrade makes db upgrades that are currently supported.
isSuccess, err := pgb.CheckForAuxDBUpgrade(client)
if err != nil {
return err
}
// Upgrade was successful, no need to proceed.
if isSuccess {
return nil
}
}
// ensure all tables have "ok" status
OK := true
for _, u := range tableUpgrades {
if u.UpgradeType != "ok" {
log.Warnf(u.String())
OK = false
}
}
if OK {
log.Debugf("All tables at correct version (%v)", tableUpgrades[0].RequiredVer)
return nil
}
return fmt.Errorf("rebuild of PostgreSQL tables required (drop with rebuilddb2 -D)")
}
return nil
}
// DropTables drops (deletes) all of the known dcrdata tables.
func (pgb *ChainDB) DropTables() {
DropTables(pgb.db)
}
// SideChainBlocks retrieves all known side chain blocks.
func (pgb *ChainDB) SideChainBlocks() ([]*dbtypes.BlockStatus, error) {
return RetrieveSideChainBlocks(pgb.db)
}
// SideChainTips retrieves the tip/head block for all known side chains.
func (pgb *ChainDB) SideChainTips() ([]*dbtypes.BlockStatus, error) {
return RetrieveSideChainTips(pgb.db)
}
// DisapprovedBlocks retrieves all blocks disapproved by stakeholder votes.
func (pgb *ChainDB) DisapprovedBlocks() ([]*dbtypes.BlockStatus, error) {
return RetrieveDisapprovedBlocks(pgb.db)
}
// BlockStatus retrieves the block chain status of the specified block.
func (pgb *ChainDB) BlockStatus(hash string) (dbtypes.BlockStatus, error) {
return RetrieveBlockStatus(pgb.db, hash)
}
// BlockFlags retrieves the block's isValid and isMainchain flags.
func (pgb *ChainDB) BlockFlags(hash string) (bool, bool, error) {
return RetrieveBlockFlags(pgb.db, hash)
}
// TransactionBlocks retrieves the blocks in which the specified transaction
// appears, along with the index of the transaction in each of the blocks. The
// next and previous block hashes are NOT SET in each BlockStatus.
func (pgb *ChainDB) TransactionBlocks(txHash string) ([]*dbtypes.BlockStatus, []uint32, error) {
hashes, heights, inds, valids, mainchains, err := RetrieveTxnsBlocks(pgb.db, txHash)
if err != nil {
return nil, nil, err
}
blocks := make([]*dbtypes.BlockStatus, len(hashes))
for i := range hashes {
blocks[i] = &dbtypes.BlockStatus{
IsValid: valids[i],
IsMainchain: mainchains[i],
Height: heights[i],
Hash: hashes[i],
// Next and previous hash not set
}
}
return blocks, inds, nil
}
// 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)
}
// HashStr uses the last stored block hash.
func (pgb *ChainDB) HashStr() string {
return pgb.bestBlockHash
}
// Hash uses the last stored block hash.
func (pgb *ChainDB) Hash() *chainhash.Hash {
// Caller should check hash instead of error
hash, _ := chainhash.NewHashFromStr(pgb.bestBlockHash)
return hash
}
// BlockHeight queries the DB for the height of the specified hash.
func (pgb *ChainDB) BlockHeight(hash string) (int64, error) {
return RetrieveBlockHeight(pgb.db, hash)
}
// BlockHash queries the DB for the hash of the mainchain block at the given
// height.
func (pgb *ChainDB) BlockHash(height int64) (string, error) {
return RetrieveBlockHash(pgb.db, height)
}
// 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
}
// Transaction retrieves all rows from the transactions table for the given
// transaction hash.
func (pgb *ChainDB) Transaction(txHash string) ([]*dbtypes.Tx, error) {
_, dbTxs, err := RetrieveDbTxsByHash(pgb.db, txHash)
return dbTxs, 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
}
// AgendaVotes fetches the data used to plot a graph of votes cast per day per
// choice for the provided agenda.
func (pgb *ChainDB) AgendaVotes(agendaID string, chartType int) (*dbtypes.AgendaVoteChoices, error) {
return retrieveAgendaVoteChoices(pgb.db, agendaID, chartType)
}
// GetOldestTxBlockTime returns the block time of the oldest transaction made in
// relation to the provided address. This helps provide more meaningful graphs
// with the addresses history plotted.
func (pgb *ChainDB) GetOldestTxBlockTime(addr string) (int64, error) {
return retrieveOldestTxBlockTime(pgb.db, addr)
}
// 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
case dbtypes.AddrTxnAll:
addrFunc = RetrieveAddressTxns
case dbtypes.AddrTxnDebit:
addrFunc = RetrieveAddressDebitTxns
case dbtypes.AddrMergedTxnDebit:
addrFunc = RetrieveAddressMergedDebitTxns
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)
}
// GetTicketPoolBlockMaturity returns the block at which all tickets with height
// greater than it are immature.
func (pgb *ChainDB) GetTicketPoolBlockMaturity() int64 {
bestBlock := int64(pgb.stakeDB.Height())
return bestBlock - int64(pgb.chainParams.TicketMaturity)
}
// GetTicketPoolByDateAndInterval fetches the tickets ordered by the purchase date
// interval provided and an error value.
func (pgb *ChainDB) GetTicketPoolByDateAndInterval(maturityBlock int64,
interval dbtypes.ChartGrouping) (*dbtypes.PoolTicketsData, error) {
val, err := dbtypes.ChartGroupingToInterval(interval)
if err != nil {
return nil, err
}
return retrieveTicketsByDate(pgb.db, maturityBlock, int64(val))
}
// PosIntervals retrieves the blocks at the respective stakebase windows interval.
// The term "window" is used here to describe the group of blocks whose count is
// defined by chainParams.StakeDiffWindowSize. During this chainParams.StakeDiffWindowSize
// block interval the ticket price and the difficulty value is constant.
func (pgb *ChainDB) PosIntervals(limit, offset uint64) ([]*dbtypes.BlocksGroupedInfo, error) {
return retrieveWindowBlocks(pgb.db, pgb.chainParams.StakeDiffWindowSize, limit, offset)
}
// TicketPoolVisualization helps block consecutive and duplicate DB queries for
// the requested ticket pool chart data. If the data for the given interval is
// cached and fresh, it is returned. If the cached data is stale and there are
// no queries running to update the cache for the given interval, this launches
// a query and updates the cache. If there is no cached data for the interval,
// this will launch a new query for the data if one is not already running, and
// if one is running, it will wait for the query to complete.
func (pgb *ChainDB) TicketPoolVisualization(interval dbtypes.ChartGrouping) ([]*dbtypes.PoolTicketsData, *dbtypes.PoolTicketsData, uint64, error) {
// Attempt to retrieve data for the current block from cache.
heightSeen := pgb.Height() // current block seen *by the ChainDB*
barcharts, donutCharts, height, intervalFound, stale := TicketPoolData(interval, heightSeen)
if intervalFound && !stale {
// The cache was fresh.
return barcharts, donutCharts, height, nil
}
// Cache is stale or empty. Attempt to gain updater status.
if !pgb.tpUpdatePermission[interval].TryLock() {
// Another goroutine is running db query to get the updated data.
if !intervalFound {
// Do not even have stale data. Must wait for the DB update to
// complete to get any data at all. Use a blocking call on the
// updater lock even though we are not going to actually do an
// update ourselves so we do not block the cache while waiting.
pgb.tpUpdatePermission[interval].Lock()
defer pgb.tpUpdatePermission[interval].Unlock()
// Try again to pull it from cache now that the update is completed.
heightSeen = pgb.Height()
barcharts, donutCharts, height, intervalFound, stale = TicketPoolData(interval, heightSeen)
// We waited for the updater of this interval, so it should be found
// at this point. If not, this is an error.
if !intervalFound {
log.Errorf("Charts data for interval %v failed to update.", interval)
return nil, nil, 0, fmt.Errorf("no charts data available")
}
if stale {
log.Warnf("Charts data for interval %v updated, but still stale.", interval)
}
}
// else return the stale data instead of waiting.
return barcharts, donutCharts, height, nil
}
// This goroutine is now the cache updater.
defer pgb.tpUpdatePermission[interval].Unlock()
// Retrieve chart data for best block in DB.
var err error
barcharts, donutCharts, height, err = pgb.ticketPoolVisualization(interval)
if err != nil {
log.Errorf("Failed to fetch ticket pool data: %v", err)
return nil, nil, 0, err
}
// Update the cache with the new ticket pool data.
UpdateTicketPoolData(interval, barcharts, donutCharts, height)
return barcharts, donutCharts, height, nil
}
// ticketPoolVisualization fetches the following ticketpool data: tickets
// grouped on the specified interval, tickets grouped by price, and ticket
// counts by ticket type (solo, pool, other split). The interval may be one of:
// "mo", "wk", "day", or "all". The data is needed to populate the ticketpool
// graphs. The data grouped by time and price are returned in a slice.
func (pgb *ChainDB) ticketPoolVisualization(interval dbtypes.ChartGrouping) (byTimeAndPrice []*dbtypes.PoolTicketsData, byInputs *dbtypes.PoolTicketsData, height uint64, err error) {
// Ensure DB height is the same before and after queries since they are not
// atomic. Initial height:
height = pgb.Height()
for {
// Latest block where mature tickets may have been mined.
maturityBlock := pgb.GetTicketPoolBlockMaturity()
// Tickets grouped by time interval
ticketsByTime, err := pgb.GetTicketPoolByDateAndInterval(maturityBlock, interval)
if err != nil {
return nil, nil, 0, err
}
// Tickets grouped by price
ticketsByPrice, err := retrieveTicketByPrice(pgb.db, maturityBlock)
if err != nil {
return nil, nil, 0, err
}
// Return time- and price-grouped data in a slice
byTimeAndPrice = []*dbtypes.PoolTicketsData{ticketsByTime, ticketsByPrice}
// Tickets grouped by number of inputs.
byInputs, err = retrieveTicketsGroupedByType(pgb.db)
if err != nil {
return nil, nil, 0, err
}
heightEnd := pgb.Height()
if heightEnd == height {
break
}
// otherwise try again to ensure charts are consistent.
height = heightEnd
}
return
}
// 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
}
// FreshenAddressCaches resets the address balance cache, and prefetches the
// project fund balance if devPrefetch is enabled and not mid-reorg.
func (pgb *ChainDB) FreshenAddressCaches(lazyProjectFund bool) error {
pgb.addressCounts.Lock()
pgb.addressCounts.validHeight = pgb.bestBlock
pgb.addressCounts.balance = map[string]explorer.AddressBalance{}
pgb.addressCounts.Unlock()
// Lazy update of DevFundBalance
if pgb.devPrefetch && !pgb.InReorg {
updateBalance := func() error {
log.Infof("Pre-fetching project fund balance at height %d...", pgb.bestBlock)
if _, err := pgb.UpdateDevBalance(); err != nil {
return fmt.Errorf("Failed to update project fund balance: %v", err)
}
return nil
}
if lazyProjectFund {
go func() {
runtime.Gosched()
if err := updateBalance(); err != nil {
log.Error(err)
}
}()
return nil
}
return updateBalance()
}
return nil
}
// 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) {
if !pgb.InReorg {