forked from eoscanada/eos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
1657 lines (1334 loc) · 38.3 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
package eos
import (
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/eoscanada/eos-go/ecc"
"github.com/tidwall/gjson"
)
var symbolRegex = regexp.MustCompile("^[0-9],[A-Z]{1,7}$")
var symbolCodeRegex = regexp.MustCompile("^[A-Z]{1,7}$")
// For reference:
// https://github.com/mithrilcoin-io/EosCommander/blob/master/app/src/main/java/io/mithrilcoin/eoscommander/data/remote/model/types/EosByteWriter.java
type Name string
type AccountName Name
type PermissionName Name
type ActionName Name
type TableName Name
type ScopeName Name
func AN(in string) AccountName { return AccountName(in) }
func ActN(in string) ActionName { return ActionName(in) }
func PN(in string) PermissionName { return PermissionName(in) }
type SafeString string
func (ss *SafeString) UnmarshalBinary(d *Decoder) error {
s, e := d.SafeReadUTF8String()
if e != nil {
return e
}
*ss = SafeString(s)
return nil
}
type AccountResourceLimit struct {
Used Int64 `json:"used"`
Available Int64 `json:"available"`
Max Int64 `json:"max"`
}
type DelegatedBandwidth struct {
From AccountName `json:"from"`
To AccountName `json:"to"`
NetWeight Asset `json:"net_weight"`
CPUWeight Asset `json:"cpu_weight"`
}
type TotalResources struct {
Owner AccountName `json:"owner"`
NetWeight Asset `json:"net_weight"`
CPUWeight Asset `json:"cpu_weight"`
RAMBytes Int64 `json:"ram_bytes"`
}
type VoterInfo struct {
Owner AccountName `json:"owner"`
Proxy AccountName `json:"proxy"`
Producers []AccountName `json:"producers"`
Staked Int64 `json:"staked"`
LastVoteWeight Float64 `json:"last_vote_weight"`
ProxiedVoteWeight Float64 `json:"proxied_vote_weight"`
IsProxy byte `json:"is_proxy"`
}
type RefundRequest struct {
Owner AccountName `json:"owner"`
RequestTime JSONTime `json:"request_time"` // {"name":"request_time", "type":"time_point_sec"},
NetAmount Asset `json:"net_amount"`
CPUAmount Asset `json:"cpu_amount"`
}
type CompressionType uint8
const (
CompressionNone = CompressionType(iota)
CompressionZlib
)
func (c CompressionType) String() string {
switch c {
case CompressionNone:
return "none"
case CompressionZlib:
return "zlib"
default:
return ""
}
}
func (c CompressionType) MarshalJSON() ([]byte, error) {
return json.Marshal(c.String())
}
func (c *CompressionType) UnmarshalJSON(data []byte) error {
tryNext, err := c.tryUnmarshalJSONAsString(data)
if err != nil && !tryNext {
return err
}
if tryNext {
_, err := c.tryUnmarshalJSONAsUint8(data)
if err != nil {
return err
}
}
return nil
}
func (c *CompressionType) tryUnmarshalJSONAsString(data []byte) (tryNext bool, err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
_, isTypeError := err.(*json.UnmarshalTypeError)
// Let's continue with next handler is we hit a type error, might be an integer...
return isTypeError, err
}
switch s {
case "none":
*c = CompressionNone
case "zlib":
*c = CompressionZlib
default:
return false, fmt.Errorf("unknown compression type %s", s)
}
return false, nil
}
func (c *CompressionType) tryUnmarshalJSONAsUint8(data []byte) (tryNext bool, err error) {
var s uint8
err = json.Unmarshal(data, &s)
if err != nil {
return false, err
}
switch s {
case 0:
*c = CompressionNone
case 1:
*c = CompressionZlib
default:
return false, fmt.Errorf("unknown compression type %d", s)
}
return false, nil
}
// CurrencyName
type CurrencyName string
type Bool bool
func (b *Bool) UnmarshalJSON(data []byte) error {
var num int
err := json.Unmarshal(data, &num)
if err == nil {
*b = Bool(num != 0)
return nil
}
var boolVal bool
if err := json.Unmarshal(data, &boolVal); err != nil {
return fmt.Errorf("couldn't unmarshal bool as int or true/false: %s", err)
}
*b = Bool(boolVal)
return nil
}
// Asset
// NOTE: there's also ExtendedAsset which is a quantity with the attached contract (AccountName)
type Asset struct {
Amount Int64
Symbol
}
func (a Asset) Add(other Asset) Asset {
if a.Symbol != other.Symbol {
panic("Add applies only to assets with the same symbol")
}
return Asset{Amount: a.Amount + other.Amount, Symbol: a.Symbol}
}
func (a Asset) Sub(other Asset) Asset {
if a.Symbol != other.Symbol {
panic("Sub applies only to assets with the same symbol")
}
return Asset{Amount: a.Amount - other.Amount, Symbol: a.Symbol}
}
func (a Asset) String() string {
amt := a.Amount
if amt < 0 {
amt = -amt
}
precisionDigitCount := int(a.Symbol.Precision)
dotAndPrecisionDigitCount := precisionDigitCount + 1
strInt := strconv.FormatInt(int64(amt), 10)
if len(strInt) < dotAndPrecisionDigitCount {
// prepend `0` for the difference:
strInt = strings.Repeat("0", dotAndPrecisionDigitCount-len(strInt)) + strInt
}
result := strInt
if a.Symbol.Precision > 0 {
result = strInt[:len(strInt)-precisionDigitCount] + "." + strInt[len(strInt)-precisionDigitCount:]
}
if a.Amount < 0 {
result = "-" + result
}
return fmt.Sprintf("%s %s", result, a.Symbol.Symbol)
}
type ExtendedAsset struct {
Asset Asset `json:"quantity"`
Contract AccountName `json:"contract"`
}
// NOTE: there's also a new ExtendedSymbol (which includes the contract (as AccountName) on which it is)
type Symbol struct {
Precision uint8
Symbol string
// Caching of symbol code if it was computed once
symbolCode uint64
}
func NewSymbolFromUint64(value uint64) (out Symbol) {
out.Precision = uint8(value & 0xFF)
out.symbolCode = value >> 8
out.Symbol = SymbolCode(out.symbolCode).String()
return
}
func NameToSymbol(name Name) (Symbol, error) {
symbol := Symbol{}
value, err := StringToName(string(name))
if err != nil {
return symbol, fmt.Errorf("name %s is invalid: %s", name, err)
}
symbol.Precision = uint8(value & 0xFF)
symbol.symbolCode = value >> 8
symbol.Symbol = SymbolCode(symbol.symbolCode).String()
return symbol, nil
}
func StringToSymbol(str string) (Symbol, error) {
symbol := Symbol{}
if !symbolRegex.MatchString(str) {
return symbol, fmt.Errorf("%s is not a valid symbol", str)
}
precision, _ := strconv.ParseUint(string(str[0]), 10, 8)
symbol.Precision = uint8(precision)
symbol.Symbol = str[2:]
return symbol, nil
}
func MustStringToSymbol(str string) Symbol {
symbol, err := StringToSymbol(str)
if err != nil {
panic("invalid symbol " + str)
}
return symbol
}
func (s Symbol) SymbolCode() (SymbolCode, error) {
if s.symbolCode != 0 {
return SymbolCode(s.symbolCode), nil
}
symbolCode, err := StringToSymbolCode(s.Symbol)
if err != nil {
return 0, err
}
return SymbolCode(symbolCode), nil
}
func (s Symbol) MustSymbolCode() SymbolCode {
symbolCode, err := StringToSymbolCode(s.Symbol)
if err != nil {
panic("invalid symbol code " + s.Symbol)
}
return symbolCode
}
func (s Symbol) ToUint64() (uint64, error) {
symbolCode, err := s.SymbolCode()
if err != nil {
return 0, fmt.Errorf("symbol %s is not a valid symbol code: %s", s.Symbol, err)
}
return uint64(symbolCode)<<8 | uint64(s.Precision), nil
}
func (s Symbol) ToName() (string, error) {
u, err := s.ToUint64()
if err != nil {
return "", err
}
return NameToString(u), nil
}
func (s Symbol) String() string {
return fmt.Sprintf("%d,%s", s.Precision, s.Symbol)
}
type SymbolCode uint64
func NameToSymbolCode(name Name) (SymbolCode, error) {
value, err := StringToName(string(name))
if err != nil {
return 0, fmt.Errorf("name %s is invalid: %s", name, err)
}
return SymbolCode(value), nil
}
func StringToSymbolCode(str string) (SymbolCode, error) {
if len(str) > 7 {
return 0, fmt.Errorf("string is too long to be a valid symbol_code")
}
var symbolCode uint64
for i := len(str) - 1; i >= 0; i-- {
if str[i] < 'A' || str[i] > 'Z' {
return 0, fmt.Errorf("only uppercase letters allowed in symbol_code string")
}
symbolCode <<= 8
symbolCode = symbolCode | uint64(str[i])
}
return SymbolCode(symbolCode), nil
}
func (sc SymbolCode) ToName() string {
return NameToString(uint64(sc))
}
func (sc SymbolCode) String() string {
builder := strings.Builder{}
symbolCode := uint64(sc)
for i := 0; i < 7; i++ {
if symbolCode == 0 {
return builder.String()
}
builder.WriteByte(byte(symbolCode & 0xFF))
symbolCode >>= 8
}
return builder.String()
}
func (sc SymbolCode) MarshalJSON() (data []byte, err error) {
return []byte(`"` + sc.String() + `"`), nil
}
// EOSSymbol represents the standard EOS symbol on the chain. It's
// here just to speed up things.
var EOSSymbol = Symbol{Precision: 4, Symbol: "EOS"}
// REXSymbol represents the standard REX symbol on the chain. It's
// here just to speed up things.
var REXSymbol = Symbol{Precision: 4, Symbol: "REX"}
func NewEOSAsset(amount int64) Asset {
return Asset{Amount: Int64(amount), Symbol: EOSSymbol}
}
// NewAsset reads from a string an EOS asset.
//
// Deprecated: Use `NewAssetFromString` instead
func NewAsset(in string) (out Asset, err error) {
return NewAssetFromString(in)
}
// NewAssetFromString reads a string an decode it to an eos.Asset
// structure if possible. The input must contains an amount and
// a symbol. The precision is inferred based on the actual number
// of decimals present.
func NewAssetFromString(in string) (out Asset, err error) {
out, err = newAssetFromString(in)
if err != nil {
return out, err
}
if out.Symbol.Symbol == "" {
return out, fmt.Errorf("invalid format %q, expected an amount and a currency symbol", in)
}
return
}
func NewEOSAssetFromString(input string) (Asset, error) {
return NewFixedSymbolAssetFromString(EOSSymbol, input)
}
func NewREXAssetFromString(input string) (Asset, error) {
return NewFixedSymbolAssetFromString(REXSymbol, input)
}
func NewFixedSymbolAssetFromString(symbol Symbol, input string) (out Asset, err error) {
integralPart, decimalPart, symbolPart, err := splitAsset(input)
if err != nil {
return out, err
}
symbolCode := symbol.MustSymbolCode().String()
precision := symbol.Precision
if len(decimalPart) > int(precision) {
return out, fmt.Errorf("symbol %s precision mismatch: expected %d, got %d", symbol, precision, len(decimalPart))
}
if symbolPart != "" && symbolPart != symbolCode {
return out, fmt.Errorf("symbol %s code mismatch: expected %s, got %s", symbol, symbolCode, symbolPart)
}
if len(decimalPart) < int(precision) {
decimalPart += strings.Repeat("0", int(precision)-len(decimalPart))
}
val, err := strconv.ParseInt(integralPart+decimalPart, 10, 64)
if err != nil {
return out, err
}
return Asset{
Amount: Int64(val),
Symbol: Symbol{Precision: precision, Symbol: symbolCode},
}, nil
}
func newAssetFromString(in string) (out Asset, err error) {
integralPart, decimalPart, symbolPart, err := splitAsset(in)
if err != nil {
return out, err
}
val, err := strconv.ParseInt(integralPart+decimalPart, 10, 64)
if err != nil {
return out, err
}
out.Amount = Int64(val)
out.Symbol.Precision = uint8(len(decimalPart))
out.Symbol.Symbol = symbolPart
return
}
func splitAsset(input string) (integralPart, decimalPart, symbolPart string, err error) {
input = strings.Trim(input, " ")
if len(input) == 0 {
return "", "", "", fmt.Errorf("input cannot be empty")
}
parts := strings.Split(input, " ")
if len(parts) >= 1 {
integralPart, decimalPart, err = splitAssetAmount(parts[0])
if err != nil {
return
}
}
if len(parts) == 2 {
symbolPart = parts[1]
if len(symbolPart) > 7 {
return "", "", "", fmt.Errorf("invalid asset %q, symbol should have less than 7 characters", input)
}
}
if len(parts) > 2 {
return "", "", "", fmt.Errorf("invalid asset %q, expecting an amount alone or an amount and a currency symbol", input)
}
return
}
func splitAssetAmount(input string) (integralPart, decimalPart string, err error) {
parts := strings.Split(input, ".")
switch len(parts) {
case 1:
integralPart = parts[0]
case 2:
integralPart = parts[0]
decimalPart = parts[1]
if len(decimalPart) > math.MaxUint8 {
err = fmt.Errorf("invalid asset amount precision %q, should have less than %d characters", input, math.MaxUint8)
}
default:
return "", "", fmt.Errorf("invalid asset amount %q, expected amount to have at most a single dot", input)
}
return
}
func (a *Asset) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
asset, err := NewAsset(s)
if err != nil {
return err
}
*a = asset
return nil
}
func (a Asset) MarshalJSON() (data []byte, err error) {
return json.Marshal(a.String())
}
type Permission struct {
PermName string `json:"perm_name"`
Parent string `json:"parent"`
RequiredAuth Authority `json:"required_auth"`
}
type PermissionLevel struct {
Actor AccountName `json:"actor"`
Permission PermissionName `json:"permission"`
}
// NewPermissionLevel parses strings like `account@active`,
// `otheraccount@owner` and builds a PermissionLevel struct. It
// validates that there is a single optional @ (where permission
// defaults to 'active'), and validates length of account and
// permission names.
func NewPermissionLevel(in string) (out PermissionLevel, err error) {
parts := strings.Split(in, "@")
if len(parts) > 2 {
return out, fmt.Errorf("permission %q invalid, use account[@permission]", in)
}
if len(parts[0]) > 12 {
return out, fmt.Errorf("account name %q too long", parts[0])
}
out.Actor = AccountName(parts[0])
out.Permission = PermissionName("active")
if len(parts) == 2 {
if len(parts[1]) > 12 {
return out, fmt.Errorf("permission %q name too long", parts[1])
}
out.Permission = PermissionName(parts[1])
}
return
}
type PermissionLevelWeight struct {
Permission PermissionLevel `json:"permission"`
Weight uint16 `json:"weight"` // weight_type
}
type Authority struct {
Threshold uint32 `json:"threshold"`
Keys []KeyWeight `json:"keys,omitempty"`
Accounts []PermissionLevelWeight `json:"accounts,omitempty"`
Waits []WaitWeight `json:"waits,omitempty"`
}
type KeyWeight struct {
PublicKey ecc.PublicKey `json:"key"`
Weight uint16 `json:"weight"` // weight_type
}
type WaitWeight struct {
WaitSec uint32 `json:"wait_sec"`
Weight uint16 `json:"weight"` // weight_type
}
type GetRawCodeAndABIResp struct {
AccountName AccountName `json:"account_name"`
WASMasBase64 string `json:"wasm"`
ABIasBase64 string `json:"abi"`
}
type GetCodeResp struct {
AccountName AccountName `json:"account_name"`
CodeHash string `json:"code_hash"`
WASM string `json:"wasm"`
ABI ABI `json:"abi"`
}
type GetCodeHashResp struct {
AccountName AccountName `json:"account_name"`
CodeHash string `json:"code_hash"`
}
type GetABIResp struct {
AccountName AccountName `json:"account_name"`
ABI ABI `json:"abi"`
}
type ABIJSONToBinResp struct {
Binargs string `json:"binargs"`
}
type ABIBinToJSONResp struct {
Args M `json:"args"`
}
// JSONTime
type JSONTime struct {
time.Time
}
const JSONTimeFormat = "2006-01-02T15:04:05"
func (t JSONTime) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", t.Format(JSONTimeFormat))), nil
}
func (t *JSONTime) UnmarshalJSON(data []byte) (err error) {
if string(data) == "null" {
return nil
}
t.Time, err = time.Parse(`"`+JSONTimeFormat+`"`, string(data))
return err
}
// ParseJSONTime will parse a string into a JSONTime object
func ParseJSONTime(date string) (JSONTime, error) {
var t JSONTime
var err error
t.Time, err = time.Parse(JSONTimeFormat, string(date))
return t, err
}
// HexBytes
type HexBytes []byte
func (t HexBytes) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(t))
}
func (t *HexBytes) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
*t, err = hex.DecodeString(s)
return
}
func (t HexBytes) String() string {
return hex.EncodeToString(t)
}
// Checksum256
type Checksum160 []byte
func (t Checksum160) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(t))
}
func (t *Checksum160) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
*t, err = hex.DecodeString(s)
return
}
type Checksum256 []byte
func (t Checksum256) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(t))
}
func (t *Checksum256) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
*t, err = hex.DecodeString(s)
return
}
func (t Checksum256) String() string {
return hex.EncodeToString(t)
}
type Checksum512 []byte
func (t Checksum512) MarshalJSON() ([]byte, error) {
return json.Marshal(hex.EncodeToString(t))
}
func (t *Checksum512) UnmarshalJSON(data []byte) (err error) {
var s string
err = json.Unmarshal(data, &s)
if err != nil {
return
}
*t, err = hex.DecodeString(s)
return
}
// SHA256Bytes is deprecated and renamed to Checksum256 for
// consistency. Please update your code as this type will eventually
// be phased out.
type SHA256Bytes = Checksum256
type Varuint32 uint32
type Varint32 int32
// Tstamp
type Tstamp struct {
time.Time
}
func (t Tstamp) MarshalJSON() ([]byte, error) {
return json.Marshal(fmt.Sprintf("%d", t.UnixNano()))
}
func (t *Tstamp) UnmarshalJSON(data []byte) (err error) {
var unixNano int64
if data[0] == '"' {
var s string
if err = json.Unmarshal(data, &s); err != nil {
return
}
unixNano, err = strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
} else {
unixNano, err = strconv.ParseInt(string(data), 10, 64)
if err != nil {
return err
}
}
*t = Tstamp{time.Unix(0, unixNano)}
return nil
}
// BlockNum extracts the block number (or height) from a hex-encoded block ID.
func BlockNum(blockID string) uint32 {
if len(blockID) < 8 {
return 0
}
bin, err := hex.DecodeString(blockID[:8])
if err != nil {
return 0
}
return binary.BigEndian.Uint32(bin)
}
type BlockTimestamp struct {
time.Time
}
const BlockTimestampFormat = "2006-01-02T15:04:05.999"
func (t BlockTimestamp) MarshalJSON() ([]byte, error) {
strTime := t.Format(BlockTimestampFormat)
if len(strTime) == len("2006-01-02T15:04:05.5") {
strTime += "00"
}
return []byte(fmt.Sprintf("%q", strTime)), nil
}
func (t *BlockTimestamp) UnmarshalJSON(data []byte) (err error) {
if string(data) == "null" {
return nil
}
t.Time, err = time.Parse(`"`+BlockTimestampFormat+`"`, string(data))
if err != nil {
t.Time, err = time.Parse(`"`+BlockTimestampFormat+`Z07:00"`, string(data))
}
return err
}
// TimePoint represents the number of microseconds since EPOCH (Jan 1st 1970)
type TimePoint uint64
func (f TimePoint) String() string {
return formatTimePoint(f, true)
}
func (f TimePoint) MarshalJSON() ([]byte, error) {
return []byte(`"` + formatTimePoint(f, true) + `"`), nil
}
func (f *TimePoint) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
out, err := time.Parse(standardTimePointFormat, s)
if err != nil {
return err
}
*f = TimePoint(out.UnixNano() / 1000)
return nil
}
// TimePointSec represents the number of seconds since EPOCH (Jan 1st 1970)
type TimePointSec uint32
func (f TimePointSec) String() string {
return formatTimePointSec(f)
}
func (f TimePointSec) MarshalJSON() ([]byte, error) {
return []byte(`"` + formatTimePointSec(f) + `"`), nil
}
func (f *TimePointSec) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
out, err := time.Parse(standardTimePointFormat, s)
if err != nil {
return err
}
*f = TimePointSec(out.Unix())
return nil
}
type JSONFloat64 = Float64
type Float64 float64
func (f *Float64) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return errors.New("empty value")
}
if data[0] == '"' {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
val, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
*f = Float64(val)
return nil
}
var fl float64
if err := json.Unmarshal(data, &fl); err != nil {
return err
}
*f = Float64(fl)
return nil
}
// JSONInt64 is deprecated in favor of Int64.
type JSONInt64 = Int64
type Int64 int64
func (i Int64) MarshalJSON() (data []byte, err error) {
if i > 0xffffffff || i < -0xffffffff {
encodedInt, err := json.Marshal(int64(i))
if err != nil {
return nil, err
}
data = append([]byte{'"'}, encodedInt...)
data = append(data, '"')
return data, nil
}
return json.Marshal(int64(i))
}
func (i *Int64) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return errors.New("empty value")
}
if data[0] == '"' {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
val, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
*i = Int64(val)
return nil
}
var v int64
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = Int64(v)
return nil
}
type Uint64 uint64
func (i Uint64) MarshalJSON() (data []byte, err error) {
if i > 0xffffffff {
encodedInt, err := json.Marshal(uint64(i))
if err != nil {
return nil, err
}
data = append([]byte{'"'}, encodedInt...)
data = append(data, '"')
return data, nil
}
return json.Marshal(uint64(i))
}
func (i *Uint64) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return errors.New("empty value")
}
if data[0] == '"' {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
val, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return err