github.com/516108736/tendermint@v0.36.0/libs/json/decoder.go (about) 1 package json 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "fmt" 8 "reflect" 9 ) 10 11 // Unmarshal unmarshals JSON into the given value, using Amino-compatible JSON encoding (strings 12 // for 64-bit numbers, and type wrappers for registered types). 13 func Unmarshal(bz []byte, v interface{}) error { 14 return decode(bz, v) 15 } 16 17 func decode(bz []byte, v interface{}) error { 18 if len(bz) == 0 { 19 return errors.New("cannot decode empty bytes") 20 } 21 22 rv := reflect.ValueOf(v) 23 if rv.Kind() != reflect.Ptr { 24 return errors.New("must decode into a pointer") 25 } 26 rv = rv.Elem() 27 28 // If this is a registered type, defer to interface decoder regardless of whether the input is 29 // an interface or a bare value. This retains Amino's behavior, but is inconsistent with 30 // behavior in structs where an interface field will get the type wrapper while a bare value 31 // field will not. 32 if typeRegistry.name(rv.Type()) != "" { 33 return decodeReflectInterface(bz, rv) 34 } 35 36 return decodeReflect(bz, rv) 37 } 38 39 func decodeReflect(bz []byte, rv reflect.Value) error { 40 if !rv.CanAddr() { 41 return errors.New("value is not addressable") 42 } 43 44 // Handle null for slices, interfaces, and pointers 45 if bytes.Equal(bz, []byte("null")) { 46 rv.Set(reflect.Zero(rv.Type())) 47 return nil 48 } 49 50 // Dereference-and-construct pointers, to handle nested pointers. 51 for rv.Kind() == reflect.Ptr { 52 if rv.IsNil() { 53 rv.Set(reflect.New(rv.Type().Elem())) 54 } 55 rv = rv.Elem() 56 } 57 58 // Times must be UTC and end with Z 59 if rv.Type() == timeType { 60 switch { 61 case len(bz) < 2 || bz[0] != '"' || bz[len(bz)-1] != '"': 62 return fmt.Errorf("JSON time must be an RFC3339 string, but got %q", bz) 63 case bz[len(bz)-2] != 'Z': 64 return fmt.Errorf("JSON time must be UTC and end with 'Z', but got %q", bz) 65 } 66 } 67 68 // If value implements json.Umarshaler, call it. 69 if rv.Addr().Type().Implements(jsonUnmarshalerType) { 70 return rv.Addr().Interface().(json.Unmarshaler).UnmarshalJSON(bz) 71 } 72 73 switch rv.Type().Kind() { 74 // Decode complex types recursively. 75 case reflect.Slice, reflect.Array: 76 return decodeReflectList(bz, rv) 77 78 case reflect.Map: 79 return decodeReflectMap(bz, rv) 80 81 case reflect.Struct: 82 return decodeReflectStruct(bz, rv) 83 84 case reflect.Interface: 85 return decodeReflectInterface(bz, rv) 86 87 // For 64-bit integers, unwrap expected string and defer to stdlib for integer decoding. 88 case reflect.Int64, reflect.Int, reflect.Uint64, reflect.Uint: 89 if bz[0] != '"' || bz[len(bz)-1] != '"' { 90 return fmt.Errorf("invalid 64-bit integer encoding %q, expected string", string(bz)) 91 } 92 bz = bz[1 : len(bz)-1] 93 fallthrough 94 95 // Anything else we defer to the stdlib. 96 default: 97 return decodeStdlib(bz, rv) 98 } 99 } 100 101 func decodeReflectList(bz []byte, rv reflect.Value) error { 102 if !rv.CanAddr() { 103 return errors.New("list value is not addressable") 104 } 105 106 switch rv.Type().Elem().Kind() { 107 // Decode base64-encoded bytes using stdlib decoder, via byte slice for arrays. 108 case reflect.Uint8: 109 if rv.Type().Kind() == reflect.Array { 110 var buf []byte 111 if err := json.Unmarshal(bz, &buf); err != nil { 112 return err 113 } 114 if len(buf) != rv.Len() { 115 return fmt.Errorf("got %v bytes, expected %v", len(buf), rv.Len()) 116 } 117 reflect.Copy(rv, reflect.ValueOf(buf)) 118 119 } else if err := decodeStdlib(bz, rv); err != nil { 120 return err 121 } 122 123 // Decode anything else into a raw JSON slice, and decode values recursively. 124 default: 125 var rawSlice []json.RawMessage 126 if err := json.Unmarshal(bz, &rawSlice); err != nil { 127 return err 128 } 129 if rv.Type().Kind() == reflect.Slice { 130 rv.Set(reflect.MakeSlice(reflect.SliceOf(rv.Type().Elem()), len(rawSlice), len(rawSlice))) 131 } 132 if rv.Len() != len(rawSlice) { // arrays of wrong size 133 return fmt.Errorf("got list of %v elements, expected %v", len(rawSlice), rv.Len()) 134 } 135 for i, bz := range rawSlice { 136 if err := decodeReflect(bz, rv.Index(i)); err != nil { 137 return err 138 } 139 } 140 } 141 142 // Replace empty slices with nil slices, for Amino compatibility 143 if rv.Type().Kind() == reflect.Slice && rv.Len() == 0 { 144 rv.Set(reflect.Zero(rv.Type())) 145 } 146 147 return nil 148 } 149 150 func decodeReflectMap(bz []byte, rv reflect.Value) error { 151 if !rv.CanAddr() { 152 return errors.New("map value is not addressable") 153 } 154 155 // Decode into a raw JSON map, using string keys. 156 rawMap := make(map[string]json.RawMessage) 157 if err := json.Unmarshal(bz, &rawMap); err != nil { 158 return err 159 } 160 if rv.Type().Key().Kind() != reflect.String { 161 return fmt.Errorf("map keys must be strings, got %v", rv.Type().Key().String()) 162 } 163 164 // Recursively decode values. 165 rv.Set(reflect.MakeMapWithSize(rv.Type(), len(rawMap))) 166 for key, bz := range rawMap { 167 value := reflect.New(rv.Type().Elem()).Elem() 168 if err := decodeReflect(bz, value); err != nil { 169 return err 170 } 171 rv.SetMapIndex(reflect.ValueOf(key), value) 172 } 173 return nil 174 } 175 176 func decodeReflectStruct(bz []byte, rv reflect.Value) error { 177 if !rv.CanAddr() { 178 return errors.New("struct value is not addressable") 179 } 180 sInfo := makeStructInfo(rv.Type()) 181 182 // Decode raw JSON values into a string-keyed map. 183 rawMap := make(map[string]json.RawMessage) 184 if err := json.Unmarshal(bz, &rawMap); err != nil { 185 return err 186 } 187 for i, fInfo := range sInfo.fields { 188 if !fInfo.hidden { 189 frv := rv.Field(i) 190 bz := rawMap[fInfo.jsonName] 191 if len(bz) > 0 { 192 if err := decodeReflect(bz, frv); err != nil { 193 return err 194 } 195 } else if !fInfo.omitEmpty { 196 frv.Set(reflect.Zero(frv.Type())) 197 } 198 } 199 } 200 201 return nil 202 } 203 204 func decodeReflectInterface(bz []byte, rv reflect.Value) error { 205 if !rv.CanAddr() { 206 return errors.New("interface value not addressable") 207 } 208 209 // Decode the interface wrapper. 210 wrapper := interfaceWrapper{} 211 if err := json.Unmarshal(bz, &wrapper); err != nil { 212 return err 213 } 214 if wrapper.Type == "" { 215 return errors.New("interface type cannot be empty") 216 } 217 if len(wrapper.Value) == 0 { 218 return errors.New("interface value cannot be empty") 219 } 220 221 // Dereference-and-construct pointers, to handle nested pointers. 222 for rv.Kind() == reflect.Ptr { 223 if rv.IsNil() { 224 rv.Set(reflect.New(rv.Type().Elem())) 225 } 226 rv = rv.Elem() 227 } 228 229 // Look up the interface type, and construct a concrete value. 230 rt, returnPtr := typeRegistry.lookup(wrapper.Type) 231 if rt == nil { 232 return fmt.Errorf("unknown type %q", wrapper.Type) 233 } 234 235 cptr := reflect.New(rt) 236 crv := cptr.Elem() 237 if err := decodeReflect(wrapper.Value, crv); err != nil { 238 return err 239 } 240 241 // This makes sure interface implementations with pointer receivers (e.g. func (c *Car)) are 242 // constructed as pointers behind the interface. The types must be registered as pointers with 243 // RegisterType(). 244 if rv.Type().Kind() == reflect.Interface && returnPtr { 245 if !cptr.Type().AssignableTo(rv.Type()) { 246 return fmt.Errorf("invalid type %q for this value", wrapper.Type) 247 } 248 rv.Set(cptr) 249 } else { 250 if !crv.Type().AssignableTo(rv.Type()) { 251 return fmt.Errorf("invalid type %q for this value", wrapper.Type) 252 } 253 rv.Set(crv) 254 } 255 return nil 256 } 257 258 func decodeStdlib(bz []byte, rv reflect.Value) error { 259 if !rv.CanAddr() && rv.Kind() != reflect.Ptr { 260 return errors.New("value must be addressable or pointer") 261 } 262 263 // Make sure we are unmarshaling into a pointer. 264 target := rv 265 if rv.Kind() != reflect.Ptr { 266 target = reflect.New(rv.Type()) 267 } 268 if err := json.Unmarshal(bz, target.Interface()); err != nil { 269 return err 270 } 271 rv.Set(target.Elem()) 272 return nil 273 } 274 275 type interfaceWrapper struct { 276 Type string `json:"type"` 277 Value json.RawMessage `json:"value"` 278 }