forked from decred/dcrd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ticketdb.go
1641 lines (1385 loc) · 47.8 KB
/
ticketdb.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) 2015 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
//
// TODO: Consider adding the height where an SStx was missed for use as SSgen in
// SSRtx output[0] OP_RETURN?
//
// This file contains an in-memory database for storing information about tickets.
//
// There should be four major datasets:
// ticketMap = Ticket map keyed for mature, available tickets by number.
// spentTicketMap = Ticket map keyed for tickets that are mature but invalid or
// spent, keyed by the block in which they were invalidated.
// missedTicketMap = Ticket map keyed for SStx hash for tickets which had the
// opportunity to be spent but were not.
// revokedTicketMap = Ticket map keyed for SStx hash for tickets which had the
// opportunity to be spent but were not, and then were revoked.
package stake
import (
"bytes"
"encoding/gob"
"errors"
"fmt"
"io/ioutil"
"math"
"path/filepath"
"sort"
"sync"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/database"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrutil"
)
// bucketSize is the number of pre-sort buckets for the in memory database of
// live tickets. This allows an approximately 1.5x-2.5x increase in sorting speed
// and easier/more efficient handling of new block insertion and evaluation
// of reorgs.
// TODO Storing the size of the buckets somewhere would make evaluation of
// blocks being added to HEAD extremely fast and should eventually be implemented.
// For example, when finding the tickets to use you can cycle through a struct
// for each bucket where the struct stores the number of tickets in the bucket,
// so you can easily find the index of the ticket you need without creating
// a giant slice and sorting it.
// Optimizations for reorganize are possible.
const BucketsSize = math.MaxUint8 + 1
// TickerData contains contextual information about tickets as indicated
// below.
// TODO Replace Missed/Expired bool with single byte bitflags.
type TicketData struct {
SStxHash chainhash.Hash
Prefix uint8 // Ticket hash prefix for pre-sort
SpendHash chainhash.Hash
BlockHeight int64 // Block for where the original sstx was located
Missed bool // Whether or not the ticket was spent
Expired bool // Whether or not the ticket expired
}
func NewTicketData(sstxHash chainhash.Hash,
prefix uint8,
spendHash chainhash.Hash,
blockHeight int64,
missed bool,
expired bool) *TicketData {
return &TicketData{sstxHash,
prefix,
spendHash,
blockHeight,
missed,
expired}
}
// td.GobEncode serializes the TicketData struct into a gob for use in storage.
//
// This function is safe for concurrent access.
func (td *TicketData) GobEncode() ([]byte, error) {
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
err := encoder.Encode(td.SStxHash)
if err != nil {
return nil, err
}
err = encoder.Encode(td.Prefix)
if err != nil {
return nil, err
}
err = encoder.Encode(td.SpendHash)
if err != nil {
return nil, err
}
err = encoder.Encode(td.BlockHeight)
if err != nil {
return nil, err
}
err = encoder.Encode(td.Missed)
if err != nil {
return nil, err
}
err = encoder.Encode(td.Expired)
if err != nil {
return nil, err
}
return w.Bytes(), nil
}
// td.GobDecode deserializes the TicketData struct into a gob for use in retrieval
// from storage.
func (td *TicketData) GobDecode(buf []byte) error {
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
err := decoder.Decode(&td.SStxHash)
if err != nil {
return err
}
err = decoder.Decode(&td.Prefix)
if err != nil {
return err
}
err = decoder.Decode(&td.SpendHash)
if err != nil {
return err
}
err = decoder.Decode(&td.BlockHeight)
if err != nil {
return err
}
err = decoder.Decode(&td.Missed)
if err != nil {
return err
}
return decoder.Decode(&td.Expired)
}
// TicketDataSlice is a sortable data structure of pointers to TicketData.
type TicketDataSlice []*TicketData
func NewTicketDataSliceEmpty() TicketDataSlice {
slice := make([]*TicketData, 0)
return TicketDataSlice(slice)
}
func NewTicketDataSlice(size int) TicketDataSlice {
slice := make([]*TicketData, size)
return TicketDataSlice(slice)
}
// Less determines which of two *TicketData values is smaller; used for sort.
func (tds TicketDataSlice) Less(i, j int) bool {
cmp := bytes.Compare(tds[i].SStxHash[:], tds[j].SStxHash[:])
isISmaller := (cmp == -1)
return isISmaller
}
// Swap swaps two *TicketData values.
func (tds TicketDataSlice) Swap(i, j int) { tds[i], tds[j] = tds[j], tds[i] }
// Len returns the length of the slice.
func (tds TicketDataSlice) Len() int { return len(tds) }
// SStxMemMap is a memory map of SStx keyed to the txHash.
type SStxMemMap map[chainhash.Hash]*TicketData
// TicketMaps is a struct of maps that encompass the four major buckets of the
// ticket in-memory database.
type TicketMaps struct {
ticketMap []SStxMemMap
spentTicketMap map[int64]SStxMemMap
missedTicketMap SStxMemMap
revokedTicketMap SStxMemMap
}
// tm.GobEncode serializes the TicketMaps struct into a gob for use in storage.
func (tm *TicketMaps) GobEncode() ([]byte, error) {
w := new(bytes.Buffer)
encoder := gob.NewEncoder(w)
err := encoder.Encode(tm.ticketMap)
if err != nil {
return nil, err
}
err = encoder.Encode(tm.spentTicketMap)
if err != nil {
return nil, err
}
err = encoder.Encode(tm.missedTicketMap)
if err != nil {
return nil, err
}
err = encoder.Encode(tm.revokedTicketMap)
if err != nil {
return nil, err
}
return w.Bytes(), nil
}
// tm.GobDecode deserializes the TicketMaps struct into a gob for use in retrieval
// from storage.
func (tm *TicketMaps) GobDecode(buf []byte) error {
r := bytes.NewBuffer(buf)
decoder := gob.NewDecoder(r)
err := decoder.Decode(&tm.ticketMap)
if err != nil {
return err
}
err = decoder.Decode(&tm.spentTicketMap)
if err != nil {
return err
}
err = decoder.Decode(&tm.missedTicketMap)
if err != nil {
return err
}
return decoder.Decode(&tm.revokedTicketMap)
}
// TicketDB is the ticket in-memory database.
type TicketDB struct {
mtx sync.Mutex
maps TicketMaps
database database.Db
chainParams *chaincfg.Params
StakeEnabledHeight int64
}
// initialize allocates buckets for each ticket number in ticketMap and buckets for
// each height up to the declared height from 0. This should be called only when no
// suitable files exist to load the TicketDB from or when rescanTicketDB() is
// called.
// WARNING: Height should be 0 for all non-debug uses.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) Initialize(np *chaincfg.Params, db database.Db) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
tmdb.chainParams = np
tmdb.database = db
tmdb.maps.ticketMap = make([]SStxMemMap, BucketsSize, BucketsSize)
tmdb.maps.spentTicketMap = make(map[int64]SStxMemMap)
tmdb.maps.missedTicketMap = make(SStxMemMap)
tmdb.maps.revokedTicketMap = make(SStxMemMap)
tmdb.StakeEnabledHeight = np.StakeEnabledHeight
// Fill in live ticket buckets
for i := 0; i < BucketsSize; i++ {
tmdb.maps.ticketMap[uint8(i)] = make(SStxMemMap)
}
}
// maybeInsertBlock creates a new bucket in the spentTicketMap; this should be
// called this whenever we try to alter the spentTicketMap; this results in
// a lot of redundant calls, but I don't think they're expensive.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) maybeInsertBlock(height int64) {
// Check if the bucket exists for the given height.
if tmdb.maps.spentTicketMap[height] != nil {
return
}
// If it doesn't exist, make it.
tmdb.maps.spentTicketMap[height] = make(SStxMemMap)
return
}
// getTopBlock is the internal function which implements the public
// GetTopBlock. See the comment for GetTopBlock for more details.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) getTopBlock() int64 {
// Discover the current height.
topHeight := tmdb.StakeEnabledHeight
for {
if tmdb.maps.spentTicketMap[topHeight] == nil {
topHeight--
break
}
topHeight++
}
// If we aren't yet at a stake mature blockchain.
if topHeight == (tmdb.StakeEnabledHeight - 1) {
return int64(-1)
}
return topHeight
}
// GetTopBlock returns the top (current) block from a TicketDB.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) GetTopBlock() int64 {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
return tmdb.getTopBlock()
}
// LoadTicketDBs fetches the stored TicketDB and UsedTicketDB from the disk and
// stores them.
// Call this after the blockchain has been loaded into the daemon.
// TODO: Make a function that checks to see if the files exist before attempting
// to load them? Or do that elsewhere.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) LoadTicketDBs(tmsPath, tmsLoc string, np *chaincfg.Params,
db database.Db) error {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
tmdb.chainParams = np
tmdb.database = db
tmdb.StakeEnabledHeight = np.StakeEnabledHeight
filename := filepath.Join(tmsPath, tmsLoc)
// Load the maps from disk.
diskTicketMaps, errDiskTM := ioutil.ReadFile(filename)
if errDiskTM != nil {
return fmt.Errorf("TicketDB err @ loadTicketDBs: could not load " +
"serialized ticketMaps from disk")
}
// Create buffer for maps and load the raw file into it.
var loadedTicketMaps TicketMaps
// Decode the maps from the buffer.
errDeserialize := loadedTicketMaps.GobDecode(diskTicketMaps)
if errDeserialize != nil {
return fmt.Errorf("could not deserialize stored ticketMaps")
}
tmdb.maps = loadedTicketMaps
// Get the latest block height from the database.
_, curHeight, err := tmdb.database.NewestSha()
if err != nil {
return err
}
// Check and see if the height of spentTicketMap is the same as the current
// height of the blockchain. If it isn't, spin up next DB for both from the
// blockchain itself (rescanTicketDB).
stmHeight := tmdb.getTopBlock()
// The database chain is shorter than the ticket db chain, abort.
if stmHeight > curHeight {
return fmt.Errorf("Ticket DB err @ loadTicketDbs: there were more "+
"blocks in the ticketDb (%v) than there were in the "+
"main db (%v); try deleting the ticket database file",
stmHeight, curHeight)
}
// The ticket db chain is shorter than the database chain, resync.
if stmHeight < curHeight {
log.Debugf("current height: %v, stm height %v", curHeight, stmHeight)
log.Errorf("Accessory ticket database is desynced, " +
"resyncing now")
err := tmdb.rescanTicketDB()
if err != nil {
return err
}
}
// If maps are empty pre-serializing, they'll be nil upon loading.
// Check to make sure that no maps are nil; if they are, generate
// them.
if tmdb.maps.ticketMap == nil {
tmdb.maps.ticketMap = make([]SStxMemMap, BucketsSize, BucketsSize)
// Fill in live ticket buckets
for i := uint8(0); ; i++ {
tmdb.maps.ticketMap[i] = make(SStxMemMap)
if i == math.MaxUint8 {
break
}
}
}
if tmdb.maps.spentTicketMap == nil {
tmdb.maps.spentTicketMap = make(map[int64]SStxMemMap)
}
if tmdb.maps.missedTicketMap == nil {
tmdb.maps.missedTicketMap = make(SStxMemMap)
}
if tmdb.maps.revokedTicketMap == nil {
tmdb.maps.revokedTicketMap = make(SStxMemMap)
}
return nil
}
// Store serializes and stores a TicketDB. Only intended to be called when shut
// down has been initiated and daemon network activity has ceased.
// TODO: Serialize in a way that is cross-platform instead of gob encoding.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) Store(tmsPath string, tmsLoc string) error {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
log.Infof("Storing the ticket database to disk")
ticketMapsBytes, err := tmdb.maps.GobEncode()
if err != nil {
return fmt.Errorf("could not serialize ticketMaps: %v", err.Error())
}
filename := filepath.Join(tmsPath, tmsLoc)
// Write the encoded ticketMap and spentTicketMap to disk
if err := ioutil.WriteFile(filename, ticketMapsBytes, 0644); err != nil {
return fmt.Errorf("could not write serialized "+
"ticketMaps to disk: %v", err.Error())
}
return nil
}
// Close deletes a TicketDB and its contents. Intended to be called only when
// store() has first been called.
// Decred: In the daemon this is never called because it causes some problems
// with storage. As everything is a native Go structure in the first place,
// we don't really need this as far as I can tell, but I'll leave this in here
// in case a usage is found.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) Close() {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
return
}
// --------------------------------------------------------------------------------
// ! WARNING
// THESE ARE DIRECT MANIPULATION FUNCTIONS THAT SHOULD MAINLY BE USED INTERNALLY
// OR FOR FOR DEBUGGING PURPOSES ONLY.
// pushLiveTicket pushes a mature ticket into the ticketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) pushLiveTicket(ticket *TicketData) error {
// Make sure the ticket bucket exists; if it doesn't something has gone wrong
// with the initialization
if tmdb.maps.ticketMap[ticket.Prefix] == nil {
return fmt.Errorf("TicketDB err @ pushLiveTicket: bucket for tickets "+
"numbered %v missing", ticket.Prefix)
}
// Make sure the ticket isn't already in the map
if tmdb.maps.ticketMap[ticket.Prefix][ticket.SStxHash] != nil {
return fmt.Errorf("TicketDB err @ pushLiveTicket: ticket with hash %v "+
"already exists", ticket.SStxHash)
}
// Always false going into live ticket map
ticket.Missed = false
// Put the ticket in its respective bucket in the map
tmdb.maps.ticketMap[ticket.Prefix][ticket.SStxHash] = ticket
return nil
}
// pushSpentTicket pushes a used ticket into the spentTicketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) pushSpentTicket(spendHeight int64, ticket *TicketData) error {
// Make sure there's a bucket in the map for used tickets
tmdb.maybeInsertBlock(spendHeight)
// Make sure the ticket isn't already in the map
if tmdb.maps.spentTicketMap[spendHeight][ticket.SStxHash] != nil {
return fmt.Errorf("TicketDB err @ pushSpentTicket: ticket with hash "+
"%v already exists", ticket.SStxHash)
}
tmdb.maps.spentTicketMap[spendHeight][ticket.SStxHash] = ticket
return nil
}
// pushMissedTicket pushes a used ticket into the spentTicketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) pushMissedTicket(ticket *TicketData) error {
// Make sure the map exists.
if tmdb.maps.missedTicketMap == nil {
return fmt.Errorf("TicketDB err @ pushMissedTicket: map missing")
}
// Make sure the ticket isn't already in the map.
if tmdb.maps.missedTicketMap[ticket.SStxHash] != nil {
return fmt.Errorf("TicketDB err @ pushMissedTicket: ticket with "+
"hash %v already exists", ticket.SStxHash)
}
// Always true going into missedTicketMap.
ticket.Missed = true
tmdb.maps.missedTicketMap[ticket.SStxHash] = ticket
return nil
}
// pushRevokedTicket pushes a used ticket into the spentTicketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) pushRevokedTicket(ticket *TicketData) error {
// Make sure the map exists.
if tmdb.maps.revokedTicketMap == nil {
return fmt.Errorf("TicketDB err @ pushRevokedTicket: map missing")
}
// Make sure the ticket isn't already in the map.
if tmdb.maps.revokedTicketMap[ticket.SStxHash] != nil {
return fmt.Errorf("TicketDB err @ pushRevokedTicket: ticket with "+
"hash %v already exists", ticket.SStxHash)
}
// Always true going into revokedTicketMap.
ticket.Missed = true
tmdb.maps.revokedTicketMap[ticket.SStxHash] = ticket
return nil
}
// removeLiveTicket removes live tickets that were added to the ticketMap from
// tickets maturing.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) removeLiveTicket(ticket *TicketData) error {
// Make sure the ticket bucket exists; if it doesn't something has gone wrong
// with the initialization
if tmdb.maps.ticketMap[ticket.Prefix] == nil {
return fmt.Errorf("TicketDB err @ removeLiveTicket: bucket for "+
"tickets numbered %v missing", ticket.Prefix)
}
// Make sure the ticket itself exists
if tmdb.maps.ticketMap[ticket.Prefix][ticket.SStxHash] == nil {
return fmt.Errorf("TicketDB err @ removeLiveTicket: ticket %v to "+
"delete does not exist!", ticket.SStxHash)
}
// Make sure that the tickets are indentical in the unlikely case of a hash
// collision
if *tmdb.maps.ticketMap[ticket.Prefix][ticket.SStxHash] != *ticket {
return fmt.Errorf("TicketDB err @ removeLiveTicket: ticket " +
"hash duplicate, but non-identical data")
}
delete(tmdb.maps.ticketMap[ticket.Prefix], ticket.SStxHash)
return nil
}
// removeSpentTicket removes spent tickets that were added to the spentTicketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) removeSpentTicket(spendHeight int64, ticket *TicketData) error {
// Make sure the height bucket exists; if it doesn't something has gone wrong
// with the initialization
if tmdb.maps.spentTicketMap[spendHeight] == nil {
return fmt.Errorf("TicketDB err @ removeSpentTicket: bucket for "+
"BlockHeight numbered %v missing", ticket.BlockHeight)
}
// Make sure the ticket itself exists
if tmdb.maps.spentTicketMap[spendHeight][ticket.SStxHash] == nil {
return fmt.Errorf("TicketDB err @ removeSpentTicket: ticket to "+
"delete does not exist!", ticket.SStxHash)
}
// Make sure that the tickets are indentical in the unlikely case of a hash
// collision
if *tmdb.maps.spentTicketMap[spendHeight][ticket.SStxHash] != *ticket {
return fmt.Errorf("TicketDB err @ removeSpentTicket: ticket hash " +
"duplicate, but non-identical data")
}
delete(tmdb.maps.spentTicketMap[spendHeight], ticket.SStxHash)
return nil
}
// removeMissedTicket removes missed tickets that were added to the spentTicketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) removeMissedTicket(ticket *TicketData) error {
// Make sure the map exists.
if tmdb.maps.missedTicketMap == nil {
return fmt.Errorf("TicketDB err @ removeMissedTicket: map missing")
}
// Make sure the ticket exists
if tmdb.maps.missedTicketMap[ticket.SStxHash] == nil {
return fmt.Errorf("TicketDB err @ removeMissedTicket: ticket to "+
"delete does not exist!", ticket.SStxHash)
}
// Make sure that the tickets are indentical in the unlikely case of a hash
// collision
if *tmdb.maps.missedTicketMap[ticket.SStxHash] != *ticket {
return fmt.Errorf("TicketDB err @ removeMissedTicket: ticket hash " +
"duplicate, but non-identical data")
}
delete(tmdb.maps.missedTicketMap, ticket.SStxHash)
return nil
}
// removeRevokedTicket removes missed tickets that were added to the
// revoked ticket map.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) removeRevokedTicket(ticket *TicketData) error {
// Make sure the map exists.
if tmdb.maps.revokedTicketMap == nil {
return fmt.Errorf("TicketDB err @ removeRevokedTicket: map missing")
}
// Make sure the ticket exists.
if tmdb.maps.revokedTicketMap[ticket.SStxHash] == nil {
return fmt.Errorf("TicketDB err @ removeRevokedTicket: ticket to "+
"delete does not exist!", ticket.SStxHash)
}
// Make sure that the tickets are indentical in the unlikely case of a hash
// collision.
if *tmdb.maps.revokedTicketMap[ticket.SStxHash] != *ticket {
return fmt.Errorf("TicketDB err @ removeRevokedTicket: ticket hash " +
"duplicate, but non-identical data")
}
delete(tmdb.maps.revokedTicketMap, ticket.SStxHash)
return nil
}
// removeSpentHeight removes a height bucket from the SpentTicketMap.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) removeSpentHeight(height int64) error {
// Make sure the height exists
if tmdb.maps.spentTicketMap[height] == nil {
return fmt.Errorf("TicketDB err @ removeSpentHeight: height to "+
"delete does not exist!", height)
}
delete(tmdb.maps.spentTicketMap, height)
return nil
}
// DumpMapsPointer is a testing function that returns a pointer to
// the internally held maps. Used for testing.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) DumpMapsPointer() TicketMaps {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
return tmdb.maps
}
// END DIRECT ACCESS/DEBUG TOOLS.
// --------------------------------------------------------------------------------
// cloneSStxMemMap is a helper function to clone mem maps to avoid races.
func cloneSStxMemMap(mapToCopy SStxMemMap) SStxMemMap {
newMemMap := make(SStxMemMap)
for hash, ticket := range mapToCopy {
newMemMap[hash] = NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return newMemMap
}
// CheckLiveTicket checks for the existence of a live ticket in ticketMap.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) CheckLiveTicket(txHash chainhash.Hash) (bool, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
prefix := txHash[0]
// Make sure the ticket bucket exists; if it doesn't something has gone wrong
// with the initialization
if tmdb.maps.ticketMap[prefix] == nil {
return false, fmt.Errorf("TicketDB err @ checkLiveTicket: bucket for "+
"tickets numbered %v missing", prefix)
}
if tmdb.maps.ticketMap[prefix][txHash] != nil {
return true, nil
}
return false, nil
}
// CheckMissedTicket checks for the existence of a missed ticket in the missed
// ticket map. Assumes missedTicketMap is intialized.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) CheckMissedTicket(txHash chainhash.Hash) bool {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
if _, exists := tmdb.maps.missedTicketMap[txHash]; exists {
return true
}
return false
}
// CheckRevokedTicket checks for the existence of a revoked ticket in the
// revoked ticket map. Assumes missedTicketMap is intialized.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) CheckRevokedTicket(txHash chainhash.Hash) bool {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
if _, exists := tmdb.maps.revokedTicketMap[txHash]; exists {
return true
}
return false
}
// DumpLiveTickets duplicates the contents of a ticket bucket from the databases's
// ticketMap and returns them to the user.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) DumpLiveTickets(bucket uint8) (SStxMemMap, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
tickets := make(SStxMemMap)
// Make sure the ticket bucket exists; if it doesn't something has gone wrong
// with the initialization
if tmdb.maps.ticketMap[bucket] == nil {
return nil, fmt.Errorf("TicketDB err @ DumpLiveTickets: bucket for "+
"tickets numbered %v missing", bucket)
}
for _, ticket := range tmdb.maps.ticketMap[bucket] {
tickets[ticket.SStxHash] = NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return tickets, nil
}
// DumpSpentTickets duplicates the contents of a ticket bucket from the databases's
// spentTicketMap and returns them to the user.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) DumpSpentTickets(height int64) (SStxMemMap, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
tickets := make(SStxMemMap)
// Make sure the ticket bucket exists; if it doesn't something has gone wrong
// with the initialization
if tmdb.maps.spentTicketMap[height] == nil {
return nil, fmt.Errorf("TicketDB err @ dumpSpentTickets: bucket for "+
"tickets numbered %v missing", height)
}
for _, ticket := range tmdb.maps.spentTicketMap[height] {
tickets[ticket.SStxHash] = NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return tickets, nil
}
// DumpMissedTickets duplicates the contents of a ticket bucket from the
// databases's missedTicketMap and returns them to the user.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) DumpMissedTickets() (SStxMemMap, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
tickets := make(SStxMemMap)
// Make sure the map is actually initialized.
if tmdb.maps.missedTicketMap == nil {
return nil, fmt.Errorf("TicketDB err @ missedTicketMap: map for " +
"missed tickets uninitialized")
}
for _, ticket := range tmdb.maps.missedTicketMap {
tickets[ticket.SStxHash] = NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return tickets, nil
}
// DumpRevokedTickets duplicates the contents of a ticket bucket from the
// databases's missedTicketMap and returns them to the user.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) DumpRevokedTickets() (SStxMemMap, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
tickets := make(SStxMemMap)
// Make sure the map is actually initialized.
if tmdb.maps.revokedTicketMap == nil {
return nil, fmt.Errorf("TicketDB err @ revokedTicketMap: map for " +
"revoked tickets uninitialized")
}
for _, ticket := range tmdb.maps.revokedTicketMap {
tickets[ticket.SStxHash] = NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return tickets, nil
}
// GetMissedTicket locates a missed ticket in the missed ticket database,
// duplicates the ticket data, and returns it.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) GetMissedTicket(hash chainhash.Hash) *TicketData {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
if ticket, exists := tmdb.maps.missedTicketMap[hash]; exists {
return NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return nil
}
// GetRevokedTicket locates a revoked ticket in the revoked ticket database,
// duplicates the ticket data, and returns it.
//
// This function is safe for concurrent access.
func (tmdb *TicketDB) GetRevokedTicket(hash chainhash.Hash) *TicketData {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
if ticket, exists := tmdb.maps.revokedTicketMap[hash]; exists {
return NewTicketData(ticket.SStxHash,
ticket.Prefix,
ticket.SpendHash,
ticket.BlockHeight,
ticket.Missed,
ticket.Expired)
}
return nil
}
// GetLiveTicketBucketData creates a map of [int]int indicating the number
// of tickets in each bucket. Used for an RPC call.
func (tmdb *TicketDB) GetLiveTicketBucketData() map[int]int {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
ltbd := make(map[int]int)
for i := 0; i < BucketsSize; i++ {
ltbd[int(i)] = len(tmdb.maps.ticketMap[i])
}
return ltbd
}
// GetLiveTicketsInBucketData creates a map indicating the ticket hash and the
// owner's address for each bucket. Used for an RPC call.
func (tmdb *TicketDB) GetLiveTicketsInBucketData(
bucket uint8) (map[chainhash.Hash]dcrutil.Address, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
ltbd := make(map[chainhash.Hash]dcrutil.Address)
tickets := tmdb.maps.ticketMap[bucket]
for _, ticket := range tickets {
// Load the ticket from the database and find the address that it's
// going to.
txReply, err := tmdb.database.FetchTxBySha(&ticket.SStxHash)
if err != nil {
return nil, err
}
_, addr, _, err :=
txscript.ExtractPkScriptAddrs(txReply[0].Tx.TxOut[0].Version,
txReply[0].Tx.TxOut[0].PkScript, tmdb.chainParams)
if err != nil {
return nil, err
}
ltbd[ticket.SStxHash] = addr[0]
}
return ltbd, nil
}
// GetLiveTicketsForAddress gets all currently active tickets for a given
// address.
func (tmdb *TicketDB) GetLiveTicketsForAddress(
address dcrutil.Address) ([]chainhash.Hash, error) {
tmdb.mtx.Lock()
defer tmdb.mtx.Unlock()
var ltfa []chainhash.Hash
for i := 0; i < BucketsSize; i++ {
for _, ticket := range tmdb.maps.ticketMap[i] {
// Load the ticket from the database and find the address that it's
// going to.
txReply, err := tmdb.database.FetchTxBySha(&ticket.SStxHash)
if err != nil {
return nil, err
}
_, addr, _, err :=
txscript.ExtractPkScriptAddrs(txReply[0].Tx.TxOut[0].Version,
txReply[0].Tx.TxOut[0].PkScript, tmdb.chainParams)
if err != nil {
return nil, err
}
// Compare the HASH160 result and see if it's equal.
if bytes.Equal(addr[0].ScriptAddress(), address.ScriptAddress()) {
ltfa = append(ltfa, ticket.SStxHash)
}
}
}
return ltfa, nil
}
// spendTickets transfers tickets from the ticketMap to the spentTicketMap. Useful
// when connecting blocks. Also pushes missed tickets to the missed ticket map.
// usedtickets is a map that contains all tickets that were actually used in SSGen
// votes; all other tickets are considered missed.
//
// This function MUST be called with the tmdb lock held (for writes).
func (tmdb *TicketDB) spendTickets(parentBlock *dcrutil.Block,
usedTickets map[chainhash.Hash]struct{},
spendingHashes map[chainhash.Hash]chainhash.Hash) (SStxMemMap, error) {
// If there is nothing being spent, break.
if len(spendingHashes) < 1 {
return nil, nil
}
// Make sure there's a bucket in the map for used tickets
height := parentBlock.Height() + 1
tmdb.maybeInsertBlock(height)
tempTickets := make(SStxMemMap)
// Sort the entire list of tickets lexicographically by sorting
// each bucket and then appending it to the list.
totalTickets := 0
sortedSlice := make([]*TicketData, 0)
for i := 0; i < BucketsSize; i++ {
mapLen := len(tmdb.maps.ticketMap[i])
totalTickets += mapLen
tempTdSlice := NewTicketDataSlice(mapLen)