/
queries.go
4098 lines (3582 loc) · 131 KB
/
queries.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 Decred developers
// Copyright (c) 2017, The dcrdata developers
// See LICENSE for details.
package dcrpg
import (
"bytes"
"context"
"database/sql"
"encoding/hex"
"fmt"
"math/big"
"strconv"
"strings"
"time"
"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/txscript"
"github.com/decred/dcrd/wire"
apitypes "github.com/decred/dcrdata/api/types/v3"
"github.com/decred/dcrdata/db/cache/v2"
"github.com/decred/dcrdata/db/dbtypes/v2"
"github.com/decred/dcrdata/db/dcrpg/v3/internal"
"github.com/decred/dcrdata/txhelpers/v2"
humanize "github.com/dustin/go-humanize"
"github.com/lib/pq"
)
// DBBestBlock retrieves the best block hash and height from the meta table. The
// error value will never be sql.ErrNoRows; instead with height == -1 indicating
// no data in the meta table.
func DBBestBlock(ctx context.Context, db *sql.DB) (hash string, height int64, err error) {
err = db.QueryRowContext(ctx, internal.SelectMetaDBBestBlock).Scan(&height, &hash)
if err == sql.ErrNoRows {
err = nil
height = -1
}
return
}
// SetDBBestBlock sets the best block hash and height in the meta table.
func SetDBBestBlock(db *sql.DB, hash string, height int64) error {
numRows, err := sqlExec(db, internal.SetMetaDBBestBlock,
"failed to update best block in meta table: ", height, hash)
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("failed to update exactly 1 row in meta table (%d)",
numRows)
}
return nil
}
// IBDComplete indicates whether initial block download was completed according
// to the meta.ibd_complete flag.
func IBDComplete(db *sql.DB) (ibdComplete bool, err error) {
err = db.QueryRow(internal.SelectMetaDBIbdComplete).Scan(&ibdComplete)
return
}
// SetIBDComplete set the ibd_complete (Initial Block Download complete) flag in
// the meta table.
func SetIBDComplete(db SqlExecutor, ibdComplete bool) error {
numRows, err := sqlExec(db, internal.SetMetaDBIbdComplete,
"failed to update ibd_complete in meta table: ", ibdComplete)
if err != nil {
return err
}
if numRows != 1 {
return fmt.Errorf("failed to update exactly 1 row in meta table (%d)",
numRows)
}
return nil
}
// outputCountType defines the modes of the output count chart data.
// outputCountByAllBlocks defines count per block i.e. solo and pooled tickets
// count per block. outputCountByTicketPoolWindow defines the output count per
// given ticket price window
type outputCountType int
const (
outputCountByAllBlocks outputCountType = iota
outputCountByTicketPoolWindow
notOneRowErrMsg = "failed to update exactly 1 row"
)
const (
creditDebitQuery = iota
creditQuery
debitQuery
mergedCreditQuery
mergedDebitQuery
mergedQuery
)
// Maintenance functions
// closeRows closes the input sql.Rows, logging any error.
func closeRows(rows *sql.Rows) {
if e := rows.Close(); e != nil {
log.Errorf("Close of Query failed: %v", e)
}
}
// SqlExecutor is implemented by both sql.DB and sql.Tx.
type SqlExecutor interface {
Exec(query string, args ...interface{}) (sql.Result, error)
}
// sqlExec executes the SQL statement string with any optional arguments, and
// returns the number of rows affected.
func sqlExec(db SqlExecutor, stmt, execErrPrefix string, args ...interface{}) (int64, error) {
res, err := db.Exec(stmt, args...)
if err != nil {
return 0, fmt.Errorf(execErrPrefix + " " + err.Error())
}
if res == nil {
return 0, nil
}
var N int64
N, err = res.RowsAffected()
if err != nil {
return 0, fmt.Errorf(`error in RowsAffected: %v`, err)
}
return N, err
}
// sqlExecStmt executes the prepared SQL statement with any optional arguments,
// and returns the number of rows affected.
func sqlExecStmt(stmt *sql.Stmt, execErrPrefix string, args ...interface{}) (int64, error) {
res, err := stmt.Exec(args...)
if err != nil {
return 0, fmt.Errorf("%v %v", execErrPrefix, err)
}
if res == nil {
return 0, nil
}
var N int64
N, err = res.RowsAffected()
if err != nil {
return 0, fmt.Errorf(`error in RowsAffected: %v`, err)
}
return N, err
}
// ExistsIndex checks if the specified index name exists.
func ExistsIndex(db *sql.DB, indexName string) (exists bool, err error) {
err = db.QueryRow(internal.IndexExists, indexName, "public").Scan(&exists)
if err == sql.ErrNoRows {
err = nil
}
return
}
// IsUniqueIndex checks if the given index name is defined as UNIQUE.
func IsUniqueIndex(db *sql.DB, indexName string) (isUnique bool, err error) {
err = db.QueryRow(internal.IndexIsUnique, indexName, "public").Scan(&isUnique)
return
}
// DeleteDuplicateVins deletes rows in vin with duplicate tx information,
// leaving the one row with the lowest id.
func DeleteDuplicateVins(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate vins: "
existsIdx, err := ExistsIndex(db, "uix_vin")
if err != nil {
return 0, err
}
if !existsIdx {
return sqlExec(db, internal.DeleteVinsDuplicateRows, execErrPrefix)
}
isuniq, err := IsUniqueIndex(db, "uix_vin")
if err != nil && err != sql.ErrNoRows {
return 0, err
}
if isuniq {
return 0, nil
}
return sqlExec(db, internal.DeleteVinsDuplicateRows, execErrPrefix)
}
func deleteDupVinsBrute(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate vins: "
// CockroachDB doesn't have CREATE TABLE .. (LIKE table), so we have to get
// the CREATE TABLE statement from the existing vins table.
var createStmt string
err := db.QueryRow(internal.ShowCreateVinsTable).Scan(&createStmt)
if err != nil {
err = fmt.Errorf("%s%v", execErrPrefix, err)
return 0, err
}
createStmt = strings.Replace(createStmt, "CREATE TABLE vins",
"CREATE TABLE vins_temp", 1)
var N0 int64
err = db.QueryRow(`SELECT COUNT(*) FROM vins;`).Scan(&N0)
if err != nil {
return 0, err
}
// Create the "vins_temp" table.
_, err = sqlExec(db, createStmt, execErrPrefix)
if err != nil {
return 0, err
}
// Populate vins_temp with the unique rows.
var N int64
N, err = sqlExec(db, internal.DistinctVinsToTempTable, execErrPrefix)
if err != nil {
return 0, err
}
// Drop the original vins table.
err = dropTable(db, "vins")
if err != nil {
return 0, err
}
// Rename vins_temp to vins.
_, err = sqlExec(db, internal.RenameVinsTemp, execErrPrefix)
if err != nil {
return 0, err
}
return N0 - N, nil
}
func deleteDupVinsAlt(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate vins: "
rows, err := db.Query(internal.SelectVinDupIDs)
if err != nil {
err = fmt.Errorf("%s%v", execErrPrefix, err)
return 0, err
}
var deleteIDs []int64
for rows.Next() {
var dupIDs []int64
if err = rows.Scan(&dupIDs); err != nil {
err = fmt.Errorf("%s%v", execErrPrefix, err)
return 0, err
}
fmt.Println(dupIDs)
if len(dupIDs) > 1 {
deleteIDs = append(deleteIDs, dupIDs[1:]...)
}
}
fmt.Println(deleteIDs)
// Delete the duplicate rows.
var N int64
N, err = sqlExec(db, internal.DeleteVinRows, execErrPrefix, deleteIDs)
if err != nil {
return 0, err
}
return N, nil
}
// DeleteDuplicateVinsCockroach deletes rows in vin with duplicate tx
// information, leaving the one row with the lowest id.
func DeleteDuplicateVinsCockroach(db *sql.DB) (int64, error) {
existsIdx, err := ExistsIndex(db, "uix_vin")
if err != nil {
return 0, err
}
if !existsIdx {
return deleteDupVinsBrute(db)
}
isuniq, err := IsUniqueIndex(db, "uix_vin")
if err != nil && err != sql.ErrNoRows {
return 0, err
}
if isuniq {
return 0, nil
}
return deleteDupVinsBrute(db)
}
// DeleteDuplicateVouts deletes rows in vouts with duplicate tx information,
// leaving the one row with the lowest id.
func DeleteDuplicateVouts(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate vouts: "
existsIdx, err := ExistsIndex(db, "uix_vout_txhash_ind")
if err != nil {
return 0, err
} else if !existsIdx {
return sqlExec(db, internal.DeleteVoutDuplicateRows, execErrPrefix)
}
if isuniq, err := IsUniqueIndex(db, "uix_vout_txhash_ind"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
return sqlExec(db, internal.DeleteVoutDuplicateRows, execErrPrefix)
}
func deleteDupVoutsBrute(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate vouts: "
// CockroachDB doesn't have CREATE TABLE .. (LIKE table), so we have to get
// the CREATE TABLE statement from the existing vins table.
var createStmt string
err := db.QueryRow(internal.ShowCreateVoutsTable).Scan(&createStmt)
if err != nil {
err = fmt.Errorf("%s%v", execErrPrefix, err)
return 0, err
}
createStmt = strings.Replace(createStmt, "CREATE TABLE vouts",
"CREATE TABLE vouts_temp", 1)
var N0 int64
err = db.QueryRow(`SELECT COUNT(*) FROM vouts;`).Scan(&N0)
if err != nil {
return 0, err
}
// Create the "vouts_temp" table.
_, err = sqlExec(db, createStmt, execErrPrefix)
if err != nil {
return 0, err
}
// Populate vouts_temp with the unique rows.
var N int64
N, err = sqlExec(db, internal.DistinctVoutsToTempTable, execErrPrefix)
if err != nil {
return 0, err
}
// Drop the original vouts table.
err = dropTable(db, "vouts")
if err != nil {
return 0, err
}
// Rename vouts_temp to vouts.
_, err = sqlExec(db, internal.RenameVoutsTemp, execErrPrefix)
if err != nil {
return 0, err
}
return N0 - N, nil
}
func deleteDupVoutsAlt(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate vouts: "
rows, err := db.Query(internal.SelectVoutDupIDs)
if err != nil {
err = fmt.Errorf("%s%v", execErrPrefix, err)
return 0, err
}
var deleteIDs []int64
for rows.Next() {
var dupIDs []int64
if err = rows.Scan(&dupIDs); err != nil {
err = fmt.Errorf("%s%v", execErrPrefix, err)
return 0, err
}
fmt.Println(dupIDs)
if len(dupIDs) > 1 {
deleteIDs = append(deleteIDs, dupIDs[1:]...)
}
}
fmt.Println(deleteIDs)
// Delete the duplicate rows.
var N int64
N, err = sqlExec(db, internal.DeleteVoutRows, execErrPrefix, deleteIDs)
if err != nil {
return 0, err
}
return N, nil
}
// DeleteDuplicateVoutsCockroach deletes rows in vouts with duplicate tx
// information, leaving the one row with the highest id.
func DeleteDuplicateVoutsCockroach(db *sql.DB) (int64, error) {
existsIdx, err := ExistsIndex(db, "uix_vout_txhash_ind")
if err != nil {
return 0, err
}
if !existsIdx {
return deleteDupVoutsBrute(db)
}
isuniq, err := IsUniqueIndex(db, "uix_vout_txhash_ind")
if err != nil && err != sql.ErrNoRows {
return 0, err
}
if isuniq {
return 0, nil
}
return deleteDupVoutsBrute(db)
}
// DeleteDuplicateTxns deletes rows in transactions with duplicate tx-block
// hashes, leaving the one row with the lowest id.
func DeleteDuplicateTxns(db *sql.DB) (int64, error) {
execErrPrefix := "failed to delete duplicate transactions: "
existsIdx, err := ExistsIndex(db, "uix_tx_hashes")
if err != nil {
return 0, err
} else if !existsIdx {
return sqlExec(db, internal.DeleteTxDuplicateRows, execErrPrefix)
}
if isuniq, err := IsUniqueIndex(db, "uix_tx_hashes"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
return sqlExec(db, internal.DeleteTxDuplicateRows, execErrPrefix)
}
// DeleteDuplicateTickets deletes rows in tickets with duplicate tx-block
// hashes, leaving the one row with the lowest id.
func DeleteDuplicateTickets(db *sql.DB) (int64, error) {
if isuniq, err := IsUniqueIndex(db, "uix_ticket_hashes_index"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
execErrPrefix := "failed to delete duplicate tickets: "
return sqlExec(db, internal.DeleteTicketsDuplicateRows, execErrPrefix)
}
// DeleteDuplicateVotes deletes rows in votes with duplicate tx-block hashes,
// leaving the one row with the lowest id.
func DeleteDuplicateVotes(db *sql.DB) (int64, error) {
if isuniq, err := IsUniqueIndex(db, "uix_votes_hashes_index"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
execErrPrefix := "failed to delete duplicate votes: "
return sqlExec(db, internal.DeleteVotesDuplicateRows, execErrPrefix)
}
// DeleteDuplicateMisses deletes rows in misses with duplicate tx-block hashes,
// leaving the one row with the lowest id.
func DeleteDuplicateMisses(db *sql.DB) (int64, error) {
if isuniq, err := IsUniqueIndex(db, "uix_misses_hashes_index"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
execErrPrefix := "failed to delete duplicate misses: "
return sqlExec(db, internal.DeleteMissesDuplicateRows, execErrPrefix)
}
// DeleteDuplicateAgendas deletes rows in agendas with duplicate names leaving
// the one row with the lowest id.
func DeleteDuplicateAgendas(db *sql.DB) (int64, error) {
if isuniq, err := IsUniqueIndex(db, "uix_agendas_name"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
execErrPrefix := "failed to delete duplicate agendas: "
return sqlExec(db, internal.DeleteAgendasDuplicateRows, execErrPrefix)
}
// DeleteDuplicateAgendaVotes deletes rows in agenda_votes with duplicate
// votes-row-id and agendas-row-id leaving the one row with the lowest id.
func DeleteDuplicateAgendaVotes(db *sql.DB) (int64, error) {
if isuniq, err := IsUniqueIndex(db, "uix_agenda_votes"); err != nil && err != sql.ErrNoRows {
return 0, err
} else if isuniq {
return 0, nil
}
execErrPrefix := "failed to delete duplicate agenda_votes: "
return sqlExec(db, internal.DeleteAgendaVotesDuplicateRows, execErrPrefix)
}
// --- stake (votes, tickets, misses) tables ---
// InsertTickets takes a slice of *dbtypes.Tx and corresponding DB row IDs for
// transactions, extracts the tickets, and inserts the tickets into the
// database. Outputs are a slice of DB row IDs of the inserted tickets, and an
// error.
func InsertTickets(db *sql.DB, dbTxns []*dbtypes.Tx, txDbIDs []uint64, checked, updateExistingRecords bool) ([]uint64, []*dbtypes.Tx, error) {
dbtx, err := db.Begin()
if err != nil {
return nil, nil, fmt.Errorf("unable to begin database transaction: %v", err)
}
// Prepare ticket insert statement, optionally updating a row if it conflicts
// with the unique index on (tx_hash, block_hash).
stmt, err := dbtx.Prepare(internal.MakeTicketInsertStatement(checked, updateExistingRecords))
if err != nil {
log.Errorf("Ticket INSERT prepare: %v", err)
_ = dbtx.Rollback() // try, but we want the Prepare error back
return nil, nil, err
}
// Choose only SSTx
var ticketTx []*dbtypes.Tx
var ticketDbIDs []uint64
for i, tx := range dbTxns {
if tx.TxType == int16(stake.TxTypeSStx) {
ticketTx = append(ticketTx, tx)
ticketDbIDs = append(ticketDbIDs, txDbIDs[i])
}
}
// Insert each ticket
ids := make([]uint64, 0, len(ticketTx))
for i, tx := range ticketTx {
// Reference Vouts[0] to determine stakesubmission address and if multisig
var stakesubmissionAddress string
var isMultisig bool
if len(tx.Vouts) > 0 {
if len(tx.Vouts[0].ScriptPubKeyData.Addresses) > 0 {
stakesubmissionAddress = tx.Vouts[0].ScriptPubKeyData.Addresses[0]
}
// scriptSubClass, _, _, _ := txscript.ExtractPkScriptAddrs(
// tx.Vouts[0].Version, tx.Vouts[0].ScriptPubKey[1:], chainParams)
scriptSubClass, _ := txscript.GetStakeOutSubclass(tx.Vouts[0].ScriptPubKey)
isMultisig = scriptSubClass == txscript.MultiSigTy
}
price := dcrutil.Amount(tx.Vouts[0].Value).ToCoin()
fee := dcrutil.Amount(tx.Fees).ToCoin()
isSplit := tx.NumVin > 1
var id uint64
err := stmt.QueryRow(
tx.TxID, tx.BlockHash, tx.BlockHeight, ticketDbIDs[i],
stakesubmissionAddress, isMultisig, isSplit, tx.NumVin,
price, fee, dbtypes.TicketUnspent, dbtypes.PoolStatusLive,
tx.IsMainchainBlock).Scan(&id)
if err != nil {
if err == sql.ErrNoRows {
continue
}
_ = stmt.Close() // try, but we want the QueryRow error back
if errRoll := dbtx.Rollback(); errRoll != nil {
log.Errorf("Rollback failed: %v", errRoll)
}
return nil, nil, err
}
ids = append(ids, id)
}
// Close prepared statement. Ignore errors as we'll Commit regardless.
_ = stmt.Close()
return ids, ticketTx, dbtx.Commit()
}
// InsertVotes takes a slice of *dbtypes.Tx, which must contain all the stake
// transactions in a block, extracts the votes, and inserts the votes into the
// database. The input MsgBlockPG contains each stake transaction's MsgTx in
// STransactions, and they must be in the same order as the dbtypes.Tx slice.
//
// This function also identifies and stores missed votes using
// msgBlock.Validators, which lists the ticket hashes called to vote on the
// previous block (msgBlock.WinningTickets are the lottery winners to be mined
// in the next block).
//
// The TicketTxnIDGetter is used to get the spent tickets' row IDs. The get
// function, TxnDbID, is called with the expire argument set to false, so that
// subsequent cache lookups by other consumers will succeed.
//
// votesMilestones holds up-to-date blockchain info deployment data.
//
// It also updates the agendas and the agenda_votes tables. Agendas table
// holds the high level information about all agendas that is contained in the
// votingMilestones.MileStone (i.e. Agenda Name, Status and LockedIn, Activated
// & HardForked heights). Agenda_votes table hold the agendas vote choices
// information and references to the agendas and votes tables.
//
// Outputs are slices of DB row IDs for the votes and misses, and an error.
func InsertVotes(db *sql.DB, dbTxns []*dbtypes.Tx, _ /*txDbIDs*/ []uint64, fTx *TicketTxnIDGetter,
msgBlock *MsgBlockPG, checked, updateExistingRecords bool, params *chaincfg.Params,
votesMilestones *dbtypes.BlockChainData) ([]uint64, []*dbtypes.Tx, []string,
[]uint64, map[string]uint64, error) {
// Choose only SSGen txns
msgTxs := msgBlock.STransactions
var voteTxs []*dbtypes.Tx
var voteMsgTxs []*wire.MsgTx
//var voteTxDbIDs []uint64 // not used presently
for i, tx := range dbTxns {
if tx.TxType == int16(stake.TxTypeSSGen) {
voteTxs = append(voteTxs, tx)
voteMsgTxs = append(voteMsgTxs, msgTxs[i])
//voteTxDbIDs = append(voteTxDbIDs, txDbIDs[i])
if tx.TxID != msgTxs[i].TxHash().String() {
return nil, nil, nil, nil, nil, fmt.Errorf("txid of dbtypes.Tx does not match that of msgTx")
}
}
}
if len(voteTxs) == 0 {
return nil, nil, nil, nil, nil, nil
}
// Start DB transaction.
dbtx, err := db.Begin()
if err != nil {
return nil, nil, nil, nil, nil, fmt.Errorf("unable to begin database transaction: %v", err)
}
// Prepare vote insert statement, optionally updating a row if it conflicts
// with the unique index on (tx_hash, block_hash).
voteInsert := internal.MakeVoteInsertStatement(checked, updateExistingRecords)
voteStmt, err := dbtx.Prepare(voteInsert)
if err != nil {
log.Errorf("Votes INSERT prepare: %v", err)
_ = dbtx.Rollback() // try, but we want the Prepare error back
return nil, nil, nil, nil, nil, err
}
// Prepare agenda insert statement.
agendaStmt, err := dbtx.Prepare(internal.MakeAgendaInsertStatement(checked))
if err != nil {
log.Errorf("Agendas INSERT prepare: %v", err)
_ = voteStmt.Close()
_ = dbtx.Rollback() // try, but we want the Prepare error back
return nil, nil, nil, nil, nil, err
}
// Prepare agenda votes insert statement.
agendaVotesInsert := internal.MakeAgendaVotesInsertStatement(checked)
agendaVotesStmt, err := dbtx.Prepare(agendaVotesInsert)
if err != nil {
log.Errorf("Agenda Votes INSERT prepare: %v", err)
_ = voteStmt.Close()
_ = agendaStmt.Close()
_ = dbtx.Rollback() // try, but we want the Prepare error back
return nil, nil, nil, nil, nil, err
}
bail := func() {
// Already up a creek. Just log any Rollback error.
_ = voteStmt.Close()
_ = agendaStmt.Close()
_ = agendaVotesStmt.Close()
if errRoll := dbtx.Rollback(); errRoll != nil {
log.Errorf("Rollback failed: %v", errRoll)
}
}
// If storedAgendas is empty, it attempts to retrieve stored agendas if they
// exists and changes between the storedAgendas and the up-to-date
// votingMilestones.AgendaMileStones map are updated to agendas table and
// storedAgendas cache. This should happen only once, since storedAgendas
// persists the added data.
if len(storedAgendas) == 0 {
var id int64
// Attempt to retrieve agendas from the database.
storedAgendas, err = retrieveAllAgendas(db)
if err != nil {
bail()
return nil, nil, nil, nil, nil,
fmt.Errorf("retrieveAllAgendas failed: : %v", err)
}
for name, d := range votesMilestones.AgendaMileStones {
m, ok := storedAgendas[name]
// Updates the current agenda details to the agendas table and
// storedAgendas map if doesn't exist or when its status has changed.
if !ok || (d.Status != m.Status) || (d.Activated != m.Activated) ||
(d.VotingDone != m.VotingDone) {
err = agendaStmt.QueryRow(name, d.Status, d.VotingDone,
d.Activated, d.HardForked).Scan(&id)
if err != nil {
bail()
return nil, nil, nil, nil, nil,
fmt.Errorf("agenda INSERT failed: : %v", err)
}
storedAgendas[name] = dbtypes.MileStone{
ID: id,
VotingDone: d.VotingDone,
Activated: d.Activated,
HardForked: d.HardForked,
Status: d.Status,
}
}
}
}
// Insert each vote, and build list of missed votes equal to
// setdiff(Validators, votes).
candidateBlockHash := msgBlock.Header.PrevBlock.String()
ids := make([]uint64, 0, len(voteTxs))
spentTicketHashes := make([]string, 0, len(voteTxs))
spentTicketDbIDs := make([]uint64, 0, len(voteTxs))
misses := make([]string, len(msgBlock.Validators))
copy(misses, msgBlock.Validators)
for i, tx := range voteTxs {
msgTx := voteMsgTxs[i]
voteVersion := stake.SSGenVersion(msgTx)
validBlock, voteBits, err := txhelpers.SSGenVoteBlockValid(msgTx)
if err != nil {
bail()
return nil, nil, nil, nil, nil, err
}
voteReward := dcrutil.Amount(msgTx.TxIn[0].ValueIn).ToCoin()
stakeSubmissionAmount := dcrutil.Amount(msgTx.TxIn[1].ValueIn).ToCoin()
stakeSubmissionTxHash := msgTx.TxIn[1].PreviousOutPoint.Hash.String()
spentTicketHashes = append(spentTicketHashes, stakeSubmissionTxHash)
// Lookup the row ID in the transactions table for the ticket purchase.
var ticketTxDbID uint64
if fTx != nil {
ticketTxDbID, err = fTx.TxnDbID(stakeSubmissionTxHash, false)
if err != nil {
bail()
return nil, nil, nil, nil, nil, err
}
}
spentTicketDbIDs = append(spentTicketDbIDs, ticketTxDbID)
// Remove the spent ticket from missed list.
for im := range misses {
if misses[im] == stakeSubmissionTxHash {
misses[im] = misses[len(misses)-1]
misses = misses[:len(misses)-1]
break
}
}
// votes table insert
var votesRowID uint64
err = voteStmt.QueryRow(
tx.BlockHeight, tx.TxID, tx.BlockHash, candidateBlockHash,
voteVersion, voteBits, validBlock.Validity,
stakeSubmissionTxHash, ticketTxDbID, stakeSubmissionAmount,
voteReward, tx.IsMainchainBlock, tx.BlockTime).Scan(&votesRowID)
if err != nil {
if err == sql.ErrNoRows {
continue
}
bail()
return nil, nil, nil, nil, nil, err
}
ids = append(ids, votesRowID)
// agendas table, not modified if not updating existing records.
if checked && !updateExistingRecords {
continue // rest of loop deals with agendas table
}
_, _, _, choices, err := txhelpers.SSGenVoteChoices(msgTx, params)
if err != nil {
bail()
return nil, nil, nil, nil, nil, err
}
var rowID uint64
for _, val := range choices {
// As of here, storedAgendas should not be empty and
// votesMilestones.AgendaMileStones should have cached the latest
// blockchain deployment info. The change in status is detected as
// the change between respective agendas statuses stored in the two
// maps. It is then updated in storedAgendas cache and agendas table.
p := votesMilestones.AgendaMileStones[val.ID]
s := storedAgendas[val.ID]
if s.Status != p.Status {
err = agendaStmt.QueryRow(val.ID, p.Status,
p.VotingDone, p.Activated, p.HardForked).Scan(&s.ID)
if err != nil {
bail()
return nil, nil, nil, nil, nil, fmt.Errorf("agenda INSERT failed: : %v", err)
}
s.Status = p.Status
s.VotingDone = p.VotingDone
s.Activated = p.Activated
s.HardForked = p.HardForked
storedAgendas[val.ID] = s
}
if p.ID == 0 {
p.ID = s.ID
votesMilestones.AgendaMileStones[val.ID] = p
}
var index, err = dbtypes.ChoiceIndexFromStr(val.Choice.Id)
if err != nil {
bail()
return nil, nil, nil, nil, nil, err
}
err = agendaVotesStmt.QueryRow(votesRowID, s.ID, index).Scan(&rowID)
if err != nil {
bail()
return nil, nil, nil, nil, nil, fmt.Errorf("agenda_votes INSERT failed: : %v", err)
}
}
}
// Close prepared statements. Ignore errors as we'll Commit regardless.
_ = voteStmt.Close()
_ = agendaStmt.Close()
_ = agendaVotesStmt.Close()
// If the validators are available, miss accounting should be accurate.
if len(msgBlock.Validators) > 0 && len(ids)+len(misses) != 5 {
fmt.Println(misses)
fmt.Println(voteTxs)
_ = dbtx.Rollback()
panic(fmt.Sprintf("votes (%d) + misses (%d) != 5", len(ids), len(misses)))
}
// Store missed tickets.
missHashMap := make(map[string]uint64)
if len(misses) > 0 {
// Insert misses, optionally updating a row if it conflicts with the
// unique index on (ticket_hash, block_hash).
stmtMissed, err := dbtx.Prepare(internal.MakeMissInsertStatement(checked, updateExistingRecords))
if err != nil {
log.Errorf("Miss INSERT prepare: %v", err)
_ = dbtx.Rollback() // try, but we want the Prepare error back
return nil, nil, nil, nil, nil, err
}
// Insert the miss in the misses table, and store the row ID of the
// new/existing/updated miss.
blockHash := msgBlock.BlockHash().String()
for i := range misses {
var id uint64
err = stmtMissed.QueryRow(
msgBlock.Header.Height, blockHash, candidateBlockHash,
misses[i]).Scan(&id)
if err != nil {
if err == sql.ErrNoRows {
continue
}
_ = stmtMissed.Close() // try, but we want the QueryRow error back
if errRoll := dbtx.Rollback(); errRoll != nil {
log.Errorf("Rollback failed: %v", errRoll)
}
return nil, nil, nil, nil, nil, err
}
missHashMap[misses[i]] = id
}
_ = stmtMissed.Close()
}
return ids, voteTxs, spentTicketHashes, spentTicketDbIDs, missHashMap, dbtx.Commit()
}
// RetrieveMissedVotesInBlock gets a list of ticket hashes that were called to
// vote in the given block, but missed their vote.
func RetrieveMissedVotesInBlock(ctx context.Context, db *sql.DB, blockHash string) (ticketHashes []string, err error) {
var rows *sql.Rows
rows, err = db.QueryContext(ctx, internal.SelectMissesInBlock, blockHash)
if err != nil {
return nil, err
}
defer closeRows(rows)
for rows.Next() {
var hash string
err = rows.Scan(&hash)
if err != nil {
break
}
ticketHashes = append(ticketHashes, hash)
}
return
}
// RetrieveMissesForTicket gets all of the blocks in which the ticket was called
// to place a vote on the previous block. The previous block that would have
// been validated by the vote is not the block data that is returned.
func RetrieveMissesForTicket(ctx context.Context, db *sql.DB, ticketHash string) (blockHashes []string, blockHeights []int64, err error) {
var rows *sql.Rows
rows, err = db.QueryContext(ctx, internal.SelectMissesForTicket, ticketHash)
if err != nil {
return nil, nil, err
}
defer closeRows(rows)
for rows.Next() {
var hash string
var height int64
err = rows.Scan(&height, &hash)
if err != nil {
break
}
blockHashes = append(blockHashes, hash)
blockHeights = append(blockHeights, height)
}
return
}
// RetrieveMissForTicket gets the mainchain block in which the ticket was called
// to place a vote on the previous block. The previous block that would have
// been validated by the vote is not the block data that is returned.
func RetrieveMissForTicket(ctx context.Context, db *sql.DB, ticketHash string) (blockHash string, blockHeight int64, err error) {
err = db.QueryRowContext(ctx, internal.SelectMissesMainchainForTicket,
ticketHash).Scan(&blockHeight, &blockHash)
return
}
// retrieveAllAgendas returns all the current agendas in the db.
func retrieveAllAgendas(db *sql.DB) (map[string]dbtypes.MileStone, error) {
rows, err := db.Query(internal.SelectAllAgendas)
if err != nil {
return nil, err
}
currentMilestones := make(map[string]dbtypes.MileStone)
defer closeRows(rows)
for rows.Next() {
var name string
var m dbtypes.MileStone
err = rows.Scan(&m.ID, &name, &m.Status, &m.VotingDone,
&m.Activated, &m.HardForked)
if err != nil {
break
}
currentMilestones[name] = m
}
return currentMilestones, err
}
// RetrieveAllRevokes gets for all ticket revocations the row IDs (primary
// keys), transaction hashes, block heights. It also gets the row ID in the vins
// table for the first input of the revocation transaction, which should
// correspond to the stakesubmission previous outpoint of the ticket purchase.
// This function is used in UpdateSpendingInfoInAllTickets, so it should not be
// subject to timeouts.
func RetrieveAllRevokes(ctx context.Context, db *sql.DB) (ids []uint64, hashes []string, heights []int64, vinDbIDs []uint64, err error) {
var rows *sql.Rows
rows, err = db.QueryContext(ctx, internal.SelectAllRevokes)
if err != nil {
return nil, nil, nil, nil, err
}
defer closeRows(rows)
for rows.Next() {
var id, vinDbID uint64
var height int64
var hash string
err = rows.Scan(&id, &hash, &height, &vinDbID)
if err != nil {
break
}
ids = append(ids, id)
heights = append(heights, height)
hashes = append(hashes, hash)
vinDbIDs = append(vinDbIDs, vinDbID)
}
return
}
// RetrieveAllVotesDbIDsHeightsTicketDbIDs gets for all votes the row IDs
// (primary keys) in the votes table, the block heights, and the row IDs in the
// tickets table of the spent tickets. This function is used in
// UpdateSpendingInfoInAllTickets, so it should not be subject to timeouts.
func RetrieveAllVotesDbIDsHeightsTicketDbIDs(ctx context.Context, db *sql.DB) (ids []uint64, heights []int64,
ticketDbIDs []uint64, err error) {
var rows *sql.Rows
rows, err = db.QueryContext(ctx, internal.SelectAllVoteDbIDsHeightsTicketDbIDs)
if err != nil {