-
Notifications
You must be signed in to change notification settings - Fork 375
/
json_decode.go
471 lines (410 loc) · 11.6 KB
/
json_decode.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
package amino
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/gnolang/gno/tm2/pkg/errors"
)
// ----------------------------------------
// cdc.decodeReflectJSON
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectJSON(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if info.Type.Kind() == reflect.Interface && rv.Kind() == reflect.Ptr {
panic("should not happen")
}
if printLog {
fmt.Printf("(D) decodeReflectJSON(bz: %s, info: %v, rv: %#v (%v), fopts: %v)\n",
bz, info, rv.Interface(), rv.Type(), fopts)
defer func() {
fmt.Printf("(D) -> err: %v\n", err)
}()
}
// Special case for null for either interface, pointer, slice
// NOTE: This doesn't match the binary implementation completely.
if nullBytes(bz) {
rv.Set(defaultValue(rv.Type()))
return
}
// Dereference-and-construct if pointer.
rv = maybeDerefAndConstruct(rv)
// Handle the most special case, "well known".
if info.ConcreteInfo.IsJSONWellKnownType {
var ok bool
ok, err = decodeReflectJSONWellKnown(bz, info, rv, fopts)
if ok || err != nil {
return
}
}
// Handle override if a pointer to rv implements UnmarshalAmino.
if info.IsAminoMarshaler {
// First, decode repr instance from bytes.
rrv := reflect.New(info.ReprType.Type).Elem()
rinfo := info.ReprType
err = cdc.decodeReflectJSON(bz, rinfo, rrv, fopts)
if err != nil {
return
}
// Then, decode from repr instance.
uwrm := rv.Addr().MethodByName("UnmarshalAmino")
uwouts := uwrm.Call([]reflect.Value{rrv})
erri := uwouts[0].Interface()
if erri != nil {
err = erri.(error)
}
return
}
switch ikind := info.Type.Kind(); ikind {
// ----------------------------------------
// Complex
case reflect.Interface:
err = cdc.decodeReflectJSONInterface(bz, info, rv, fopts)
case reflect.Array:
err = cdc.decodeReflectJSONArray(bz, info, rv, fopts)
case reflect.Slice:
err = cdc.decodeReflectJSONSlice(bz, info, rv, fopts)
case reflect.Struct:
err = cdc.decodeReflectJSONStruct(bz, info, rv, fopts)
// ----------------------------------------
// Signed, Unsigned
case reflect.Int64, reflect.Int:
fallthrough
case reflect.Uint64, reflect.Uint:
if bz[0] != '"' || bz[len(bz)-1] != '"' {
err = errors.New(
"invalid character -- Amino:JSON int/int64/uint/uint64 expects quoted values for javascript numeric support, got: %v", //nolint: lll
string(bz),
)
if err != nil {
return
}
}
bz = bz[1 : len(bz)-1]
fallthrough
case reflect.Int32, reflect.Int16, reflect.Int8,
reflect.Uint32, reflect.Uint16, reflect.Uint8:
err = invokeStdlibJSONUnmarshal(bz, rv, fopts)
// ----------------------------------------
// Misc
case reflect.Float32, reflect.Float64:
if !fopts.Unsafe {
return errors.New("amino:JSON float* support requires `amino:\"unsafe\"`")
}
fallthrough
case reflect.Bool, reflect.String:
err = invokeStdlibJSONUnmarshal(bz, rv, fopts)
// ----------------------------------------
// Default
default:
panic(fmt.Sprintf("unsupported type %v", info.Type.Kind()))
}
return err
}
func invokeStdlibJSONUnmarshal(bz []byte, rv reflect.Value, fopts FieldOptions) error {
if !rv.CanAddr() && rv.Kind() != reflect.Ptr {
panic("rv not addressable nor pointer")
}
rrv := rv
if rv.Kind() != reflect.Ptr {
rrv = reflect.New(rv.Type())
}
if err := json.Unmarshal(bz, rrv.Interface()); err != nil {
return err
}
rv.Set(rrv.Elem())
return nil
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectJSONInterface(bz []byte, iinfo *TypeInfo, rv reflect.Value,
fopts FieldOptions,
) (err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectJSONInterface")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
/*
We don't make use of user-provided interface values because there are a
lot of edge cases.
* What if the type is mismatched?
* What if the JSON field entry is missing?
* Circular references?
*/
if !rv.IsNil() {
// We don't strictly need to set it nil, but lets keep it here for a
// while in case we forget, for defensive purposes.
rv.Set(iinfo.ZeroValue)
}
// Extract type_url.
typeURL, value, err := extractJSONTypeURL(bz)
if err != nil {
return
}
// NOTE: Unlike decodeReflectBinaryInterface, we already dealt with nil in decodeReflectJSON.
// Get concrete type info.
// NOTE: Unlike decodeReflectBinaryInterface, uses the full type_url string,
// which if generated by Amino, is the name preceded by a single slash.
var cinfo *TypeInfo
cinfo, err = cdc.getTypeInfoFromTypeURLRLock(typeURL, fopts)
if err != nil {
return
}
// Extract the value bytes.
if cinfo.IsJSONAnyValueType || (cinfo.IsAminoMarshaler && cinfo.ReprType.IsJSONAnyValueType) {
bz = value
} else {
bz, err = deriveJSONObject(bz, typeURL)
if err != nil {
return
}
}
// Construct the concrete type.
crv, irvSet := constructConcreteType(cinfo)
// Decode into the concrete type.
err = cdc.decodeReflectJSON(bz, cinfo, crv, fopts)
if err != nil {
rv.Set(irvSet) // Helps with debugging
return
}
// We need to set here, for when !PointerPreferred and the type
// is say, an array of bytes (e.g. [32]byte), then we must call
// rv.Set() *after* the value was acquired.
rv.Set(irvSet)
return err
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectJSONArray(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectJSONArray")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
length := info.Type.Len()
switch ert.Kind() {
case reflect.Uint8: // Special case: byte array
var buf []byte
err = json.Unmarshal(bz, &buf)
if err != nil {
return
}
if len(buf) != length {
err = fmt.Errorf("decodeReflectJSONArray: byte-length mismatch, got %v want %v",
len(buf), length)
}
reflect.Copy(rv, reflect.ValueOf(buf))
return
default: // General case.
var einfo *TypeInfo
einfo, err = cdc.getTypeInfoWLock(ert)
if err != nil {
return
}
// Read into rawSlice.
var rawSlice []json.RawMessage
if err = json.Unmarshal(bz, &rawSlice); err != nil {
return
}
if len(rawSlice) != length {
err = fmt.Errorf("decodeReflectJSONArray: length mismatch, got %v want %v", len(rawSlice), length)
return
}
// Decode each item in rawSlice.
for i := 0; i < length; i++ {
erv := rv.Index(i)
ebz := rawSlice[i]
err = cdc.decodeReflectJSON(ebz, einfo, erv, fopts)
if err != nil {
return
}
}
return
}
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectJSONSlice(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectJSONSlice")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
ert := info.Type.Elem()
switch ert.Kind() {
case reflect.Uint8: // Special case: byte slice
err = json.Unmarshal(bz, rv.Addr().Interface())
if err != nil {
return
}
if rv.Len() == 0 {
// Special case when length is 0.
// NOTE: We prefer nil slices.
rv.Set(info.ZeroValue)
}
// else {
// NOTE: Already set via json.Unmarshal() above.
// }
return
default: // General case.
var einfo *TypeInfo
einfo, err = cdc.getTypeInfoWLock(ert)
if err != nil {
return
}
// Read into rawSlice.
var rawSlice []json.RawMessage
if err = json.Unmarshal(bz, &rawSlice); err != nil {
return
}
// Special case when length is 0.
// NOTE: We prefer nil slices.
length := len(rawSlice)
if length == 0 {
rv.Set(info.ZeroValue)
return
}
// Read into a new slice.
esrt := reflect.SliceOf(ert) // TODO could be optimized.
srv := reflect.MakeSlice(esrt, length, length)
for i := 0; i < length; i++ {
erv := srv.Index(i)
ebz := rawSlice[i]
err = cdc.decodeReflectJSON(ebz, einfo, erv, fopts)
if err != nil {
return
}
}
// TODO do we need this extra step?
rv.Set(srv)
return
}
}
// CONTRACT: rv.CanAddr() is true.
func (cdc *Codec) decodeReflectJSONStruct(bz []byte, info *TypeInfo, rv reflect.Value, fopts FieldOptions) (err error) {
if !rv.CanAddr() {
panic("rv not addressable")
}
if printLog {
fmt.Println("(d) decodeReflectJSONStruct")
defer func() {
fmt.Printf("(d) -> err: %v\n", err)
}()
}
// Map all the fields(keys) to their blobs/bytes.
// NOTE: In decodeReflectBinaryStruct, we don't need to do this,
// since fields are encoded in order.
rawMap := make(map[string]json.RawMessage)
err = json.Unmarshal(bz, &rawMap)
if err != nil {
return
}
for _, field := range info.Fields {
// Get field rv and info.
frv := rv.Field(field.Index)
finfo := field.TypeInfo
// Get value from rawMap.
valueBytes := rawMap[field.JSONName]
if len(valueBytes) == 0 {
// TODO: Since the Go stdlib's JSON codec allows case-insensitive
// keys perhaps we need to also do case-insensitive lookups here.
// So "Vanilla" and "vanilla" would both match to the same field.
// It is actually a security flaw with encoding/json library
// - See https://github.com/golang/go/issues/14750
// but perhaps we are aiming for as much compatibility here.
// JAE: I vote we depart from encoding/json, than carry a vuln.
// Set to the zero value only if not omitempty
if !field.JSONOmitEmpty {
// Set nil/zero on frv.
frv.Set(defaultValue(frv.Type()))
}
continue
}
// Decode into field rv.
err = cdc.decodeReflectJSON(valueBytes, finfo, frv, fopts)
if err != nil {
return
}
}
return nil
}
// ----------------------------------------
// Misc.
type anyWrapper struct {
TypeURL string `json:"@type"`
Value json.RawMessage `json:"value"`
}
func extractJSONTypeURL(bz []byte) (typeURL string, value json.RawMessage, err error) {
anyw := new(anyWrapper)
err = json.Unmarshal(bz, anyw)
if err != nil {
err = fmt.Errorf("cannot parse Any JSON wrapper: %w", err)
return
}
// Get typeURL.
if anyw.TypeURL == "" {
err = errors.New("JSON encoding of interfaces require non-empty @type field")
return
}
typeURL = anyw.TypeURL
value = anyw.Value
return
}
func deriveJSONObject(bz []byte, typeURL string) (res []byte, err error) {
str := string(bz)
if len(bz) == 0 {
err = errors.New("expected JSON object but was empty")
return
}
if !strings.HasPrefix(str, "{") {
err = fmt.Errorf("expected JSON object but was not: %s", bz)
return
}
str = strings.TrimLeft(str, " \t\r\n")
if !strings.HasPrefix(str, "{") {
err = fmt.Errorf("expected JSON object representing Any to start with '{', but got %v", string(bz))
return
}
str = str[1:]
str = strings.TrimLeft(str, " \t\r\n")
if !strings.HasPrefix(str, `"@type"`) {
err = fmt.Errorf("expected JSON object representing Any to start with \"@type\" field, but got %v", string(bz))
return
}
str = str[7:]
str = strings.TrimLeft(str, " \t\r\n")
if !strings.HasPrefix(str, ":") {
err = fmt.Errorf("expected JSON object representing Any to start with \"@type\" field, but got %v", string(bz))
return
}
str = str[1:]
str = strings.TrimLeft(str, " \t\r\n")
if !strings.HasPrefix(str, fmt.Sprintf(`"%v"`, typeURL)) {
err = fmt.Errorf("expected JSON object representing Any to start with \"@type\":\"%v\", but got %v", typeURL, string(bz))
return
}
str = str[2+len(typeURL):]
str = strings.TrimLeft(str, ",")
return []byte("{" + str), nil
}
func nullBytes(b []byte) bool {
return bytes.Equal(b, []byte(`null`))
}
func unquoteString(in string) (out string, err error) {
err = json.Unmarshal([]byte(in), &out)
return out, err
}