-
Notifications
You must be signed in to change notification settings - Fork 128
/
types.go
2249 lines (2018 loc) · 67.6 KB
/
types.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-2022, The Decred developers
// See LICENSE for details.
package dbtypes
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrdata/v8/db/dbtypes/internal"
"github.com/decred/dcrdata/v8/txhelpers"
)
var scriptClassNames map[string]ScriptClass
func init() {
// Set up the map for the NewScriptClassFromString function.
scriptClassNames = make(map[string]ScriptClass, len(scriptClassNames))
for sc, name := range scriptClassToName {
scriptClassNames[name] = ScriptClass(sc)
}
}
// ScriptClass is an enumeration for the list of standard types of script.
type ScriptClass byte
// Classes of script payment known about in the blockchain.
const (
SCNonStandard ScriptClass = iota // None of the recognized forms.
SCPubKey // Pay pubkey.
SCPubKeyHash // Pay pubkey hash.
SCScriptHash // Pay to script hash.
SCMultiSig // Multi signature.
SCNullData // Empty data-only (provably prunable).
SCStakeSubmission // Stake submission.
SCStakeGen // Stake generation
SCStakeRevocation // Stake revocation.
SCStakeSubChange // Change for stake submission tx.
SCStakeSubCommit // Pseudo-class for stake submission commitments, odd outputs
SCPubkeyAlt // Alternative signature pubkey.
SCPubkeyHashAlt // Alternative signature pubkey hash.
SCTreasuryAdd // Add value to treasury
SCTreasuryGen // Generate utxos from treasury account
scLen
SCInvalid ScriptClass = 0xff
)
var scriptClassToName = [...]string{
SCNonStandard: "nonstandard",
SCPubKey: "pubkey",
SCPubkeyAlt: "pubkeyalt",
SCPubKeyHash: "pubkeyhash",
SCPubkeyHashAlt: "pubkeyhashalt",
SCScriptHash: "scripthash",
SCMultiSig: "multisig",
SCNullData: "nulldata",
SCStakeSubmission: "stakesubmission",
SCStakeGen: "stakegen",
SCStakeRevocation: "stakerevoke",
SCStakeSubChange: "sstxchange",
SCStakeSubCommit: "sstxcommitment",
SCTreasuryAdd: "treasuryadd",
SCTreasuryGen: "treasurygen",
}
// NewScriptClass converts a stdscript.ScriptType to the DB's ScriptClass type,
// which is less fine-grained with respect to the stake subtypes.
func NewScriptClass(sc stdscript.ScriptType) ScriptClass {
switch sc {
case stdscript.STNonStandard:
return SCNonStandard
case stdscript.STPubKeyEcdsaSecp256k1:
return SCPubKey
case stdscript.STPubKeyHashEcdsaSecp256k1:
return SCPubKeyHash
case stdscript.STScriptHash:
return SCScriptHash
case stdscript.STMultiSig:
return SCMultiSig
case stdscript.STNullData:
return SCNullData // could be a SCStakeSubCommit
case stdscript.STStakeSubmissionPubKeyHash, stdscript.STStakeSubmissionScriptHash:
return SCStakeSubmission
case stdscript.STStakeGenPubKeyHash, stdscript.STStakeGenScriptHash:
return SCStakeGen
case stdscript.STStakeRevocationPubKeyHash, stdscript.STStakeRevocationScriptHash:
return SCStakeRevocation
case stdscript.STStakeChangePubKeyHash, stdscript.STStakeChangeScriptHash:
return SCStakeSubChange
case stdscript.STPubKeyEd25519, stdscript.STPubKeySchnorrSecp256k1:
return SCPubkeyAlt
case stdscript.STPubKeyHashEd25519, stdscript.STPubKeyHashSchnorrSecp256k1:
return SCPubkeyHashAlt
case stdscript.STTreasuryGenPubKeyHash, stdscript.STTreasuryGenScriptHash:
return SCTreasuryGen
case stdscript.STTreasuryAdd:
return SCTreasuryAdd
}
return SCInvalid
}
// NewScriptClassFromString creates a ScriptClass from a string representation.
func NewScriptClassFromString(stdSC string) ScriptClass {
sc, found := scriptClassNames[strings.ToLower(stdSC)]
if !found {
return SCInvalid
}
return sc
}
// String implements the Stringer interface by returning the name of
// the enum script class. If the enum is invalid then "Invalid" will be
// returned.
func (sc ScriptClass) String() string {
if sc < scLen {
return scriptClassToName[sc]
}
return "invalid"
}
// Scan satisfies the sql.Scanner interface.
func (sc *ScriptClass) Scan(src interface{}) error {
str, ok := src.(string)
if !ok {
return fmt.Errorf("not a string script class")
}
*sc = NewScriptClassFromString(str)
return nil
}
var _ sql.Scanner = (*ScriptClass)(nil)
// Scan satisfies the sql/driver.Valuer interface.
func (sc ScriptClass) Value() (driver.Value, error) {
return sc.String(), nil
}
var _ driver.Valuer = ScriptClass(0)
// MarshalJSON marshals a ScriptClass to JSON, just the string in quotes.
func (sc ScriptClass) MarshalJSON() ([]byte, error) {
return json.Marshal(sc.String())
}
// UnmarshalJSON unmarshals a ScriptClass from JSON, which must be a string.
func (sc *ScriptClass) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return err
}
*sc = NewScriptClassFromString(str)
return nil
}
// ErrorKind identifies a kind of error that can be used to define new errors
// via const SomeError = dbtypes.ErrorKind("something").
type ErrorKind string
// Error satisfies the error interface and prints human-readable errors.
func (e ErrorKind) Error() string {
return string(e)
}
// Error pairs an error with details.
type Error struct {
wrapped error
detail string
}
// Error satisfies the error interface, combining the wrapped error message with
// the details.
func (e Error) Error() string {
return e.wrapped.Error() + ": " + e.detail
}
// Unwrap returns the wrapped error, allowing errors.Is and errors.As to work.
func (e Error) Unwrap() error {
return e.wrapped
}
// NewError wraps the provided Error with details in an Error, facilitating the
// use of errors.Is and errors.As via errors.Unwrap.
func NewError(err error, detail string) Error {
return Error{
wrapped: err,
detail: detail,
}
}
var (
// PGCancelError is the error string PostgreSQL returns when a query fails
// to complete due to user requested cancellation.
PGCancelError = "pq: canceling statement due to user request"
CtxDeadlineExceeded = context.DeadlineExceeded.Error()
TimeoutPrefix = "TIMEOUT of PostgreSQL query"
// ErrNoResult should be returned by the db driver instead of
// driver-specific errors like sql.ErrNoRows.
ErrNoResult = ErrorKind("no result")
)
// IsTimeout checks if the message is prefixed with the expected DB timeout
// message prefix.
func IsTimeout(msg string) bool {
// Contains is used instead of HasPrefix since error messages are often
// supplemented with additional information.
return strings.Contains(msg, TimeoutPrefix) ||
strings.Contains(msg, CtxDeadlineExceeded)
}
// IsTimeoutErr checks if error's message is prefixed with the expected DB
// timeout message prefix.
func IsTimeoutErr(err error) bool {
return err != nil && IsTimeout(err.Error())
}
// TimeDef is time.Time wrapper that formats time by default as a string without
// a timezone. The time Stringer interface formats the time into a string
// with a timezone.
type TimeDef struct {
T time.Time
}
const (
timeDefFmtHuman = "2006-01-02 15:04:05 (MST)"
timeDefFmtDateTimeNoTZ = "2006-01-02 15:04:05"
timeDefFmtJS = time.RFC3339
)
// String formats the time in a human-friendly layout. This may be used when
// TimeDef values end up on the explorer pages.
func (t TimeDef) String() string {
return t.T.Format(timeDefFmtHuman)
}
// RFC3339 formats the time in a machine-friendly layout.
func (t TimeDef) RFC3339() string {
return t.T.Format(timeDefFmtJS)
}
// UNIX returns the UNIX epoch time stamp.
func (t TimeDef) UNIX() int64 {
return t.T.Unix()
}
func (t TimeDef) Format(layout string) string {
return t.T.Format(layout)
}
// DatetimeWithoutTZ formats the time in a human-friendly layout, without
// time zone.
func (t *TimeDef) DatetimeWithoutTZ() string {
return t.T.Format(timeDefFmtDateTimeNoTZ)
}
// MarshalJSON is set as the default marshalling function for TimeDef struct.
func (t *TimeDef) MarshalJSON() ([]byte, error) {
return json.Marshal(t.RFC3339())
}
// NewTimeDef constructs a TimeDef from the given time.Time. It presets the
// timezone for formatting to UTC.
func NewTimeDef(t time.Time) TimeDef {
return TimeDef{
T: t.UTC(),
}
}
// NewTimeDefFromUNIX constructs a TimeDef from the given UNIX epoch time stamp
// in seconds. It presets the timezone for formatting to UTC.
func NewTimeDefFromUNIX(t int64) TimeDef {
return NewTimeDef(time.Unix(t, 0))
}
// Scan implements the sql.Scanner interface for TimeDef. This will not
// reinterpret the stored time string for a particular time zone. That is, if
// the stored time stamp shows no time zone (as with TIMESTAMP), the default
// time.Time scanner will load it as a local time, and this Scan converts to
// UTC. If the timestamp has a timezone (as with TIMESTAMPTZ), including UTC
// explicitly set, it will be accounted for when converting to UTC. All this
// Scan implementation does beyond the default time.Time scanner is to set the
// time.Time's location to UTC, which keeps the instant in time the same,
// adjusting the numbers in the time string to the equivalent time in UTC. For
// example, if the time read from the DB is "2016-02-08 12:00:00" (with no time
// zone) and the server time zone is CST (UTC-6), this ensures the default
// displayed time string is in UTC: "2016-02-08 18:00:00Z". On the other hand,
// if the time read from the DB is "2016-02-08 12:00:00+6", it does not matter
// what the server time zone is set to, and the time will still be converted to
// UTC as "2016-02-08 18:00:00Z".
func (t *TimeDef) Scan(src interface{}) error {
srcTime, ok := src.(time.Time)
if !ok {
return fmt.Errorf("scanned value not a time.Time")
}
// Debug:
// fmt.Printf("srcTime: %v, location: %p\n", srcTime, srcTime.Location()) // valid location not set!
// Set location to UTC. This does not shift the UNIX epoch time.
t.T = srcTime.UTC()
// Debug:
// fmt.Printf("t: %v, t.T: %v, location: %s\n", t, t.T, t.T.Location().String())
return nil
}
// Value implements the sql.Valuer interface. It ensures that the Time Values
// are for the UTC time zone. Times will only survive a round trip to and from
// the DB tables if they are stored from a time.Time with Location set to UTC.
func (t TimeDef) Value() (driver.Value, error) {
return t.T.UTC(), nil
}
// Ensure TimeDef satisfies sql.Valuer.
var _ driver.Valuer = (*TimeDef)(nil)
// TimeDefLocal satisfies the sql.Valuer interface, but it provides Local Time.
type TimeDefLocal TimeDef
// Value implements the sql.Valuer interface. It ensures that the Time Values
// are for the Local time zone. It is unlikely to be desirable to store values
// this way. Only storing a time.Time in UTC allows round trip fidelity.
func (t TimeDefLocal) Value() (driver.Value, error) {
return t.T.Local(), nil
}
// Ensure TimeDefLocal satisfies sql.Valuer.
var _ driver.Valuer = (*TimeDefLocal)(nil)
// Tickets have 6 states, 5 possible fates:
// Live -...---> Voted
// \-> Missed (unspent) [--> Revoked]
// \--...--> Expired (unspent) [--> Revoked]
type TicketSpendType int16
// These are the recognized TicketSpendType values.
const (
TicketUnspent TicketSpendType = iota
TicketRevoked
TicketVoted
)
// String implements Stringer for TicketSpendType.
func (p TicketSpendType) String() string {
switch p {
case TicketUnspent:
return "unspent"
case TicketRevoked:
return "revoked"
case TicketVoted:
return "Voted"
default:
return "unknown"
}
}
// AgendaStatusType defines the various agenda statuses.
type AgendaStatusType int8
const (
// InitialAgendaStatus is the agenda status when the agenda is not yet up for
// voting and the votes tally is not also available.
InitialAgendaStatus AgendaStatusType = iota
// StartedAgendaStatus is the agenda status when the agenda is up for voting.
StartedAgendaStatus
// FailedAgendaStatus is the agenda status set when the votes tally does not
// attain the minimum threshold set. Activation height is not set for such an
// agenda.
FailedAgendaStatus
// LockedInAgendaStatus is the agenda status when the agenda is considered to
// have passed after attaining the minimum set threshold. This agenda will
// have its activation height set.
LockedInAgendaStatus
// ActivatedAgendaStatus is the agenda status chaincfg.Params.RuleChangeActivationInterval
// blocks (e.g. 8064 blocks = 2016 * 4 for 4 weeks on mainnet) after
// LockedInAgendaStatus ("lockedin") that indicates when the rule change is to
// be effected. https://docs.decred.org/glossary/#rule-change-interval-rci.
ActivatedAgendaStatus
// UnknownStatus is used when a status string is not recognized.
UnknownStatus
)
func (a AgendaStatusType) String() string {
switch a {
case InitialAgendaStatus:
return "upcoming"
case StartedAgendaStatus:
return "in progress"
case LockedInAgendaStatus:
return "locked in"
case FailedAgendaStatus:
return "failed"
case ActivatedAgendaStatus:
return "finished"
default:
return "unknown"
}
}
// Ensure at compile time that AgendaStatusType satisfies interface json.Marshaller.
var _ json.Marshaler = (*AgendaStatusType)(nil)
// MarshalJSON is AgendaStatusType default marshaller.
func (a AgendaStatusType) MarshalJSON() ([]byte, error) {
return json.Marshal(a.String())
}
// UnmarshalJSON is the default unmarshaller for AgendaStatusType.
func (a *AgendaStatusType) UnmarshalJSON(b []byte) error {
var str string
if err := json.Unmarshal(b, &str); err != nil {
return err
}
*a = AgendaStatusFromStr(str)
return nil
}
// AgendaStatusFromStr creates an agenda status from a string. If "UnknownStatus"
// is returned then an invalid status string has been passed.
func AgendaStatusFromStr(status string) AgendaStatusType {
switch strings.ToLower(status) {
case "defined", "upcoming":
return InitialAgendaStatus
case "started", "in progress":
return StartedAgendaStatus
case "failed":
return FailedAgendaStatus
case "lockedin", "locked in":
return LockedInAgendaStatus
case "active", "finished":
return ActivatedAgendaStatus
default:
return UnknownStatus
}
}
// AddrTxnViewType enumerates the different address transaction view types as
// displayed by the address page.
type AddrTxnViewType int
// These are the recognized AddrTxnViewType values.
const (
AddrTxnAll AddrTxnViewType = iota
AddrTxnCredit
AddrTxnDebit
AddrMergedTxnDebit
AddrMergedTxnCredit
AddrMergedTxn
AddrUnspentTxn
AddrTxnUnknown
)
// AddrTxnViewTypes is the canonical mapping from AddrTxnViewType to string.
var AddrTxnViewTypes = map[AddrTxnViewType]string{
AddrTxnAll: "all",
AddrTxnCredit: "credit",
AddrTxnDebit: "debit",
AddrMergedTxnDebit: "merged_debit",
AddrMergedTxnCredit: "merged_credit",
AddrMergedTxn: "merged",
AddrUnspentTxn: "unspent",
AddrTxnUnknown: "unknown",
}
func (a AddrTxnViewType) String() string {
return AddrTxnViewTypes[a]
}
// IsMerged indicates if the address transactions view type is a merged view. If
// the type is invalid, a non-nil error is returned.
func (a AddrTxnViewType) IsMerged() (bool, error) {
switch a {
case AddrTxnAll, AddrTxnCredit, AddrTxnDebit, AddrUnspentTxn:
return false, nil
case AddrMergedTxn, AddrMergedTxnCredit, AddrMergedTxnDebit:
return true, nil
default:
return false, fmt.Errorf("unrecognized address transaction view: %v", a)
}
}
// AddrTxnViewTypeFromStr attempts to decode a string into an AddrTxnViewType.
func AddrTxnViewTypeFromStr(txnType string) AddrTxnViewType {
txnType = strings.ToLower(txnType)
switch txnType {
case "all":
return AddrTxnAll
case "credit", "credits":
return AddrTxnCredit
case "debit", "debits":
return AddrTxnDebit
case "merged_debit", "merged debit":
return AddrMergedTxnDebit
case "merged_credit", "merged credit":
return AddrMergedTxnCredit
case "merged":
return AddrMergedTxn
case "unspent":
return AddrUnspentTxn
default:
return AddrTxnUnknown
}
}
// TimeBasedGrouping defines the possible ways that a time can be grouped
// according to all, year, month, week or day grouping. This time grouping is
// used in time-based grouping like charts and blocks list view.
type TimeBasedGrouping int8
// These are the recognized TimeBasedGrouping values.
const (
AllGrouping TimeBasedGrouping = iota
YearGrouping
MonthGrouping
WeekGrouping
DayGrouping
UnknownGrouping
)
// NumIntervals is the number of known values for TimeBasedGrouping.
const NumIntervals = 5
// TimeIntervals is an array of distinct time intervals used for grouping data.
var TimeIntervals = [NumIntervals]TimeBasedGrouping{
AllGrouping,
YearGrouping,
MonthGrouping,
WeekGrouping,
DayGrouping,
}
const (
// InitialDBLoad is a sync where data is first loaded from the chain db into
// the respective dbs currently supported. InitialDBLoad value references
// the first progress bar id on the status page.
InitialDBLoad = "initial-load"
// AddressesTableSync is a sync that runs immediately after initialDBLoad.
// Data previously loaded into vins table is sync'd with the addresses
// table. AddressesTableSync value references the second progress bar id on
// the status page.
AddressesTableSync = "addresses-sync"
)
// ProgressBarLoad contains the raw data needed to populate the status sync updates.
// It is used to update the status sync through a channel.
type ProgressBarLoad struct {
From int64
To int64
Msg string
Subtitle string
BarID string
Timestamp int64
}
// BlocksGroupedInfo contains the data about a stake difficulty (ticket price) window,
// including intrinsic properties (e.g. window index, ticket price, start block, etc.),
// and aggregate transaction counts (e.g. number of votes, regular transactions,
// new tickets, etc.)
type BlocksGroupedInfo struct {
// intrinsic properties
IndexVal int64
EndBlock int64
Difficulty float64
TicketPrice int64
StartTime TimeDef
FormattedStartTime string
EndTime TimeDef
FormattedEndTime string
Size int64
FormattedSize string
// Aggregate properties
Voters uint64
Transactions uint64
FreshStake uint64
Revocations uint64
TxCount uint64
BlocksCount int64
}
// TimeBasedGroupings maps a given time grouping to its standard string value.
var TimeBasedGroupings = map[TimeBasedGrouping]string{
AllGrouping: "all",
YearGrouping: "year",
MonthGrouping: "month",
WeekGrouping: "week",
DayGrouping: "day",
}
// String implements the Stringer interface for TimeBasedGrouping.
func (g TimeBasedGrouping) String() string {
return TimeBasedGroupings[g]
}
// TimeGroupingFromStr converts groupings string to its respective TimeBasedGrouping value.
func TimeGroupingFromStr(groupings string) TimeBasedGrouping {
switch strings.ToLower(groupings) {
case "all":
return AllGrouping
case "yr", "year", "years":
return YearGrouping
case "mo", "month", "months":
return MonthGrouping
case "wk", "week", "weeks":
return WeekGrouping
case "day", "days":
return DayGrouping
default:
return UnknownGrouping
}
}
// HistoryChart is used to differentiate the distinct graphs that appear on the
// address history page.
type HistoryChart int8
// These are the recognized HistoryChart values.
const (
TxsType HistoryChart = iota
AmountFlow
ChartUnknown
)
type TicketPoolStatus int16
// NB:PoolStatusLive also defines immature tickets in addition to defining live tickets.
const (
PoolStatusLive TicketPoolStatus = iota
PoolStatusVoted
PoolStatusExpired
PoolStatusMissed
)
// VoteChoice defines the type of vote choice, and the underlying integer value
// is stored in the database (do not change these without upgrading the DB!).
type VoteChoice uint8
// These are the recognized VoteChoice values.
const (
Yes VoteChoice = iota
Abstain
No
VoteChoiceUnknown
)
// String implements the Stringer interface for TicketPoolStatus.
func (p TicketPoolStatus) String() string {
switch p {
case PoolStatusLive:
return "live"
case PoolStatusVoted:
return "Voted"
case PoolStatusExpired:
return "expired"
case PoolStatusMissed:
return "missed"
default:
return "unknown"
}
}
// String implements the Stringer interface for VoteChoice.
func (v VoteChoice) String() string {
switch v {
case Abstain:
return "abstain"
case Yes:
return "yes"
case No:
return "no"
default:
return "unknown"
}
}
// ChoiceIndexFromStr converts the vote choice string to a vote choice index.
func ChoiceIndexFromStr(choice string) (VoteChoice, error) {
switch choice {
case "abstain":
return Abstain, nil
case "yes":
return Yes, nil
case "no":
return No, nil
default:
return VoteChoiceUnknown, fmt.Errorf(`Vote Choice "%s" is unknown`, choice)
}
}
// These are text keys used to identify different chart types.
const (
AvgBlockSize = "avg-block-size"
BlockChainSize = "blockchain-size"
ChainWork = "chainwork"
CoinSupply = "coin-supply"
DurationBTW = "duration-btw-blocks"
HashRate = "hashrate"
POWDifficulty = "pow-difficulty"
TicketByWindows = "ticket-by-outputs-windows"
TicketPrice = "ticket-price"
TicketsByBlocks = "ticket-by-outputs-blocks"
TicketSpendT = "ticket-spend-type"
TxPerBlock = "tx-per-block"
TxPerDay = "tx-per-day"
FeePerBlock = "fee-per-block"
TicketPoolSize = "ticket-pool-size"
TicketPoolValue = "ticket-pool-value"
)
// MileStone defines the various stages passed by vote on a given agenda.
// Activated is the height at which the delay time begins before a vote activates.
// HardForked is the height at which the consensus rule changes.
// VotingDone is the height at which voting is considered complete or when the
// status changes from "started" to either "failed" or "lockedin".
type MileStone struct {
ID int64 `json:"-"`
Status AgendaStatusType `json:"status"`
VotingStarted int64 `json:"votingStarted"`
VotingDone int64 `json:"votingdone"`
Activated int64 `json:"activated"`
HardForked int64 `json:"hardforked"`
StartTime time.Time `json:"starttime"`
ExpireTime time.Time `json:"expiretime"`
}
// AgendaSummary describes a short summary of a given agenda that includes
// vote choices tally and deployment rule change intervals.
type AgendaSummary struct {
Yes uint32
No uint32
Abstain uint32
VotingStarted int64
LockedIn int64
}
// TreasurySpendVotes summarizes the vote tally for a tspend.
type TreasurySpendVotes struct {
Hash string `json:"hash"`
Expiry int64 `json:"expiry"`
VoteStart int64 `json:"votestart"`
VoteEnd int64 `json:"voteend"`
YesVotes int64 `json:"yesvotes"`
NoVotes int64 `json:"novotes"`
}
// TreasurySpendMetaData extends TreasurySpendVotes and contains some
// status-dependent data representations for display purposes.
type TreasurySpendMetaData struct {
*TreasurySpendVotes
PoliteiaKey string
VoteEndDate time.Time
VoteStartDate time.Time
NextTVI int64
NextTVITime time.Time
Approved bool
QuorumAchieved bool
QuorumCount int64
MaxVotes int64
EligibleVotes int64
RequiredYesVotes int64
TotalVotes int64
PassPercent float32
Approval float32
}
// BlockChainData defines data holding the latest block chain state from the
// getblockchaininfo rpc endpoint.
type BlockChainData struct {
Chain string
SyncHeight int64
BestHeight int64
BestBlockHash string
Difficulty uint32
VerificationProgress float64
ChainWork string
IsInitialBlockDownload bool
MaxBlockSize int64
AgendaMileStones map[string]MileStone
}
// SyncResult is the result of a database sync operation, containing the height
// of the last block and an error value.
type SyncResult struct {
Height int64
Error error
}
// JSONB is used to implement the sql.Scanner and driver.Valuer interfaces
// required for the type to make a postgresql compatible JSONB type.
type JSONB map[string]interface{}
// Value satisfies driver.Valuer
func (p VinTxPropertyARRAY) Value() (driver.Value, error) {
j, err := json.Marshal(p)
return j, err
}
// Scan satisfies sql.Scanner
func (p *VinTxPropertyARRAY) Scan(src interface{}) error {
source, ok := src.([]byte)
if !ok {
return fmt.Errorf("scan type assertion .([]byte) failed")
}
var i interface{}
err := json.Unmarshal(source, &i)
if err != nil {
return err
}
// Set this JSONB
is, ok := i.([]interface{})
if !ok {
return fmt.Errorf("type assertion .([]interface{}) failed")
}
numVin := len(is)
ba := make(VinTxPropertyARRAY, numVin)
for ii := range is {
VinTxPropertyMapIface, ok := is[ii].(map[string]interface{})
if !ok {
return fmt.Errorf("type assertion .(map[string]interface) failed")
}
b, _ := json.Marshal(VinTxPropertyMapIface)
err := json.Unmarshal(b, &ba[ii])
if err != nil {
return err
}
}
*p = ba
return nil
}
// DeletionSummary provides the number of rows removed from the tables when a
// block is removed.
type DeletionSummary struct {
Blocks, Vins, Vouts, Addresses, Transactions int64
VoutSpendTxIDs int64
Tickets, Votes, Misses int64
Treasury, Swaps int64
Timings *DeletionSummary // durations
}
// String makes a pretty summary of the totals.
func (s DeletionSummary) String() string {
if s.Timings == nil {
summary := fmt.Sprintf("%9d Blocks purged\n", s.Blocks)
summary += fmt.Sprintf("%9d Vins purged\n", s.Vins)
summary += fmt.Sprintf("%9d Vouts purged\n", s.Vouts)
summary += fmt.Sprintf("%9d Addresses purged\n", s.Addresses)
summary += fmt.Sprintf("%9d Transactions purged\n", s.Transactions)
summary += fmt.Sprintf("%9d Vout spend txids reset\n", s.VoutSpendTxIDs)
summary += fmt.Sprintf("%9d Tickets purged\n", s.Tickets)
summary += fmt.Sprintf("%9d Votes purged\n", s.Votes)
summary += fmt.Sprintf("%9d Misses purged\n", s.Misses)
summary += fmt.Sprintf("%9d Treasury transactions purged\n", s.Treasury)
summary += fmt.Sprintf("%9d Swaps purged", s.Swaps)
return summary
}
summary := fmt.Sprintf("%9d Blocks purged in %v\n", s.Blocks, time.Duration(s.Timings.Blocks))
summary += fmt.Sprintf("%9d Vins purged in %v\n", s.Vins, time.Duration(s.Timings.Vins))
summary += fmt.Sprintf("%9d Vouts purged in %v\n", s.Vouts, time.Duration(s.Timings.Vouts))
summary += fmt.Sprintf("%9d Addresses purged in %v\n", s.Addresses, time.Duration(s.Timings.Addresses))
summary += fmt.Sprintf("%9d Transactions purged in %v\n", s.Transactions, time.Duration(s.Timings.Transactions))
summary += fmt.Sprintf("%9d Vout spending tx row ids reset in %v\n", s.VoutSpendTxIDs, time.Duration(s.Timings.VoutSpendTxIDs))
summary += fmt.Sprintf("%9d Tickets purged in %v\n", s.Tickets, time.Duration(s.Timings.Tickets))
summary += fmt.Sprintf("%9d Votes purged in %v\n", s.Votes, time.Duration(s.Timings.Votes))
summary += fmt.Sprintf("%9d Misses purged in %v\n", s.Misses, time.Duration(s.Timings.Misses))
summary += fmt.Sprintf("%9d Treasury transactions purged in %v\n", s.Treasury, time.Duration(s.Timings.Treasury))
summary += fmt.Sprintf("%9d Swaps purged in %v", s.Swaps, time.Duration(s.Timings.Swaps))
return summary
}
// DeletionSummarySlice is used to define methods on DeletionSummary slices.
type DeletionSummarySlice []DeletionSummary
// Reduce returns a single DeletionSummary with the corresponding fields summed.
func (ds DeletionSummarySlice) Reduce() DeletionSummary {
var timings DeletionSummarySlice
var s DeletionSummary
for i := range ds {
s.Blocks += ds[i].Blocks
s.Vins += ds[i].Vins
s.Vouts += ds[i].Vouts
s.Addresses += ds[i].Addresses
s.Transactions += ds[i].Transactions
s.VoutSpendTxIDs += ds[i].VoutSpendTxIDs
s.Tickets += ds[i].Tickets
s.Votes += ds[i].Votes
s.Misses += ds[i].Misses
s.Treasury += ds[i].Treasury
s.Swaps += ds[i].Swaps
if ds[i].Timings != nil {
timings = append(timings, *ds[i].Timings)
}
}
if timings != nil {
timingsReduced := timings.Reduce()
s.Timings = &timingsReduced
}
return s
}
// VinTxPropertyARRAY is a slice of VinTxProperty structs that implements
// sql.Scanner and driver.Valuer.
type VinTxPropertyARRAY []VinTxProperty
// func VinTxPropertyToJSONB(vin *VinTxProperty) (JSONB, error) {
// var vinJSONB map[string]interface{}
// vinJSON, err := json.Marshal(vin)
// if err != nil {
// return vinJSONB, err
// }
// var vinInterface interface{}
// err = json.Unmarshal(vinJSON, &vinInterface)
// if err != nil {
// return vinJSONB, err
// }
// vinJSONB = vinInterface.(map[string]interface{})
// return vinJSONB, nil
// }
// UInt64Array represents a one-dimensional array of PostgreSQL integer types
type UInt64Array []uint64
// Scan implements the sql.Scanner interface.
func (a *UInt64Array) Scan(src interface{}) error {
switch src := src.(type) {
case []byte:
return a.scanBytes(src)
case string:
return a.scanBytes([]byte(src))
case nil:
*a = nil
return nil
}
return fmt.Errorf("pq: cannot convert %T to UInt64Array", src)
}
func (a *UInt64Array) scanBytes(src []byte) error {
elems, err := internal.ScanLinearArray(src, []byte{','}, "UInt64Array")
if err != nil {
return err
}
if *a != nil && len(elems) == 0 {
*a = (*a)[:0]
} else {
b := make(UInt64Array, len(elems))
for i, v := range elems {
if b[i], err = strconv.ParseUint(string(v), 10, 64); err != nil {
return fmt.Errorf("pq: parsing array element index %d: %v", i, err)
}
}
*a = b
}
return nil
}
// Value implements the driver.Valuer interface.
func (a UInt64Array) Value() (driver.Value, error) {
if a == nil {
return nil, nil
}
if n := len(a); n > 0 {
// There will be at least two curly brackets, N bytes of values,
// and N-1 bytes of delimiters.
b := make([]byte, 1, 1+2*n)
b[0] = '{'
b = strconv.AppendUint(b, a[0], 10)
for i := 1; i < n; i++ {
b = append(b, ',')
b = strconv.AppendUint(b, a[i], 10)
}
return string(append(b, '}')), nil
}
return "{}", nil
}