This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
amino.go
446 lines (391 loc) · 10.9 KB
/
amino.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
package amino
import (
"bytes"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"time"
)
//----------------------------------------
// Global methods for global sealed codec.
var gcdc *Codec
// we use this time to init. a zero value (opposed to reflect.Zero which gives time.Time{} / 01-01-01 00:00:00)
var zeroTime time.Time
const (
unixEpochStr = "1970-01-01 00:00:00 +0000 UTC"
epochFmt = "2006-01-02 15:04:05 +0000 UTC"
)
func init() {
gcdc = NewCodec().Seal()
var err error
zeroTime, err = time.Parse(epochFmt, unixEpochStr)
if err != nil {
panic("couldn't parse Zero value for time")
}
}
func MarshalBinary(o interface{}) ([]byte, error) {
return gcdc.MarshalBinary(o)
}
func MarshalBinaryWriter(w io.Writer, o interface{}) (n int64, err error) {
return gcdc.MarshalBinaryWriter(w, o)
}
func MustMarshalBinary(o interface{}) []byte {
return gcdc.MustMarshalBinary(o)
}
func MarshalBinaryBare(o interface{}) ([]byte, error) {
return gcdc.MarshalBinaryBare(o)
}
func MustMarshalBinaryBare(o interface{}) []byte {
return gcdc.MustMarshalBinaryBare(o)
}
func UnmarshalBinary(bz []byte, ptr interface{}) error {
return gcdc.UnmarshalBinary(bz, ptr)
}
func UnmarshalBinaryReader(r io.Reader, ptr interface{}, maxSize int64) (n int64, err error) {
return gcdc.UnmarshalBinaryReader(r, ptr, maxSize)
}
func MustUnmarshalBinary(bz []byte, ptr interface{}) {
gcdc.MustUnmarshalBinary(bz, ptr)
}
func UnmarshalBinaryBare(bz []byte, ptr interface{}) error {
return gcdc.UnmarshalBinaryBare(bz, ptr)
}
func MustUnmarshalBinaryBare(bz []byte, ptr interface{}) {
gcdc.MustUnmarshalBinaryBare(bz, ptr)
}
func MarshalJSON(o interface{}) ([]byte, error) {
return gcdc.MarshalJSON(o)
}
func UnmarshalJSON(bz []byte, ptr interface{}) error {
return gcdc.UnmarshalJSON(bz, ptr)
}
func MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
return gcdc.MarshalJSONIndent(o, prefix, indent)
}
//----------------------------------------
// Typ3
type Typ3 uint8
const (
// Typ3 types
Typ3_Varint = Typ3(0)
Typ3_8Byte = Typ3(1)
Typ3_ByteLength = Typ3(2)
//Typ3_Struct = Typ3(3)
//Typ3_StructTerm = Typ3(4)
Typ3_4Byte = Typ3(5)
//Typ3_List = Typ3(6)
//Typ3_Interface = Typ3(7)
)
func (typ Typ3) String() string {
switch typ {
case Typ3_Varint:
return "(U)Varint"
case Typ3_8Byte:
return "8Byte"
case Typ3_ByteLength:
return "ByteLength"
//case Typ3_Struct:
// return "Struct"
//case Typ3_StructTerm:
// return "StructTerm"
case Typ3_4Byte:
return "4Byte"
//case Typ3_List:
// return "List"
//case Typ3_Interface:
// return "Interface"
default:
return fmt.Sprintf("<Invalid Typ3 %X>", byte(typ))
}
}
//----------------------------------------
// *Codec methods
// MarshalBinary encodes the object o according to the Amino spec,
// but prefixed by a uvarint encoding of the object to encode.
// Use MarshalBinaryBare if you don't want byte-length prefixing.
//
// For consistency, MarshalBinary will first dereference pointers
// before encoding. MarshalBinary will panic if o is a nil-pointer,
// or if o is invalid.
func (cdc *Codec) MarshalBinary(o interface{}) ([]byte, error) {
// Write the bytes here.
var buf = new(bytes.Buffer)
// Write the bz without length-prefixing.
bz, err := cdc.MarshalBinaryBare(o)
if err != nil {
return nil, err
}
// Write uvarint(len(bz)).
err = EncodeUvarint(buf, uint64(len(bz)))
if err != nil {
return nil, err
}
// Write bz.
_, err = buf.Write(bz)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// MarshalBinaryWriter writes the bytes as would be returned from
// MarshalBinary to the writer w.
func (cdc *Codec) MarshalBinaryWriter(w io.Writer, o interface{}) (n int64, err error) {
var bz, _n = []byte(nil), int(0)
bz, err = cdc.MarshalBinary(o)
if err != nil {
return 0, err
}
_n, err = w.Write(bz) // TODO: handle overflow in 32-bit systems.
n = int64(_n)
return
}
// Panics if error.
func (cdc *Codec) MustMarshalBinary(o interface{}) []byte {
bz, err := cdc.MarshalBinary(o)
if err != nil {
panic(err)
}
return bz
}
// MarshalBinaryBare encodes the object o according to the Amino spec.
// MarshalBinaryBare doesn't prefix the byte-length of the encoding,
// so the caller must handle framing.
func (cdc *Codec) MarshalBinaryBare(o interface{}) ([]byte, error) {
// Dereference value if pointer.
var rv, _, isNilPtr = derefPointers(reflect.ValueOf(o))
if isNilPtr {
// NOTE: You can still do so by calling
// `.MarshalBinary(struct{ *SomeType })` or so on.
panic("MarshalBinary cannot marshal a nil pointer directly. Try wrapping in a struct?")
}
// Encode Amino:binary bytes.
var bz []byte
buf := new(bytes.Buffer)
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return nil, err
}
err = cdc.encodeReflectBinary(buf, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return nil, err
}
bz = buf.Bytes()
// If registered concrete, prepend prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
bz = append(pb, bz...)
}
return bz, nil
}
// Panics if error.
func (cdc *Codec) MustMarshalBinaryBare(o interface{}) []byte {
bz, err := cdc.MarshalBinaryBare(o)
if err != nil {
panic(err)
}
return bz
}
// Like UnmarshalBinaryBare, but will first decode the byte-length prefix.
// UnmarshalBinary will panic if ptr is a nil-pointer.
// Returns an error if not all of bz is consumed.
func (cdc *Codec) UnmarshalBinary(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("UnmarshalBinary cannot decode empty bytes")
}
// Read byte-length prefix.
u64, n := binary.Uvarint(bz)
if n < 0 {
return fmt.Errorf("Error reading msg byte-length prefix: got code %v", n)
}
if u64 > uint64(len(bz)-n) {
return fmt.Errorf("Not enough bytes to read in UnmarshalBinary, want %v more bytes but only have %v",
u64, len(bz)-n)
} else if u64 < uint64(len(bz)-n) {
return fmt.Errorf("Bytes left over in UnmarshalBinary, should read %v more bytes but have %v",
u64, len(bz)-n)
}
bz = bz[n:]
// Decode.
return cdc.UnmarshalBinaryBare(bz, ptr)
}
// Like UnmarshalBinaryBare, but will first read the byte-length prefix.
// UnmarshalBinaryReader will panic if ptr is a nil-pointer.
// If maxSize is 0, there is no limit (not recommended).
func (cdc *Codec) UnmarshalBinaryReader(r io.Reader, ptr interface{}, maxSize int64) (n int64, err error) {
if maxSize < 0 {
panic("maxSize cannot be negative.")
}
// Read byte-length prefix.
var l int64
var buf [binary.MaxVarintLen64]byte
for i := 0; i < len(buf); i++ {
_, err = r.Read(buf[i : i+1])
if err != nil {
return
}
n += 1
if buf[i]&0x80 == 0 {
break
}
if n >= maxSize {
err = fmt.Errorf("Read overflow, maxSize is %v but uvarint(length-prefix) is itself greater than maxSize.", maxSize)
}
}
u64, _ := binary.Uvarint(buf[:])
if err != nil {
return
}
if maxSize > 0 {
if uint64(maxSize) < u64 {
err = fmt.Errorf("Read overflow, maxSize is %v but this amino binary object is %v bytes.", maxSize, u64)
return
}
if (maxSize - n) < int64(u64) {
err = fmt.Errorf("Read overflow, maxSize is %v but this length-prefixed amino binary object is %v+%v bytes.", maxSize, n, u64)
return
}
}
l = int64(u64)
if l < 0 {
err = fmt.Errorf("Read overflow, this implementation can't read this because, why would anyone have this much data? Hello from 2018.")
}
// Read that many bytes.
var bz = make([]byte, l, l)
_, err = io.ReadFull(r, bz)
if err != nil {
return
}
n += l
// Decode.
err = cdc.UnmarshalBinaryBare(bz, ptr)
return
}
// Panics if error.
func (cdc *Codec) MustUnmarshalBinary(bz []byte, ptr interface{}) {
err := cdc.UnmarshalBinary(bz, ptr)
if err != nil {
panic(err)
}
}
// UnmarshalBinaryBare will panic if ptr is a nil-pointer.
func (cdc *Codec) UnmarshalBinaryBare(bz []byte, ptr interface{}) error {
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
panic("Unmarshal expects a pointer")
}
rv = rv.Elem()
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return err
}
// If registered concrete, consume and verify prefix bytes.
if info.Registered {
pb := info.Prefix.Bytes()
if len(bz) < 4 {
return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X", pb, bz)
} else if !bytes.Equal(bz[:4], pb) {
return fmt.Errorf("UnmarshalBinaryBare expected to read prefix bytes %X (since it is registered concrete) but got %X...", pb, bz[:4])
}
bz = bz[4:]
}
// Decode contents into rv.
n, err := cdc.decodeReflectBinary(bz, info, rv, FieldOptions{BinFieldNum: 1}, true)
if err != nil {
return fmt.Errorf("unmarshal to %v failed after %d bytes (%v): %X", info.Type, n, err, bz)
}
if n != len(bz) {
return fmt.Errorf("unmarshal to %v didn't read all bytes. Expected to read %v, only read %v: %X", info.Type, len(bz), n, bz)
}
return nil
}
// Panics if error.
func (cdc *Codec) MustUnmarshalBinaryBare(bz []byte, ptr interface{}) {
err := cdc.UnmarshalBinaryBare(bz, ptr)
if err != nil {
panic(err)
}
}
func (cdc *Codec) MarshalJSON(o interface{}) ([]byte, error) {
rv := reflect.ValueOf(o)
if rv.Kind() == reflect.Invalid {
return []byte("null"), nil
}
rt := rv.Type()
w := new(bytes.Buffer)
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return nil, err
}
// Write the disfix wrapper if it is a registered concrete type.
if info.Registered {
// Part 1:
err = writeStr(w, _fmt(`{"type":"%s","value":`, info.Name))
if err != nil {
return nil, err
}
}
// Write the rest from rv.
if err := cdc.encodeReflectJSON(w, info, rv, FieldOptions{}); err != nil {
return nil, err
}
// disfix wrapper continued...
if info.Registered {
// Part 2:
if err != nil {
return nil, err
}
err = writeStr(w, `}`)
if err != nil {
return nil, err
}
}
return w.Bytes(), nil
}
func (cdc *Codec) UnmarshalJSON(bz []byte, ptr interface{}) error {
if len(bz) == 0 {
return errors.New("UnmarshalJSON cannot decode empty bytes")
}
rv := reflect.ValueOf(ptr)
if rv.Kind() != reflect.Ptr {
return errors.New("UnmarshalJSON expects a pointer")
}
rv = rv.Elem()
rt := rv.Type()
info, err := cdc.getTypeInfo_wlock(rt)
if err != nil {
return err
}
// If registered concrete, consume and verify type wrapper.
if info.Registered {
// Consume type wrapper info.
name, bz_, err := decodeInterfaceJSON(bz)
if err != nil {
return err
}
// Check name against info.
if name != info.Name {
return fmt.Errorf("UnmarshalJSON wants to decode a %v but found a %v", info.Name, name)
}
bz = bz_
}
return cdc.decodeReflectJSON(bz, info, rv, FieldOptions{})
}
// MarshalJSONIndent calls json.Indent on the output of cdc.MarshalJSON
// using the given prefix and indent string.
func (cdc *Codec) MarshalJSONIndent(o interface{}, prefix, indent string) ([]byte, error) {
bz, err := cdc.MarshalJSON(o)
if err != nil {
return nil, err
}
var out bytes.Buffer
err = json.Indent(&out, bz, prefix, indent)
if err != nil {
return nil, err
}
return out.Bytes(), nil
}