/
pgblockchain.go
5912 lines (5240 loc) · 200 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-2019, The Eacred developers
// Copyright (c) 2017, The ecrdata developers
// See LICENSE for details.
package dcrpg
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/chappjc/trylock"
"github.com/Eacred/eacrd/blockchain/stake"
"github.com/Eacred/eacrd/chaincfg/chainhash"
"github.com/Eacred/eacrd/chaincfg"
"github.com/Eacred/eacrd/dcrutil"
chainjson "github.com/Eacred/eacrd/rpc/jsonrpc/types"
"github.com/Eacred/eacrd/rpcclient"
"github.com/Eacred/eacrd/wire"
apitypes "github.com/Eacred/eacrdata/api/types"
"github.com/Eacred/eacrdata/blockdata"
"github.com/Eacred/eacrdata/db/cache"
"github.com/Eacred/eacrdata/db/dbtypes"
"github.com/Eacred/eacrdata/db/dcrpg/internal"
exptypes "github.com/Eacred/eacrdata/explorer/types"
"github.com/Eacred/eacrdata/mempool"
"github.com/Eacred/eacrdata/rpcutils"
"github.com/Eacred/eacrdata/stakedb"
"github.com/Eacred/eacrdata/txhelpers"
pitypes "github.com/dmigwi/go-piparser/proposals/types"
humanize "github.com/dustin/go-humanize"
"github.com/lib/pq"
)
var (
zeroHash = chainhash.Hash{}
zeroHashStringBytes = []byte(chainhash.Hash{}.String())
)
const dcrToAtoms = 1e8
type retryError struct{}
// Error implements Stringer for retryError.
func (s retryError) Error() string {
return "retry"
}
// IsRetryError checks if an error is a retryError type.
func IsRetryError(err error) bool {
_, isRetryErr := err.(retryError)
return isRetryErr
}
// storedAgendas holds the current state of agenda data already in the db.
// This helps track changes in the lockedIn and activated heights when they
// happen without making too many db accesses everytime we are updating the
// agenda_votes table.
var storedAgendas map[string]dbtypes.MileStone
// isPiparserRunning is the flag set when a Piparser instance is running.
const isPiparserRunning = uint32(1)
// piParserCounter is a counter that helps guarantee that only one instance
// of proposalsUpdateHandler can ever be running at any one given moment.
var piParserCounter uint32
// 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.TimeBasedGrouping]int64
TimeGraphCache map[dbtypes.TimeBasedGrouping]*dbtypes.PoolTicketsData
PriceGraphCache map[dbtypes.TimeBasedGrouping]*dbtypes.PoolTicketsData
// DonutGraphCache persist data for the Number of tickets outputs pie chart.
DonutGraphCache map[dbtypes.TimeBasedGrouping]*dbtypes.PoolTicketsData
}
// ProposalsFetcher defines the interface of the proposals plug-n-play data source.
type ProposalsFetcher interface {
UpdateSignal() <-chan struct{}
ProposalsHistory() ([]*pitypes.History, error)
ProposalsHistorySince(since time.Time) ([]*pitypes.History, error)
}
// ticketPoolGraphsCache persists the latest ticketpool data queried from the db.
var ticketPoolGraphsCache = &ticketPoolDataCache{
Height: make(map[dbtypes.TimeBasedGrouping]int64),
TimeGraphCache: make(map[dbtypes.TimeBasedGrouping]*dbtypes.PoolTicketsData),
PriceGraphCache: make(map[dbtypes.TimeBasedGrouping]*dbtypes.PoolTicketsData),
DonutGraphCache: make(map[dbtypes.TimeBasedGrouping]*dbtypes.PoolTicketsData),
}
// TicketPoolData is a thread-safe way to access the ticketpool graphs data
// stored in the cache.
func TicketPoolData(interval dbtypes.TimeBasedGrouping, height int64) (timeGraph *dbtypes.PoolTicketsData,
priceGraph *dbtypes.PoolTicketsData, donutChart *dbtypes.PoolTicketsData, actualHeight int64, intervalFound, isStale bool) {
ticketPoolGraphsCache.RLock()
defer ticketPoolGraphsCache.RUnlock()
var tFound, pFound, dFound bool
timeGraph, tFound = ticketPoolGraphsCache.TimeGraphCache[interval]
priceGraph, pFound = ticketPoolGraphsCache.PriceGraphCache[interval]
donutChart, dFound = ticketPoolGraphsCache.DonutGraphCache[interval]
intervalFound = tFound && pFound && dFound
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.TimeBasedGrouping, timeGraph *dbtypes.PoolTicketsData,
priceGraph *dbtypes.PoolTicketsData, donutcharts *dbtypes.PoolTicketsData, height int64) {
ticketPoolGraphsCache.Lock()
defer ticketPoolGraphsCache.Unlock()
ticketPoolGraphsCache.Height[interval] = height
ticketPoolGraphsCache.TimeGraphCache[interval] = timeGraph
ticketPoolGraphsCache.PriceGraphCache[interval] = priceGraph
ticketPoolGraphsCache.DonutGraphCache[interval] = donutcharts
}
// utxoStore provides a UTXOData cache with thread-safe get/set methods.
type utxoStore struct {
sync.Mutex
c map[string]map[uint32]*dbtypes.UTXOData
}
// newUtxoStore constructs a new utxoStore.
func newUtxoStore(prealloc int) utxoStore {
return utxoStore{
c: make(map[string]map[uint32]*dbtypes.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) (*dbtypes.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
}
func (u *utxoStore) set(txHash string, txIndex uint32, addrs []string, val int64) {
txUTXOVals, ok := u.c[txHash]
if !ok {
u.c[txHash] = map[uint32]*dbtypes.UTXOData{
txIndex: {
Addresses: addrs,
Value: val,
},
}
} else {
txUTXOVals[txIndex] = &dbtypes.UTXOData{
Addresses: addrs,
Value: val,
}
}
}
// Set stores the addresses and amount in a UTXOData entry in the cache for the
// given outpoint.
func (u *utxoStore) Set(txHash string, txIndex uint32, addrs []string, val int64) {
u.Lock()
defer u.Unlock()
u.set(txHash, txIndex, addrs, val)
}
// Reinit re-initializes the utxoStore with the given UTXOs.
func (u *utxoStore) Reinit(utxos []dbtypes.UTXO) {
u.Lock()
defer u.Unlock()
// Pre-allocate the transaction hash map assuming the number of unique
// transaction hashes in input is roughly 2/3 of the number of UTXOs.
prealloc := 2 * len(utxos) / 3
u.c = make(map[string]map[uint32]*dbtypes.UTXOData, prealloc)
for i := range utxos {
u.set(utxos[i].TxHash, utxos[i].TxIndex, utxos[i].Addresses, utxos[i].Value)
}
}
// 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
}
type cacheLocks struct {
bal *cache.CacheLock
rows *cache.CacheLock
rowsMerged *cache.CacheLock
utxo *cache.CacheLock
}
// BlockGetter implements a few basic blockchain data retrieval functions. It is
// like rpcutils.BlockFetcher except that it must also implement
// GetBlockChainInfo.
type BlockGetter interface {
// rpcutils.BlockFetcher implements GetBestBlock, GetBlock, GetBlockHash,
// and GetBlockHeaderVerbose.
rpcutils.BlockFetcher
// GetBlockChainInfo is required for a legacy upgrade involving agendas.
GetBlockChainInfo() (*chainjson.GetBlockChainInfoResult, error)
}
// ChainDB provides an interface for storing and manipulating extracted
// blockchain data in a PostgreSQL database.
type ChainDB struct {
ctx context.Context
queryTimeout time.Duration
db *sql.DB
mp rpcutils.MempoolAddressChecker
chainParams *chaincfg.Params
devAddress string
dupChecks bool
bestBlock *BestBlock
lastBlock map[chainhash.Hash]uint64
stakeDB *stakedb.StakeDatabase
unspentTicketCache *TicketTxnIDGetter
AddressCache *cache.AddressCache
CacheLocks cacheLocks
devPrefetch bool
InBatchSync bool
InReorg bool
tpUpdatePermission map[dbtypes.TimeBasedGrouping]*trylock.Mutex
utxoCache utxoStore
deployments *ChainDeployments
piparser ProposalsFetcher
proposalsSync lastSync
cockroach bool
MPC *mempool.MempoolDataCache
// BlockCache stores apitypes.BlockDataBasic and apitypes.StakeInfoExtended
// in StoreBlock for quick retrieval without a DB query.
BlockCache *apitypes.APICache
heightClients []chan uint32
shutdownEcrdata func()
Client *rpcclient.Client
tipMtx sync.RWMutex
tipSummary *apitypes.BlockDataBasic
lastExplorerBlock struct {
sync.Mutex
hash string
blockInfo *exptypes.BlockInfo
// Somewhat unrelated, difficulties is a map of timestamps to mining
// difficulties. It is in this cache struct since these values are
// commonly retrieved when the explorer block is updated.
difficulties map[int64]float64
}
}
// ChainDeployments is mutex-protected blockchain deployment data.
type ChainDeployments struct {
mtx sync.RWMutex
chainInfo *dbtypes.BlockChainData
}
// BestBlock is mutex-protected block hash and height.
type BestBlock struct {
mtx sync.RWMutex
height int64
hash string
}
// lastSync defines the latest sync time for the proposal votes sync.
type lastSync struct {
mtx sync.RWMutex
syncTime time.Time
}
func (pgb *ChainDB) timeoutError() string {
return fmt.Sprintf("%s after %v", dbtypes.TimeoutPrefix, pgb.queryTimeout)
}
// replaceCancelError will replace the generic error strings that can occur when
// a PG query is canceled (dbtypes.PGCancelError) or a context deadline is
// exceeded (dbtypes.CtxDeadlineExceeded from context.DeadlineExceeded).
func (pgb *ChainDB) replaceCancelError(err error) error {
if err == nil {
return err
}
patched := err.Error()
if strings.Contains(patched, dbtypes.PGCancelError) {
patched = strings.Replace(patched, dbtypes.PGCancelError,
pgb.timeoutError(), -1)
} else if strings.Contains(patched, dbtypes.CtxDeadlineExceeded) {
patched = strings.Replace(patched, dbtypes.CtxDeadlineExceeded,
pgb.timeoutError(), -1)
} else {
return err
}
return errors.New(patched)
}
// MissingSideChainBlocks identifies side chain blocks that are missing from the
// DB. Side chains known to ecrd 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 (pgb *ChainDB) MissingSideChainBlocks() ([]dbtypes.SideChain, int, error) {
// First get the side chain tips (head blocks).
tips, err := rpcutils.SideChains(pgb.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(pgb.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 := pgb.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
}
// TicketTxnIDGetter provides a cache for DB row IDs of tickets.
type TicketTxnIDGetter struct {
mtx 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.mtx.RLock()
dbID, ok := t.idCache[txid]
t.mtx.RUnlock()
if ok {
if expire {
t.mtx.Lock()
delete(t.idCache, txid)
t.mtx.Unlock()
}
return dbID, nil
}
// Cache miss. Get the row id by hash from the tickets table.
log.Tracef("Cache miss for %s.", txid)
return RetrieveTicketIDByHashNoCancel(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.mtx.Lock()
defer t.mtx.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.mtx.Lock()
defer t.mtx.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
QueryTimeout time.Duration
}
// NewChainDB constructs a ChainDB for the given connection and Eacred network
// parameters. By default, duplicate row checks on insertion are enabled. See
// NewChainDBWithCancel to enable context cancellation of running queries.
// proposalsUpdateChan is used to manage politeia update notifications trigger
// between the notifier and the handler method. A non-nil BlockGetter is only
// needed if database upgrades are required.
func NewChainDB(dbi *DBInfo, params *chaincfg.Params, stakeDB *stakedb.StakeDatabase,
devPrefetch, hidePGConfig bool, addrCacheCap int, mp rpcutils.MempoolAddressChecker,
parser ProposalsFetcher, client *rpcclient.Client, shutdown func()) (*ChainDB, error) {
ctx := context.Background()
chainDB, err := NewChainDBWithCancel(ctx, dbi, params, stakeDB,
devPrefetch, hidePGConfig, addrCacheCap, mp, parser, client, shutdown)
if err != nil {
return nil, err
}
return chainDB, nil
}
// NewChainDBWithCancel constructs a cancellation-capable ChainDB for the given
// connection and Eacred network parameters. By default, duplicate row checks on
// insertion are enabled. See EnableDuplicateCheckOnInsert to change this
// behavior. NewChainDB creates context that cannot be cancelled
// (context.Background()) except by the pg timeouts. If it is necessary to
// cancel queries with CTRL+C, for example, use NewChainDBWithCancel. A non-nil
// BlockGetter is only needed if database upgrades are required.
func NewChainDBWithCancel(ctx context.Context, dbi *DBInfo, params *chaincfg.Params,
stakeDB *stakedb.StakeDatabase, devPrefetch, hidePGConfig bool, addrCacheCap int,
mp rpcutils.MempoolAddressChecker, parser ProposalsFetcher, client *rpcclient.Client,
shutdown func()) (*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
}
// Put the PostgreSQL time zone in UTC.
var initTZ string
initTZ, err = CheckCurrentTimeZone(db)
if err != nil {
return nil, err
}
if initTZ != "UTC" {
log.Infof("Switching PostgreSQL time zone to UTC for this session.")
if _, err = db.Exec(`SET TIME ZONE UTC`); err != nil {
return nil, fmt.Errorf("Failed to set time zone to UTC: %v", err)
}
}
pgVersion, err := RetrievePGVersion(db)
if err != nil {
return nil, err
}
log.Info(pgVersion)
cockroach := strings.Contains(pgVersion, "CockroachDB")
// Optionally logs the PostgreSQL configuration.
if !cockroach && !hidePGConfig {
perfSettings, err := RetrieveSysSettingsPerformance(db)
if err != nil {
return nil, err
}
log.Infof("postgres configuration settings:\n%v", perfSettings)
servSettings, err := RetrieveSysSettingsServer(db)
if err != nil {
return nil, err
}
log.Infof("postgres server settings:\n%v", servSettings)
}
// Check the synchronous_commit setting.
if !cockroach {
syncCommit, err := RetrieveSysSettingSyncCommit(db)
if err != nil {
return nil, err
}
if syncCommit != "off" {
log.Warnf(`PERFORMANCE ISSUE! The synchronous_commit setting is "%s". `+
`Changing it to "off".`, syncCommit)
// Turn off synchronous_commit.
if err = SetSynchronousCommit(db, "off"); err != nil {
return nil, fmt.Errorf("failed to set synchronous_commit: %v", err)
}
// Verify that the setting was changed.
if syncCommit, err = RetrieveSysSettingSyncCommit(db); err != nil {
return nil, err
}
if syncCommit != "off" {
log.Errorf(`Failed to set synchronous_commit="off". Check PostgreSQL user permissions.`)
}
}
} else {
// Force CockroachDB to use a real sequence when creating a table with a
// SERIAL column.
_, err = db.Exec("SET experimental_serial_normalization = sql_sequence;")
if err != nil {
return nil, fmt.Errorf("failed to set experimental_serial_normalization: %v", err)
}
// Prevent too many versions of nextval() during bulk inserts using
// autoincrement of row primary key by lowering garbage the collection
// interval (from 25 hours!).
crdbGCInterval := 1200 // 20 minutes between garbage collections
_, err = db.Exec(fmt.Sprintf(`ALTER DATABASE %s CONFIGURE ZONE USING gc.ttlseconds=$1;`,
dbi.DBName), crdbGCInterval)
if err != nil {
// In secure mode, the user may need permissions to modify zones. e.g.
// GRANT UPDATE ON TABLE ecrdata_mainnet.crdb_internal.zones TO ecrdata_user;
return nil, fmt.Errorf(`failed to set gc.ttlseconds=%d for database "%s": %v`,
crdbGCInterval, dbi.DBName, err)
}
}
// Perform any necessary database schema upgrades.
var doLegacyUpgrade bool
dbVer, compatAction, err := versionCheck(db)
switch err {
case nil:
if compatAction == OK {
// meta table present and no upgrades required
log.Infof("DB schema version %v", dbVer)
break
}
// Upgrades required
if client == nil {
return nil, fmt.Errorf("a rpcclient.Client is required for database upgrades")
}
// Do upgrades required by meta table versioning.
log.Infof("DB schema version %v upgrading to version %v", dbVer, targetDatabaseVersion)
upgrader := NewUpgrader(ctx, db, client, stakeDB)
success, err := upgrader.UpgradeDatabase()
if err != nil {
return nil, fmt.Errorf("failed to upgrade database: %v", err)
}
if !success {
return nil, fmt.Errorf("failed to upgrade database (upgrade not supported?)")
}
case tablesNotFoundErr:
// Empty database (no blocks table). Proceed to setupTables.
log.Infof(`Empty database "%s". Creating tables...`, dbi.DBName)
if err = CreateTables(db); err != nil {
return nil, fmt.Errorf("failed to create tables: %v", err)
}
err = insertMetaData(db, &metaData{
netName: params.Name,
currencyNet: uint32(params.Net),
bestBlockHeight: -1,
dbVer: *targetDatabaseVersion,
})
if err != nil {
return nil, fmt.Errorf("insertMetaData failed: %v", err)
}
case metaNotFoundErr:
log.Infof("Legacy DB versioning found.")
doLegacyUpgrade = true
if client == nil {
return nil, fmt.Errorf("a rpcclient.Client is required for database upgrades")
}
// Create any missing tables with version comments for legacy upgrades.
if err = CreateTablesLegacy(db); err != nil {
return nil, fmt.Errorf("failed to create tables with legacy versioning: %v", err)
}
default:
return nil, err
}
// Get the best block height from the blocks table.
bestHeight, bestHash, err := RetrieveBestBlock(ctx, db)
if err != nil {
return nil, fmt.Errorf("RetrieveBestBlock: %v", err)
}
// NOTE: Once legacy versioned tables are no longer in use, use the height
// and hash from DBBestBlock instead.
// Unless legacy table versioning is still in use, verify that the best
// block in the meta table is the same as in the blocks table. If the blocks
// table is ahead of the meta table, it is likely that the data for the best
// block was not fully inserted into all tables. Purge data back to the meta
// table's best block height. Also purge if the hashes do not match.
if !doLegacyUpgrade {
dbHash, dbHeightInit, err := DBBestBlock(ctx, db)
if err != nil {
return nil, fmt.Errorf("DBBestBlock: %v", err)
}
// Best block height in the transactions table (written to even before
// the blocks table).
bestTxsBlockHeight, bestTxsBlockHash, err :=
RetrieveTxsBestBlockMainchain(ctx, db)
if err != nil {
return nil, err
}
if bestTxsBlockHeight > bestHeight {
bestHeight = bestTxsBlockHeight
bestHash = bestTxsBlockHash
}
// The meta table's best block height should never end up larger than
// the blocks table's best block height, but purge a block anyway since
// something went awry. This will update the best block in the meta
// table to match the blocks table, allowing ecrdata to start.
if dbHeightInit > bestHeight {
log.Warnf("Best block height in meta table (%d) "+
"greater than best height in blocks table (%d)!",
dbHeightInit, bestHeight)
_, bestHeight, bestHash, err = DeleteBestBlock(ctx, db)
if err != nil {
return nil, fmt.Errorf("DeleteBestBlock: %v", err)
}
dbHash, dbHeightInit, err = DBBestBlock(ctx, db)
if err != nil {
return nil, fmt.Errorf("DBBestBlock: %v", err)
}
}
// Purge blocks if the best block hashes do not match, and until the
// best block height in the data tables is less than or equal to the
// starting height in the meta table.
log.Debugf("meta height %d / blocks height %d", dbHeightInit, bestHeight)
for dbHash != bestHash || dbHeightInit < bestHeight {
log.Warnf("Purging best block %s (%d).", bestHash, bestHeight)
// Delete the best block across all tables, updating the best block
// in the meta table.
_, bestHeight, bestHash, err = DeleteBestBlock(ctx, db)
if err != nil {
return nil, fmt.Errorf("DeleteBestBlock: %v", err)
}
if bestHeight == -1 {
break
}
// Now dbHash must equal bestHash. If not, DeleteBestBlock failed to
// update the meta table.
dbHash, _, err = DBBestBlock(ctx, db)
if err != nil {
return nil, fmt.Errorf("DBBestBlock: %v", err)
}
if dbHash != bestHash {
return nil, fmt.Errorf("best block hash in meta and blocks tables do not match: "+
"%s != %s", dbHash, bestHash)
}
}
}
// Project fund address of the current network
var projectFundAddress string
if projectFundAddress, err = dbtypes.DevSubsidyAddress(params); err != nil {
log.Warnf("ChainDB.NewChainDB: %v", err)
}
log.Infof("Pre-loading unspent ticket info for InsertVote optimization.")
unspentTicketCache := NewTicketTxnIDGetter(db)
unspentTicketDbIDs, unspentTicketHashes, err := RetrieveUnspentTickets(ctx, 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.TimeBasedGrouping]*trylock.Mutex)
for g := range dbtypes.TimeBasedGroupings {
tpUpdatePermissions[g] = new(trylock.Mutex)
}
// If a query timeout is not set (i.e. zero), default to 24 hrs for
// essentially no timeout.
queryTimeout := dbi.QueryTimeout
if queryTimeout <= 0 {
queryTimeout = time.Hour
}
log.Infof("Setting PostgreSQL DB statement timeout to %v.", queryTimeout)
bestBlock := &BestBlock{
height: bestHeight,
hash: bestHash,
}
// Create the address cache with the given capacity. The project fund
// address is set to prevent purging its data when cache reaches capacity.
addrCache := cache.NewAddressCache(addrCacheCap)
addrCache.ProjectAddress = projectFundAddress
chainDB := &ChainDB{
ctx: ctx,
queryTimeout: queryTimeout,
db: db,
mp: mp,
chainParams: params,
devAddress: projectFundAddress,
dupChecks: true,
bestBlock: bestBlock,
lastBlock: make(map[chainhash.Hash]uint64),
stakeDB: stakeDB,
unspentTicketCache: unspentTicketCache,
AddressCache: addrCache,
CacheLocks: cacheLocks{cache.NewCacheLock(), cache.NewCacheLock(), cache.NewCacheLock(), cache.NewCacheLock()},
devPrefetch: devPrefetch,
tpUpdatePermission: tpUpdatePermissions,
utxoCache: newUtxoStore(5e4),
deployments: new(ChainDeployments),
piparser: parser,
cockroach: cockroach,
MPC: new(mempool.MempoolDataCache),
BlockCache: apitypes.NewAPICache(1e4),
heightClients: make([]chan uint32, 0),
shutdownEcrdata: shutdown,
Client: client,
}
chainDB.lastExplorerBlock.difficulties = make(map[int64]float64)
// Update the current chain state in the ChainDB
if client != nil {
bci, err := chainDB.BlockchainInfo()
if err != nil {
return nil, fmt.Errorf("failed to fetch the latest blockchain info")
}
chainDB.UpdateChainState(bci)
}
// If loading a DB with the legacy versioning system, fully upgrade prior to
// migrating to meta table versioning.
if doLegacyUpgrade {
log.Infof("Performing legacy DB version check and upgrade.")
if err = chainDB.VersionCheck(client); err != nil {
return chainDB, fmt.Errorf("legacy DB version check/upgrade failed: %v", err)
}
log.Infof("Migrating DB versioning scheme to meta table versioning...")
if err = CreateTable(db, "meta"); err != nil {
return chainDB, fmt.Errorf(`failed to create "meta" table: %v`, err)
}
err = insertMetaData(db, &metaData{
netName: params.Name,
currencyNet: uint32(params.Net),
bestBlockHeight: bestBlock.height,
bestBlockHash: bestBlock.hash,
dbVer: *legacyDatabaseVersion,
ibdComplete: true, // We don't know this, but assume it is done.
})
if err != nil {
return chainDB, fmt.Errorf("insertMetaData failed: %v", err)
}
// Now run any upgrades from legacyDatabaseVersion to
// targetDatabaseVersion.
upgrader := NewUpgrader(ctx, db, client, stakeDB)
success, err := upgrader.UpgradeDatabase()
if err != nil {
return chainDB, fmt.Errorf("failed to upgrade legacy database: %v", err)
} else if !success {
return chainDB, fmt.Errorf("failed to upgrade legacy database (upgrade not supported?)")
}
}
return chainDB, nil
}
// StartPiparserHandler controls how piparser update handler will be initiated.
// This handler should to be run once only when the first sync after startup completes.
func (pgb *ChainDB) StartPiparserHandler() {
if atomic.CompareAndSwapUint32(&piParserCounter, 0, isPiparserRunning) {
// Start the proposal updates handler async method.
pgb.proposalsUpdateHandler()
log.Info("Piparser instance to handle updates is now active")
} else {
log.Error("piparser instance is already running, another one cannot be activated")
}
}
// Close closes the underlying sql.DB connection to the database.
func (pgb *ChainDB) Close() error {
return pgb.db.Close()
}
// SqlDB returns the underlying sql.DB, which should not be used directly unless
// you know what you are doing (if you have to ask...).
func (pgb *ChainDB) SqlDB() *sql.DB {
return pgb.db
}
// InitUtxoCache resets the UTXO cache with the given slice of UTXO data.
func (pgb *ChainDB) InitUtxoCache(utxos []dbtypes.UTXO) {
pgb.utxoCache.Reinit(utxos)
}
// 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
}
// UseMempoolChecker assigns a MempoolAddressChecker for searching mempool for
// transactions involving a certain address.
func (pgb *ChainDB) UseMempoolChecker(mp rpcutils.MempoolAddressChecker) {
pgb.mp = mp
}
// EnableDuplicateCheckOnInsert specifies whether SQL insertions should check
// for row conflicts (duplicates), and avoid adding or updating.
func (pgb *ChainDB) EnableDuplicateCheckOnInsert(dupCheck bool) {
if pgb == nil {
return
}
pgb.dupChecks = dupCheck
}
var (
// metaNotFoundErr is the error from versionCheck when the meta table does
// not exist.
metaNotFoundErr = errors.New("meta table not found")
// tablesNotFoundErr is the error from versionCheck when any of the tables
// do not exist.
tablesNotFoundErr = errors.New("tables not found")
)
// versionCheck attempts to retrieve the database version from the meta table,
// along with a CompatAction upgrade plan. If any of the regular data tables do
// not exist, a tablesNotFoundErr error is returned to indicated that the tables
// do not exist (or are partially created.) If the data tables exist but the
// meta table does not exist, a metaNotFoundErr error is returned to indicate
// that the legacy table versioning system is in use.
func versionCheck(db *sql.DB) (*DatabaseVersion, CompatAction, error) {
// Detect an empty database, only checking for the "blocks" table since some
// of the tables are created by schema upgrades (e.g. proposal_votes).
exists, err := TableExists(db, "blocks")
if err != nil {
return nil, Unknown, err
}
if !exists {
return nil, Unknown, tablesNotFoundErr
}
// The meta table stores the database schema version.
exists, err = TableExists(db, "meta")
if err != nil {
return nil, Unknown, err
}
// If there is no meta table, this could indicate the legacy table
// versioning system is still in used. Return the MetaNotFoundErr error.
if !exists {
return nil, Unknown, metaNotFoundErr
}
// Retrieve the database version from the meta table.
dbVer, err := DBVersion(db)
if err != nil {
return nil, Unknown, fmt.Errorf("DBVersion failure: %v", err)
}
// Return the version, and an upgrade plan to reach targetDatabaseVersion.
return &dbVer, dbVer.NeededToReach(targetDatabaseVersion), nil
}
// DropTables drops (deletes) all of the known ecrdata tables.
func (pgb *ChainDB) DropTables() {
DropTables(pgb.db)
}
// SideChainBlocks retrieves all known side chain blocks.
func (pgb *ChainDB) SideChainBlocks() ([]*dbtypes.BlockStatus, error) {
ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
defer cancel()
scb, err := RetrieveSideChainBlocks(ctx, pgb.db)
return scb, pgb.replaceCancelError(err)
}
// SideChainTips retrieves the tip/head block for all known side chains.
func (pgb *ChainDB) SideChainTips() ([]*dbtypes.BlockStatus, error) {
ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
defer cancel()
sct, err := RetrieveSideChainTips(ctx, pgb.db)
return sct, pgb.replaceCancelError(err)
}
// DisapprovedBlocks retrieves all blocks disapproved by stakeholder votes.
func (pgb *ChainDB) DisapprovedBlocks() ([]*dbtypes.BlockStatus, error) {
ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
defer cancel()
disb, err := RetrieveDisapprovedBlocks(ctx, pgb.db)
return disb, pgb.replaceCancelError(err)
}
// BlockStatus retrieves the block chain status of the specified block.
func (pgb *ChainDB) BlockStatus(hash string) (dbtypes.BlockStatus, error) {
ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
defer cancel()
bs, err := RetrieveBlockStatus(ctx, pgb.db, hash)
return bs, pgb.replaceCancelError(err)
}
// blockFlags retrieves the block's isValid and isMainchain flags.
func (pgb *ChainDB) blockFlags(ctx context.Context, hash string) (bool, bool, error) {
iv, im, err := RetrieveBlockFlags(ctx, pgb.db, hash)
return iv, im, pgb.replaceCancelError(err)
}
// BlockFlags retrieves the block's isValid and isMainchain flags.
func (pgb *ChainDB) BlockFlags(hash string) (bool, bool, error) {
ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
defer cancel()
return pgb.blockFlags(ctx, hash)
}
// BlockFlagsNoCancel retrieves the block's isValid and isMainchain flags.
func (pgb *ChainDB) BlockFlagsNoCancel(hash string) (bool, bool, error) {
return pgb.blockFlags(context.Background(), hash)
}
// blockChainDbID gets the row ID of the given block hash in the block_chain
// table. The cancellation context is used without timeout.
func (pgb *ChainDB) blockChainDbID(ctx context.Context, hash string) (dbID uint64, err error) {
err = pgb.db.QueryRowContext(ctx, internal.SelectBlockChainRowIDByHash, hash).Scan(&dbID)
err = pgb.replaceCancelError(err)
return
}
// BlockChainDbID gets the row ID of the given block hash in the block_chain
// table. The cancellation context is used without timeout.
func (pgb *ChainDB) BlockChainDbID(hash string) (dbID uint64, err error) {
return pgb.blockChainDbID(pgb.ctx, hash)
}
// BlockChainDbIDNoCancel gets the row ID of the given block hash in the
// block_chain table. The cancellation context is used without timeout.
func (pgb *ChainDB) BlockChainDbIDNoCancel(hash string) (dbID uint64, err error) {
return pgb.blockChainDbID(context.Background(), hash)
}
// RegisterCharts registers chart data fetchers and appenders with the provided
// ChartData.
func (pgb *ChainDB) RegisterCharts(charts *cache.ChartData) {
charts.AddUpdater(cache.ChartUpdater{
Tag: "basic blocks",
Fetcher: pgb.chartBlocks,
Appender: appendChartBlocks,
})
charts.AddUpdater(cache.ChartUpdater{
Tag: "coin supply",
Fetcher: pgb.coinSupply,