forked from eoscanada/eos-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
816 lines (645 loc) · 16.9 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
package eos
import (
"encoding/base64"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/eoscanada/eos-go/ecc"
)
// 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 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 JSONFloat64 `json:"last_vote_weight"`
ProxiedVoteWeight JSONFloat64 `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 {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
switch s {
case "zlib":
*c = CompressionZlib
default:
*c = CompressionNone
}
return 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
}
strInt := fmt.Sprintf("%d", amt)
if len(strInt) < int(a.Symbol.Precision+1) {
// prepend `0` for the difference:
strInt = strings.Repeat("0", int(a.Symbol.Precision+uint8(1))-len(strInt)) + strInt
}
var result string
if a.Symbol.Precision == 0 {
result = strInt
} else {
result = strInt[:len(strInt)-int(a.Symbol.Precision)] + "." + strInt[len(strInt)-int(a.Symbol.Precision):]
}
if a.Amount < 0 {
result = "-" + result
}
return fmt.Sprintf("%s %s", result, a.Symbol.Symbol)
}
type ExtendedAsset struct {
Asset Asset `json:"asset"`
Contract AccountName
}
// NOTE: there's also a new ExtendedSymbol (which includes the contract (as AccountName) on which it is)
type Symbol struct {
Precision uint8
Symbol string
}
type SymbolCode uint64
// EOSSymbol represents the standard EOS symbol on the chain. It's
// here just to speed up things.
var EOSSymbol = Symbol{Precision: 4, Symbol: "EOS"}
func NewEOSAssetFromString(amount string) (out Asset, err error) {
if len(amount) == 0 {
return out, fmt.Errorf("cannot be an empty string")
}
if strings.Contains(amount, " EOS") {
amount = strings.Replace(amount, " EOS", "", 1)
}
if !strings.Contains(amount, ".") {
val, err := strconv.ParseInt(amount, 10, 64)
if err != nil {
return out, err
}
return NewEOSAsset(val * 10000), nil
}
parts := strings.Split(amount, ".")
if len(parts) != 2 {
return out, fmt.Errorf("cannot have two . in amount")
}
if len(parts[1]) > 4 {
return out, fmt.Errorf("EOS has only 4 decimals")
}
val, err := strconv.ParseInt(strings.Replace(amount, ".", "", 1), 10, 64)
if err != nil {
return out, err
}
return NewEOSAsset(val * int64(math.Pow10(4-len(parts[1])))), nil
}
func NewEOSAsset(amount int64) Asset {
return Asset{Amount: amount, Symbol: EOSSymbol}
}
// NewAsset parses a string like `1000.0000 EOS` into a properly setup Asset
func NewAsset(in string) (out Asset, err error) {
sec := strings.SplitN(in, " ", 2)
if len(sec) != 2 {
return out, fmt.Errorf("invalid format %q, expected an amount and a currency symbol", in)
}
if len(sec[1]) > 7 {
return out, fmt.Errorf("currency symbol %q too long", sec[1])
}
out.Symbol.Symbol = sec[1]
amount := sec[0]
amountSec := strings.SplitN(amount, ".", 2)
if len(amountSec) == 2 {
out.Symbol.Precision = uint8(len(amountSec[1]))
}
val, err := strconv.ParseInt(strings.Replace(amount, ".", "", 1), 10, 64)
if err != nil {
return out, err
}
out.Amount = val
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"
func (t BlockTimestamp) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", t.Format(BlockTimestampFormat))), 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
// TimePointSec represents the number of seconds since EPOCH (Jan 1st 1970)
type TimePointSec uint32
type JSONFloat64 float64
func (f *JSONFloat64) 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 = JSONFloat64(val)
return nil
}
var fl float64
if err := json.Unmarshal(data, &fl); err != nil {
return err
}
*f = JSONFloat64(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
}
*i = Uint64(val)
return nil
}
var v uint64
if err := json.Unmarshal(data, &v); err != nil {
return err
}
*i = Uint64(v)
return nil
}
type Uint128 struct {
Lo uint64
Hi uint64
}
type Int128 Uint128
type Float128 Uint128
// func (i Int128) BigInt() *big.Int {
// // decode the Lo and Hi to handle the sign
// return nil
// }
// func (i Uint128) BigInt() *big.Int {
// // no sign to handle, all good..
// return nil
// }
// func NewInt128(i *big.Int) (Int128, error) {
// // if the big Int overflows the JSONInt128 limits..
// return Int128{}, nil
// }
// func NewUint128(i *big.Int) (Uint128, error) {
// // if the big Int overflows the JSONInt128 limits..
// return Uint128{}, nil
// }
func (i Uint128) MarshalJSON() (data []byte, err error) {
return json.Marshal(i.String())
}
func (i Int128) MarshalJSON() (data []byte, err error) {
return json.Marshal(Uint128(i).String())
}
func (i Float128) MarshalJSON() (data []byte, err error) {
return json.Marshal(Uint128(i).String())
}
func (i Uint128) String() string {
// Same for Int128, Float128
number := make([]byte, 16)
binary.LittleEndian.PutUint64(number[:], i.Lo)
binary.LittleEndian.PutUint64(number[8:], i.Hi)
return fmt.Sprintf("0x%s%s", hex.EncodeToString(number[:8]), hex.EncodeToString(number[8:]))
}
func (i *Int128) UnmarshalJSON(data []byte) error {
var el Uint128
if err := json.Unmarshal(data, &el); err != nil {
return err
}
out := Int128(el)
*i = out
return nil
}
func (i *Float128) UnmarshalJSON(data []byte) error {
var el Uint128
if err := json.Unmarshal(data, &el); err != nil {
return err
}
out := Float128(el)
*i = out
return nil
}
func (i *Uint128) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if !strings.HasPrefix(s, "0x") && !strings.HasPrefix(s, "0X") {
return fmt.Errorf("int128 expects 0x prefix")
}
truncatedVal := s[2:]
if len(truncatedVal) != 32 {
return fmt.Errorf("int128 expects 32 characters after 0x, had %d", len(truncatedVal))
}
loHex := truncatedVal[:16]
hiHex := truncatedVal[16:]
lo, err := hex.DecodeString(loHex)
if err != nil {
return err
}
hi, err := hex.DecodeString(hiHex)
if err != nil {
return err
}
loUint := binary.LittleEndian.Uint64(lo)
hiUint := binary.LittleEndian.Uint64(hi)
i.Lo = loUint
i.Hi = hiUint
return nil
}
// Blob
// Blob is base64 encoded data
// https://github.com/EOSIO/fc/blob/0e74738e938c2fe0f36c5238dbc549665ddaef82/include/fc/variant.hpp#L47
type Blob string
// Data returns decoded base64 data
func (b Blob) Data() ([]byte, error) {
return base64.StdEncoding.DecodeString(string(b))
}
// String returns the blob as a string
func (b Blob) String() string {
return string(b)
}