-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
2715 lines (2422 loc) · 78.1 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tmsqlite
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"runtime/trace"
"slices"
"strings"
"sync/atomic"
"github.com/gordian-engine/gordian/gcrypto"
"github.com/gordian-engine/gordian/tm/tmconsensus"
"github.com/gordian-engine/gordian/tm/tmstore"
)
// Store is a single type satisfying all the [tmstore] interfaces.
type Store struct {
// The string "purego" or "cgo" depending on build tags.
BuildType string
// Due to transaction locking behaviors of sqlite
// (see: https://www.sqlite.org/lang_transaction.html),
// and the way they interact with the Go SQL drivers,
// it is better to maintain two separate connection pools.
ro, rw *sql.DB
hs tmconsensus.HashScheme
reg *gcrypto.Registry
}
func NewOnDiskStore(
ctx context.Context,
dbPath string,
hashScheme tmconsensus.HashScheme,
reg *gcrypto.Registry,
) (*Store, error) {
dbPath = filepath.Clean(dbPath)
if _, err := os.Stat(dbPath); err != nil {
// Create a file for the database;
// if no file exists, then our startup pragma commands fail.
if os.IsNotExist(err) {
// The file did not exist so we need to create it.
// We don't use os.Create since that will truncate an existing file.
// While very unlikely that we would be racing to create a file,
// it is much better to be defensive about it.
f, err := os.OpenFile(dbPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return nil, fmt.Errorf("failed to create empty database file: %w", err)
}
if err := f.Close(); err != nil {
return nil, fmt.Errorf("failed to close new empty database file: %w", err)
}
} else {
return nil, fmt.Errorf("failed to stat path %q: %w", dbPath, err)
}
}
// In contrast to the in-memory store,
// we only have to mark this connection mode as read-write.
// In combination with the SetMaxOpenConns(1) call,
// this allows only a single writer at a time;
// instead of other writers getting an ephemeral "table is locked"
// or "database is locked" error, they will simply block
// while contending for the single available connection.
uri := "file:" + dbPath + "?mode=rw"
// The driver type comes from the sqlitedriver_*.go file
// chosen based on build tags.
rw, err := sql.Open(sqliteDriverType, uri)
if err != nil {
return nil, fmt.Errorf("error opening read-write database: %w", err)
}
rw.SetMaxOpenConns(1)
// Unlike other pragmas, this is persistent,
// and it is only relevant to on-disk databases.
if _, err := rw.ExecContext(ctx, `PRAGMA journal_mode = WAL`); err != nil {
return nil, fmt.Errorf("failed to set journal_mode=WAL: %w", err)
}
if err := pragmasRW(ctx, rw); err != nil {
return nil, err
}
if err := migrate(ctx, rw); err != nil {
return nil, err
}
// Change mode=rw to mode=ro (since we know that was the final query parameter).
uri = uri[:len(uri)-1] + "o"
ro, err := sql.Open(sqliteDriverType, uri)
if err != nil {
return nil, fmt.Errorf("error opening read-only database: %w", err)
}
if err := pragmasRO(ctx, ro); err != nil {
return nil, err
}
return &Store{
BuildType: sqliteBuildType,
rw: rw,
ro: ro,
hs: hashScheme,
reg: reg,
}, nil
}
var inMemNameCounter uint32
func NewInMemStore(
ctx context.Context,
hashScheme tmconsensus.HashScheme,
reg *gcrypto.Registry,
) (*Store, error) {
dbName := fmt.Sprintf("db%0000d", atomic.AddUint32(&inMemNameCounter, 1))
uri := "file:" + dbName +
// Give the "file" a unique name so that multiple connections within one process
// can use the same in-memory database.
// Standard query parameter: https://www.sqlite.org/uri.html#recognized_query_parameters
"?mode=memory" +
// The cache can only be shared or private.
// A private cache means every connection would see a unique database,
// so this must be shared.
"&cache=shared" +
// Both SQLite wrappers support _txlock.
// Immediate effectively takes a write lock on the database
// at the beginning of every transaction.
// https://www.sqlite.org/lang_transaction.html#deferred_immediate_and_exclusive_transactions
"&_txlock=immediate"
// The driver type comes from the sqlitedriver_*.go file
// chosen based on build tags.
rw, err := sql.Open(sqliteDriverType, uri)
if err != nil {
return nil, fmt.Errorf("error opening read-write database: %w", err)
}
// Without limiting it to one open connection,
// we would get frequent "table is locked" errors.
// These errors, as far as I can tell,
// do not automatically resolve with the busy timeout handler.
// So, only allow one active write connection to the database at a time.
rw.SetMaxOpenConns(1)
// We don't set journal mode to WAL with the in-memory store,
// like we do at this point in the on-disk store.
if err := pragmasRW(ctx, rw); err != nil {
return nil, err
}
if err := migrate(ctx, rw); err != nil {
return nil, err
}
// It would be nice if there was a way to mark this connection as read-only,
// but that does not appear possible with the drivers available
// (you have to connect to an on-disk database for that).
// We use an identical connection URI except for removing the txlock directive.
var ok bool
uri, ok = strings.CutSuffix(uri, "&_txlock=immediate")
if !ok {
panic(fmt.Errorf("BUG: failed to cut _txlock suffix from uri %q", uri))
}
ro, err := sql.Open(sqliteDriverType, uri)
if err != nil {
return nil, fmt.Errorf("error opening read-only database: %w", err)
}
if err := pragmasRO(ctx, ro); err != nil {
return nil, err
}
return &Store{
BuildType: sqliteBuildType,
rw: rw,
ro: ro,
hs: hashScheme,
reg: reg,
}, nil
}
func (s *Store) Close() error {
errRO := s.ro.Close()
if errRO != nil {
errRO = fmt.Errorf("error closing read-only database: %w", errRO)
}
errRW := s.rw.Close()
if errRW != nil {
errRW = fmt.Errorf("error closing read-write database: %w", errRW)
}
return errors.Join(errRO, errRW)
}
func (s *Store) SetNetworkHeightRound(
ctx context.Context,
votingHeight uint64, votingRound uint32,
committingHeight uint64, committingRound uint32,
) error {
defer trace.StartRegion(ctx, "SetNetworkHeightRound").End()
_, err := s.rw.ExecContext(
ctx,
`UPDATE mirror SET vh = ?, vr = ?, ch = ?, cr = ? WHERE id=0`,
votingHeight, votingRound, committingHeight, committingRound,
)
return err
}
func (s *Store) NetworkHeightRound(ctx context.Context) (
votingHeight uint64, votingRound uint32,
committingHeight uint64, committingRound uint32,
err error,
) {
defer trace.StartRegion(ctx, "NetworkHeightRound").End()
err = s.ro.QueryRowContext(
ctx,
`SELECT vh, vr, ch, cr FROM mirror WHERE id=0`,
).Scan(
&votingHeight, &votingRound,
&committingHeight, &committingRound,
)
if err == nil &&
votingHeight == 0 && votingRound == 0 &&
committingHeight == 0 && committingRound == 0 {
return 0, 0, 0, 0, tmstore.ErrStoreUninitialized
}
return
}
func (s *Store) SetStateMachineHeightRound(
ctx context.Context,
height uint64, round uint32,
) error {
defer trace.StartRegion(ctx, "SetStateMachineHeightRound").End()
_, err := s.rw.ExecContext(
ctx,
`UPDATE state_machine SET h = ?, r = ? WHERE id=0`,
height, round,
)
return err
}
func (s *Store) StateMachineHeightRound(ctx context.Context) (
height uint64, round uint32,
err error,
) {
defer trace.StartRegion(ctx, "StateMachineHeightRound").End()
err = s.ro.QueryRowContext(
ctx,
`SELECT h, r FROM state_machine WHERE id=0`,
).Scan(
&height, &round,
)
if err == nil &&
height == 0 && round == 0 {
return 0, 0, tmstore.ErrStoreUninitialized
}
return
}
func (s *Store) SavePubKeys(ctx context.Context, keys []gcrypto.PubKey) (string, error) {
defer trace.StartRegion(ctx, "SavePubKeys").End()
hash, err := s.hs.PubKeys(keys)
if err != nil {
return "", fmt.Errorf("failed to calculate public key hash: %w", err)
}
// First check if the hash is already in the database.
// (Assuming we aren't racing in core Gordian to add this;
// if we are racing, then this just needs to move inside the transaction.)
var count int
err = s.ro.QueryRowContext(
ctx,
// Would this be better as an EXISTS query?
`SELECT COUNT(hash) FROM validator_pub_key_hashes WHERE hash = ?;`,
hash,
).Scan(&count)
if err != nil {
return "", fmt.Errorf("failed to check public key hash existence: %w", err)
}
if count > 0 {
return string(hash), tmstore.PubKeysAlreadyExistError{
ExistingHash: string(hash),
}
}
// Otherwise the count was zero, so we need to do all the work.
tx, err := s.rw.BeginTx(ctx, nil)
if err != nil {
return "", fmt.Errorf("failed to open transaction: %w", err)
}
defer tx.Rollback()
if _, err := s.createPubKeysInTx(ctx, tx, hash, keys); err != nil {
return "", err
}
if err := tx.Commit(); err != nil {
return "", fmt.Errorf("failed to commit saving public key hash: %w", err)
}
return string(hash), nil
}
// createPubKeysInTx saves the set of public keys belonging to the given hash.
// This method assumes that the hash does not exist in the validator_pub_key_hashes table yet.
func (s *Store) createPubKeysInTx(
ctx context.Context,
tx *sql.Tx,
pubKeyHash []byte,
keys []gcrypto.PubKey,
) (hashID int64, err error) {
defer trace.StartRegion(ctx, "createPubKeysInTx").End()
// Create the key hash first.
res, err := tx.ExecContext(
ctx,
`INSERT INTO validator_pub_key_hashes(hash, n_keys) VALUES(?,?);`,
pubKeyHash, len(keys),
)
if err != nil {
return -1, fmt.Errorf("failed to save new public key hash: %w", err)
}
hashID, err = res.LastInsertId()
if err != nil {
return -1, fmt.Errorf("failed to get last insert ID after saving new public key hash: %w", err)
}
args := make([]any, 0, 3*len(keys))
for i, k := range keys {
res, err := tx.ExecContext(
ctx,
`INSERT OR IGNORE INTO validator_pub_keys(type, key) VALUES(?,?);`,
k.TypeName(), k.PubKeyBytes(),
)
if err != nil {
return -1, fmt.Errorf("failed to insert validator public key: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return -1, fmt.Errorf("failed to get rows affected after inserting validator public key: %w", err)
}
var keyID int64
if n == 1 {
keyID, err = res.LastInsertId()
if err != nil {
return -1, fmt.Errorf("failed to get insert ID after inserting validator public key: %w", err)
}
} else {
// No rows affected, so we need to query the ID.
if err := tx.QueryRowContext(
ctx,
`SELECT id FROM validator_pub_keys WHERE type = ? AND key = ?;`,
k.TypeName(), k.PubKeyBytes(),
).Scan(&keyID); err != nil {
return -1, fmt.Errorf("failed to get key ID when querying: %w", err)
}
}
// Now that we have a hash ID, key ID, and ordinal index,
// we can update args we will insert into the pub key hash entries.
args = append(args, hashID, i, keyID)
}
q := `INSERT INTO validator_pub_key_hash_entries(hash_id, idx, key_id) VALUES (?,?,?)` +
strings.Repeat(", (?,?,?)", len(keys)-1)
if _, err := tx.ExecContext(ctx, q, args...); err != nil {
return -1, fmt.Errorf("failed to insert public key hash entry: %w", err)
}
return hashID, nil
}
func (s *Store) LoadPubKeys(ctx context.Context, hash string) ([]gcrypto.PubKey, error) {
defer trace.StartRegion(ctx, "LoadPubKeys").End()
rows, err := s.ro.QueryContext(
ctx,
`SELECT type, key FROM v_validator_pub_keys_for_hash WHERE hash = ? ORDER BY idx ASC`,
// This is annoying: if you leave the hash as a string,
// the string type apparently won't match the blob type,
// and so you get a misleading empty result.
[]byte(hash),
)
if err != nil {
return nil, fmt.Errorf("failed to query public keys by hash: %w", err)
}
defer rows.Close()
var keys []gcrypto.PubKey
var keyBytes []byte
var typeName string
for rows.Next() {
keyBytes = keyBytes[:0]
if err := rows.Scan(&typeName, &keyBytes); err != nil {
return nil, fmt.Errorf("failed to scan validator hash row: %w", err)
}
key, err := s.reg.Decode(typeName, bytes.Clone(keyBytes))
if err != nil {
return nil, fmt.Errorf("failed to decode validator key %x: %w", keyBytes, err)
}
keys = append(keys, key)
}
if len(keys) == 0 {
return nil, tmstore.NoPubKeyHashError{Want: hash}
}
return keys, nil
}
func (s *Store) SaveVotePowers(ctx context.Context, powers []uint64) (string, error) {
defer trace.StartRegion(ctx, "SaveVotePowers").End()
hash, err := s.hs.VotePowers(powers)
if err != nil {
return "", fmt.Errorf("failed to calculate vote power hash: %w", err)
}
// First check if the hash is already in the database.
// (Assuming we aren't racing in core Gordian to add this;
// if we are racing, then this just needs to move inside the transaction.)
var count int
err = s.ro.QueryRowContext(
ctx,
`SELECT COUNT(hash) FROM validator_power_hashes WHERE hash = ?;`,
hash,
).Scan(&count)
if err != nil {
return "", fmt.Errorf("failed to check vote power hash existence: %w", err)
}
if count > 0 {
return string(hash), tmstore.VotePowersAlreadyExistError{
ExistingHash: string(hash),
}
}
// Otherwise the count was zero, so we need to do all the work.
tx, err := s.rw.BeginTx(ctx, nil)
if err != nil {
return "", fmt.Errorf("failed to open transaction: %w", err)
}
defer tx.Rollback()
if _, err := s.createVotePowersInTx(ctx, tx, hash, powers); err != nil {
return "", err
}
if err := tx.Commit(); err != nil {
return "", fmt.Errorf("failed to commit saving vote power hash: %w", err)
}
return string(hash), nil
}
// createVotePowersInTx saves the set of vote powers belonging to the given hash.
// This method assumes that the hash does not exist in the validator_vote_power_hashes table yet.
func (s *Store) createVotePowersInTx(
ctx context.Context,
tx *sql.Tx,
votePowerHash []byte,
powers []uint64,
) (hashID int64, err error) {
defer trace.StartRegion(ctx, "createVotePowersInTx").End()
// Create the key hash first.
res, err := tx.ExecContext(
ctx,
`INSERT INTO validator_power_hashes(hash, n_powers) VALUES(?,?);`,
votePowerHash, len(powers),
)
if err != nil {
return -1, fmt.Errorf("failed to save new vote power hash: %w", err)
}
hashID, err = res.LastInsertId()
if err != nil {
return -1, fmt.Errorf("failed to get last insert ID after saving new vote power hash: %w", err)
}
args := make([]any, 0, 3*len(powers))
// TODO: condense this into one larger insert.
for i, power := range powers {
args = append(args, hashID, i, power)
}
q := `INSERT INTO validator_power_hash_entries(hash_id, idx, power)
VALUES (?,?,?)` +
strings.Repeat(", (?,?,?)", len(powers)-1)
if _, err := tx.ExecContext(ctx, q, args...); err != nil {
return -1, fmt.Errorf("failed to insert vote power hash entry: %w", err)
}
return hashID, nil
}
func (s *Store) LoadVotePowers(ctx context.Context, hash string) ([]uint64, error) {
defer trace.StartRegion(ctx, "LoadVotePowers").End()
rows, err := s.ro.QueryContext(
ctx,
`
SELECT validator_power_hash_entries.power FROM validator_power_hash_entries
JOIN validator_power_hashes ON validator_power_hashes.id = validator_power_hash_entries.hash_id
WHERE validator_power_hashes.hash = ? ORDER BY validator_power_hash_entries.idx ASC;`,
// This is annoying: if you leave the hash as a string,
// the string type apparently won't match the blob type,
// and so you get a misleading empty result.
[]byte(hash),
)
if err != nil {
return nil, fmt.Errorf("failed to query vote powers by hash: %w", err)
}
defer rows.Close()
var powers []uint64
for rows.Next() {
var pow uint64
if err := rows.Scan(&pow); err != nil {
return nil, fmt.Errorf("failed to scan validator power row: %w", err)
}
powers = append(powers, pow)
}
if len(powers) == 0 {
return nil, tmstore.NoVotePowerHashError{Want: hash}
}
return powers, nil
}
func (s *Store) LoadValidators(ctx context.Context, keyHash, powHash string) ([]tmconsensus.Validator, error) {
defer trace.StartRegion(ctx, "LoadValidators").End()
rows, err := s.ro.QueryContext(
ctx,
`SELECT keys.type, keys.key, powers.power FROM
(
SELECT type, key, idx FROM v_validator_pub_keys_for_hash WHERE hash = ? ORDER BY idx ASC
) as keys
JOIN
(
SELECT power, idx FROM v_validator_powers_for_hash WHERE hash = ? ORDER BY idx ASC
) as powers ON keys.idx = powers.idx
`,
[]byte(keyHash), []byte(powHash),
)
if err != nil {
return nil, fmt.Errorf("failed to query for validators: %w", err)
}
defer rows.Close()
var vals []tmconsensus.Validator
var typeName string
var keyBytes []byte
for rows.Next() {
keyBytes = keyBytes[:0]
var pow uint64
if err := rows.Scan(&typeName, &keyBytes, &pow); err != nil {
return nil, fmt.Errorf("failed to scan validator row: %w", err)
}
key, err := s.reg.Decode(typeName, bytes.Clone(keyBytes))
if err != nil {
return nil, fmt.Errorf("failed to decode validator key %x: %w", keyBytes, err)
}
vals = append(vals, tmconsensus.Validator{
PubKey: key,
Power: pow,
})
}
rows.Close()
if len(vals) > 0 {
// One more check that the key count is correct.
// There is probably some way to push this into the prior query.
row := s.ro.QueryRowContext(
ctx,
`SELECT keys.n_keys, powers.n_powers FROM
(SELECT n_keys FROM validator_pub_key_hashes WHERE hash = ?) AS keys,
(SELECT n_powers FROM validator_power_hashes WHERE hash = ?) AS powers`,
[]byte(keyHash), []byte(powHash),
)
var nKeys, nPows int
if err := row.Scan(&nKeys, &nPows); err != nil {
return nil, fmt.Errorf("failed to scan count results: %w", err)
}
if nKeys != nPows {
return nil, tmstore.PubKeyPowerCountMismatchError{
NPubKeys: nKeys,
NVotePower: nPows,
}
}
if nKeys != len(vals) {
panic(fmt.Errorf(
"BUG: expected %d vals, but queried %d", nKeys, len(vals),
))
}
return vals, nil
}
// We are missing at least one hash.
// Run another query to determine which we are missing.
row := s.ro.QueryRowContext(
ctx,
`SELECT * FROM
(SELECT COUNT(hash) FROM validator_pub_key_hashes WHERE hash = ?),
(SELECT COUNT(hash) FROM validator_power_hashes WHERE hash = ?)`,
[]byte(keyHash), []byte(powHash),
)
var nKeys, nPows int
if err := row.Scan(&nKeys, &nPows); err != nil {
return nil, fmt.Errorf("failed to scan hash counts: %w", err)
}
var hashErr error
if nKeys == 0 {
hashErr = tmstore.NoPubKeyHashError{Want: keyHash}
}
if nPows == 0 {
hashErr = errors.Join(hashErr, tmstore.NoVotePowerHashError{Want: powHash})
}
if hashErr == nil {
panic(fmt.Errorf(
"DATA RACE: hashes (pub keys: %x; power: %x) were missing and then appeared",
keyHash, powHash,
))
}
return nil, hashErr
}
func (s *Store) SaveFinalization(
ctx context.Context,
height uint64, round uint32,
blockHash string,
valSet tmconsensus.ValidatorSet,
appStateHash string,
) error {
defer trace.StartRegion(ctx, "SaveFinalization").End()
// We're going to need to touch a couple tables, so do this all within a transaction.
tx, err := s.rw.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("failed to open transaction: %w", err)
}
defer tx.Rollback()
// Check if the validator hashes already exist.
row := tx.QueryRowContext(
ctx,
`SELECT * FROM
(SELECT COUNT(hash) FROM validator_pub_key_hashes WHERE hash = ?),
(SELECT COUNT(hash) FROM validator_power_hashes WHERE hash = ?)`,
valSet.PubKeyHash, valSet.VotePowerHash,
)
var nKeys, nPows int
if err := row.Scan(&nKeys, &nPows); err != nil {
return fmt.Errorf("failed to scan hash counts: %w", err)
}
if nKeys == 0 {
if _, err := s.createPubKeysInTx(ctx, tx, valSet.PubKeyHash, tmconsensus.ValidatorsToPubKeys(valSet.Validators)); err != nil {
return fmt.Errorf("failed to save new public key hash: %w", err)
}
}
if nPows == 0 {
if _, err := s.createVotePowersInTx(ctx, tx, valSet.VotePowerHash, tmconsensus.ValidatorsToVotePowers(valSet.Validators)); err != nil {
return fmt.Errorf("failed to save new vote power hash: %w", err)
}
}
// The power hashes exist.
// Now we should be able to write the finalization record.
res, err := tx.ExecContext(
ctx,
`INSERT INTO
finalizations(height, round, block_hash, validator_pub_key_hash_id, validator_power_hash_id, app_state_hash)
SELECT ?, ?, ?, keys.id, powers.id, ? FROM
(SELECT id FROM validator_pub_key_hashes WHERE hash = ?) AS keys,
(SELECT id FROM validator_power_hashes WHERE hash = ?) AS powers
`,
height, round, []byte(blockHash), []byte(appStateHash), valSet.PubKeyHash, valSet.VotePowerHash,
)
if err != nil {
if isPrimaryKeyConstraintError(err) {
return tmstore.FinalizationOverwriteError{Height: height}
}
return fmt.Errorf("failed to write finalization: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("failed to check rows affected: %w", err)
}
if n != 1 {
return fmt.Errorf("expected 1 affected row, got %d", n)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
func (s *Store) LoadFinalizationByHeight(ctx context.Context, height uint64) (
round uint32,
blockHash string,
valSet tmconsensus.ValidatorSet,
appStateHash string,
err error,
) {
defer trace.StartRegion(ctx, "LoadFinalizationByHeight").End()
// This two-stage query seems like a prime candidate for NextResultSet,
// but it appears neither SQLite driver supports it.
// So use a read-only transaction instead.
// (Which is apparently not even enforced: see
// https://github.com/mattn/go-sqlite3/issues/685 and
// https://gitlab.com/cznic/sqlite/-/issues/193 .)
tx, err := s.ro.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
err = fmt.Errorf("failed to begin read-only transaction: %w", err)
return
}
defer tx.Rollback()
// TODO: this query could also retrieve the n_validators and n_powers in order to
// validate the hashes refer to the same number of powers and validators.
var blockHashBytes, appStateHashBytes []byte
var nKeys, nPowers int
if err = tx.QueryRowContext(
ctx,
`SELECT
f.round,
f.block_hash, f.app_state_hash,
key_hashes.hash, power_hashes.hash,
key_hashes.n_keys, power_hashes.n_powers
FROM finalizations AS f
JOIN validator_pub_key_hashes AS key_hashes ON key_hashes.id = f.validator_pub_key_hash_id
JOIN validator_power_hashes AS power_hashes ON power_hashes.id = f.validator_power_hash_id
WHERE f.height = ?`,
height,
).Scan(
&round,
&blockHashBytes, &appStateHashBytes,
&valSet.PubKeyHash, &valSet.VotePowerHash,
&nKeys, &nPowers,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
// The compliance tests require HeightUnknownError when no finalization matches the height.
err = tmconsensus.HeightUnknownError{Want: height}
return
}
// Otherwise, just wrap that error.
err = fmt.Errorf("failed to scan finalization primitive data: %w", err)
return
}
if nKeys != nPowers {
// We already know they are > 0 due to checks on the respective tables.
panic(fmt.Errorf(
"DATABASE CORRUPTION: finalization for height %d references pubkey hash %x (with %d keys) and power hash %x (with %d powers)",
height, valSet.PubKeyHash, nKeys, valSet.VotePowerHash, nPowers,
))
}
blockHash = string(blockHashBytes)
appStateHash = string(appStateHashBytes)
// Then extract the validators.
rows, err := tx.QueryContext(
ctx,
// It seems like there should be a view for this,
// but maybe not because we are joining on the finalizations table?
`SELECT keys.type, keys.key, powers.power FROM
(
SELECT type, key, idx FROM v_validator_pub_keys_for_hash
JOIN finalizations ON finalizations.validator_pub_key_hash_id = v_validator_pub_keys_for_hash.hash_id
WHERE finalizations.height = ?1 ORDER BY idx ASC
) as keys
JOIN
(
SELECT power, idx FROM v_validator_powers_for_hash
JOIN finalizations ON finalizations.validator_power_hash_id = v_validator_powers_for_hash.hash_id
WHERE finalizations.height = ?1 ORDER BY idx ASC
) as powers ON keys.idx = powers.idx
`,
height,
)
if err != nil {
err = fmt.Errorf("failed to query validators for finalization: %w", err)
return
}
defer rows.Close()
var typeName string
var keyBytes []byte
for rows.Next() {
keyBytes = keyBytes[:0]
var pow uint64
if err = rows.Scan(&typeName, &keyBytes, &pow); err != nil {
err = fmt.Errorf("failed to scan validator row: %w", err)
return
}
var key gcrypto.PubKey
key, err = s.reg.Decode(typeName, bytes.Clone(keyBytes))
if err != nil {
err = fmt.Errorf("failed to decode validator key %x: %w", keyBytes, err)
return
}
valSet.Validators = append(valSet.Validators, tmconsensus.Validator{
PubKey: key,
Power: pow,
})
}
return
}
// selectOrInsertPubKeysByHash looks up the database ID of the given pubKeyHash.
// If the record exists, the ID is returned.
// If the record does not exist, a new record is created
// for the given hash and the given public keys in the provided order.
func (s *Store) selectOrInsertPubKeysByHash(
ctx context.Context,
tx *sql.Tx,
pubKeyHash []byte,
pubKeys []gcrypto.PubKey,
) (hashID int64, err error) {
defer trace.StartRegion(ctx, "selectOrInsertPubKeysByHash").End()
row := tx.QueryRowContext(
ctx,
`SELECT id FROM validator_pub_key_hashes WHERE hash = ?`,
pubKeyHash,
)
err = row.Scan(&hashID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return s.createPubKeysInTx(ctx, tx, pubKeyHash, pubKeys)
}
// Not sql.ErrNoRows, so nothing else we can do.
return -1, fmt.Errorf("failed to scan pub key hash ID: %w", err)
}
return hashID, nil
}
// selectOrInsertVotePowersByHash looks up the database ID of the given votePowerHash.
// If the record exists, the ID is returned.
// If the record does not exist, a new record is created
// for the given hash and the given powers in the provided order.
func (s *Store) selectOrInsertVotePowersByHash(
ctx context.Context,
tx *sql.Tx,
votePowerHash []byte,
votePowers []uint64,
) (hashID int64, err error) {
defer trace.StartRegion(ctx, "selectOrInsertVotePowersByHash").End()
row := tx.QueryRowContext(
ctx,
`SELECT id FROM validator_power_hashes WHERE hash = ?`,
votePowerHash,
)
err = row.Scan(&hashID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return s.createVotePowersInTx(ctx, tx, votePowerHash, votePowers)
}
// Not sql.ErrNoRows, so nothing else we can do.
return -1, fmt.Errorf("failed to scan vote power hash ID: %w", err)
}
return hashID, nil
}
func (s *Store) SaveCommittedHeader(ctx context.Context, ch tmconsensus.CommittedHeader) error {
defer trace.StartRegion(ctx, "SaveCommittedHeader").End()
tx, err := s.rw.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("failed to begin transaction: %w", err)
}
defer tx.Rollback()
h := ch.Header
headerID, err := s.createHeaderInTx(ctx, tx, h, true)
if err != nil && !errors.As(err, new(tmstore.OverwriteError)) {
return fmt.Errorf("failed to create header record: %w", err)
}
// Now store the proof.
res, err := tx.ExecContext(
ctx,
`INSERT INTO commit_proofs(round, validators_pub_key_hash_id) VALUES
(?, (SELECT validators_pub_key_hash_id FROM headers WHERE id = ?))`,
ch.Proof.Round, headerID,
)
if err != nil {
return fmt.Errorf("failed to insert commit proof: %w", err)
}
commitProofID, err := res.LastInsertId()
if err != nil {
return fmt.Errorf("failed to get ID of inserted commit proof: %w", err)
}
if err := s.saveCommitProofs(ctx, tx, commitProofID, ch.Proof.Proofs); err != nil {
return fmt.Errorf("failed to save header's commit proof: %w", err)
}
// Finally, insert the committed header record.
if _, err := tx.ExecContext(
ctx,
`INSERT INTO committed_headers(header_id, proof_id) VALUES(?, ?)`,
headerID, commitProofID,
); err != nil {
return fmt.Errorf("failed to insert into commit_headers: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction to save header: %w", err)
}
return nil
}
// createHeaderInTx saves a new header record
// and returns the header ID.
//
// If there is already a header with the same height and hash,
// createHeaderInTx returns the ID and a [tmstore.OverwriteError] (with Field="hash").
func (s *Store) createHeaderInTx(
ctx context.Context,
tx *sql.Tx,
h tmconsensus.Header,
committed bool,
) (int64, error) {
defer trace.StartRegion(ctx, "createHeaderInTx").End()
pubKeyHashID, err := s.selectOrInsertPubKeysByHash(
ctx, tx,
h.ValidatorSet.PubKeyHash,
tmconsensus.ValidatorsToPubKeys(h.ValidatorSet.Validators),
)
if err != nil {
return -1, fmt.Errorf("failed to save validator public keys: %w", err)
}
votePowerHashID, err := s.selectOrInsertVotePowersByHash(
ctx, tx,
h.ValidatorSet.VotePowerHash,
tmconsensus.ValidatorsToVotePowers(h.ValidatorSet.Validators),
)
if err != nil {
return -1, fmt.Errorf("failed to save validator vote powers: %w", err)
}
nextPubKeyHashID := pubKeyHashID
if !bytes.Equal(h.ValidatorSet.PubKeyHash, h.NextValidatorSet.PubKeyHash) {
nextPubKeyHashID, err = s.selectOrInsertPubKeysByHash(
ctx, tx,
h.NextValidatorSet.PubKeyHash,
tmconsensus.ValidatorsToPubKeys(h.NextValidatorSet.Validators),
)
if err != nil {
return -1, fmt.Errorf("failed to save next validator public keys: %w", err)
}