github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/common/hexutil/json.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package hexutil 19 20 import ( 21 "encoding/hex" 22 "encoding/json" 23 "fmt" 24 "math/big" 25 "reflect" 26 "strconv" 27 ) 28 29 var ( 30 bytesT = reflect.TypeOf(Bytes(nil)) 31 bigT = reflect.TypeOf((*Big)(nil)) 32 uintT = reflect.TypeOf(Uint(0)) 33 uint64T = reflect.TypeOf(Uint64(0)) 34 ) 35 36 // Bytes marshals/unmarshals as a JSON string with 0x prefix. 37 // The empty slice marshals as "0x". 38 type Bytes []byte 39 40 // MarshalText implements encoding.TextMarshaler 41 func (b Bytes) MarshalText() ([]byte, error) { 42 result := make([]byte, len(b)*2+2) 43 copy(result, `0x`) 44 hex.Encode(result[2:], b) 45 return result, nil 46 } 47 48 // UnmarshalJSON implements json.Unmarshaler. 49 func (b *Bytes) UnmarshalJSON(input []byte) error { 50 if !isString(input) { 51 return errNonString(bytesT) 52 } 53 return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bytesT) 54 } 55 56 // UnmarshalText implements encoding.TextUnmarshaler. 57 func (b *Bytes) UnmarshalText(input []byte) error { 58 raw, err := checkText(input, true) 59 if err != nil { 60 return err 61 } 62 dec := make([]byte, len(raw)/2) 63 if _, err = hex.Decode(dec, raw); err != nil { 64 err = mapError(err) 65 } else { 66 *b = dec 67 } 68 return err 69 } 70 71 // String returns the hex encoding of b. 72 func (b Bytes) String() string { 73 return Encode(b) 74 } 75 76 // ImplementsGraphQLType returns true if Bytes implements the specified GraphQL type. 77 func (b Bytes) ImplementsGraphQLType(name string) bool { return name == "Bytes" } 78 79 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 80 func (b *Bytes) UnmarshalGraphQL(input interface{}) error { 81 var err error 82 switch input := input.(type) { 83 case string: 84 data, err := Decode(input) 85 if err != nil { 86 return err 87 } 88 *b = data 89 default: 90 err = fmt.Errorf("Unexpected type for Bytes: %v", input) 91 } 92 return err 93 } 94 95 // UnmarshalFixedJSON decodes the input as a string with 0x prefix. The length of out 96 // determines the required input length. This function is commonly used to implement the 97 // UnmarshalJSON method for fixed-size types. 98 func UnmarshalFixedJSON(typ reflect.Type, input, out []byte) error { 99 if !isString(input) { 100 return errNonString(typ) 101 } 102 return wrapTypeError(UnmarshalFixedText(typ.String(), input[1:len(input)-1], out), typ) 103 } 104 105 // UnmarshalFixedText decodes the input as a string with 0x prefix. The length of out 106 // determines the required input length. This function is commonly used to implement the 107 // UnmarshalText method for fixed-size types. 108 func UnmarshalFixedText(typname string, input, out []byte) error { 109 raw, err := checkText(input, true) 110 if err != nil { 111 return err 112 } 113 if len(raw)/2 != len(out) { 114 return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname) 115 } 116 // Pre-verify syntax before modifying out. 117 for _, b := range raw { 118 if decodeNibble(b) == badNibble { 119 return ErrSyntax 120 } 121 } 122 hex.Decode(out, raw) 123 return nil 124 } 125 126 // UnmarshalFixedUnprefixedText decodes the input as a string with optional 0x prefix. The 127 // length of out determines the required input length. This function is commonly used to 128 // implement the UnmarshalText method for fixed-size types. 129 func UnmarshalFixedUnprefixedText(typname string, input, out []byte) error { 130 raw, err := checkText(input, false) 131 if err != nil { 132 return err 133 } 134 if len(raw)/2 != len(out) { 135 return fmt.Errorf("hex string has length %d, want %d for %s", len(raw), len(out)*2, typname) 136 } 137 // Pre-verify syntax before modifying out. 138 for _, b := range raw { 139 if decodeNibble(b) == badNibble { 140 return ErrSyntax 141 } 142 } 143 hex.Decode(out, raw) 144 return nil 145 } 146 147 // Big marshals/unmarshals as a JSON string with 0x prefix. 148 // The zero value marshals as "0x0". 149 // 150 // Negative integers are not supported at this time. Attempting to marshal them will 151 // return an error. Values larger than 256bits are rejected by Unmarshal but will be 152 // marshaled without error. 153 type Big big.Int 154 155 // MarshalText implements encoding.TextMarshaler 156 func (b Big) MarshalText() ([]byte, error) { 157 return []byte(EncodeBig((*big.Int)(&b))), nil 158 } 159 160 // UnmarshalJSON implements json.Unmarshaler. 161 func (b *Big) UnmarshalJSON(input []byte) error { 162 if !isString(input) { 163 return errNonString(bigT) 164 } 165 return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), bigT) 166 } 167 168 // UnmarshalText implements encoding.TextUnmarshaler 169 func (b *Big) UnmarshalText(input []byte) error { 170 raw, err := checkNumberText(input) 171 if err != nil { 172 return err 173 } 174 if len(raw) > 64 { 175 return ErrBig256Range 176 } 177 words := make([]big.Word, len(raw)/bigWordNibbles+1) 178 end := len(raw) 179 for i := range words { 180 start := end - bigWordNibbles 181 if start < 0 { 182 start = 0 183 } 184 for ri := start; ri < end; ri++ { 185 nib := decodeNibble(raw[ri]) 186 if nib == badNibble { 187 return ErrSyntax 188 } 189 words[i] *= 16 190 words[i] += big.Word(nib) 191 } 192 end = start 193 } 194 var dec big.Int 195 dec.SetBits(words) 196 *b = (Big)(dec) 197 return nil 198 } 199 200 // ToInt converts b to a big.Int. 201 func (b *Big) ToInt() *big.Int { 202 return (*big.Int)(b) 203 } 204 205 // String returns the hex encoding of b. 206 func (b *Big) String() string { 207 return EncodeBig(b.ToInt()) 208 } 209 210 // ImplementsGraphQLType returns true if Big implements the provided GraphQL type. 211 func (b Big) ImplementsGraphQLType(name string) bool { return name == "BigInt" } 212 213 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 214 func (b *Big) UnmarshalGraphQL(input interface{}) error { 215 var err error 216 switch input := input.(type) { 217 case string: 218 return b.UnmarshalText([]byte(input)) 219 case int32: 220 var num big.Int 221 num.SetInt64(int64(input)) 222 *b = Big(num) 223 default: 224 err = fmt.Errorf("Unexpected type for BigInt: %v", input) 225 } 226 return err 227 } 228 229 // Uint64 marshals/unmarshals as a JSON string with 0x prefix. 230 // The zero value marshals as "0x0". 231 type Uint64 uint64 232 233 // MarshalText implements encoding.TextMarshaler. 234 func (b Uint64) MarshalText() ([]byte, error) { 235 buf := make([]byte, 2, 10) 236 copy(buf, `0x`) 237 buf = strconv.AppendUint(buf, uint64(b), 16) 238 return buf, nil 239 } 240 241 // UnmarshalJSON implements json.Unmarshaler. 242 func (b *Uint64) UnmarshalJSON(input []byte) error { 243 if !isString(input) { 244 return errNonString(uint64T) 245 } 246 return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uint64T) 247 } 248 249 // UnmarshalText implements encoding.TextUnmarshaler 250 func (b *Uint64) UnmarshalText(input []byte) error { 251 raw, err := checkNumberText(input) 252 if err != nil { 253 return err 254 } 255 if len(raw) > 16 { 256 return ErrUint64Range 257 } 258 var dec uint64 259 for _, byte := range raw { 260 nib := decodeNibble(byte) 261 if nib == badNibble { 262 return ErrSyntax 263 } 264 dec *= 16 265 dec += nib 266 } 267 *b = Uint64(dec) 268 return nil 269 } 270 271 // String returns the hex encoding of b. 272 func (b Uint64) String() string { 273 return EncodeUint64(uint64(b)) 274 } 275 276 // ImplementsGraphQLType returns true if Uint64 implements the provided GraphQL type. 277 func (b Uint64) ImplementsGraphQLType(name string) bool { return name == "Long" } 278 279 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 280 func (b *Uint64) UnmarshalGraphQL(input interface{}) error { 281 var err error 282 switch input := input.(type) { 283 case string: 284 return b.UnmarshalText([]byte(input)) 285 case int32: 286 *b = Uint64(input) 287 default: 288 err = fmt.Errorf("Unexpected type for Long: %v", input) 289 } 290 return err 291 } 292 293 // Uint marshals/unmarshals as a JSON string with 0x prefix. 294 // The zero value marshals as "0x0". 295 type Uint uint 296 297 // MarshalText implements encoding.TextMarshaler. 298 func (b Uint) MarshalText() ([]byte, error) { 299 return Uint64(b).MarshalText() 300 } 301 302 // UnmarshalJSON implements json.Unmarshaler. 303 func (b *Uint) UnmarshalJSON(input []byte) error { 304 if !isString(input) { 305 return errNonString(uintT) 306 } 307 return wrapTypeError(b.UnmarshalText(input[1:len(input)-1]), uintT) 308 } 309 310 // UnmarshalText implements encoding.TextUnmarshaler. 311 func (b *Uint) UnmarshalText(input []byte) error { 312 var u64 Uint64 313 err := u64.UnmarshalText(input) 314 if u64 > Uint64(^uint(0)) || err == ErrUint64Range { 315 return ErrUintRange 316 } else if err != nil { 317 return err 318 } 319 *b = Uint(u64) 320 return nil 321 } 322 323 // String returns the hex encoding of b. 324 func (b Uint) String() string { 325 return EncodeUint64(uint64(b)) 326 } 327 328 func isString(input []byte) bool { 329 return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' 330 } 331 332 func bytesHave0xPrefix(input []byte) bool { 333 return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') 334 } 335 336 func checkText(input []byte, wantPrefix bool) ([]byte, error) { 337 if len(input) == 0 { 338 return nil, nil // empty strings are allowed 339 } 340 if bytesHave0xPrefix(input) { 341 input = input[2:] 342 } else if wantPrefix { 343 return nil, ErrMissingPrefix 344 } 345 if len(input)%2 != 0 { 346 return nil, ErrOddLength 347 } 348 return input, nil 349 } 350 351 func checkNumberText(input []byte) (raw []byte, err error) { 352 if len(input) == 0 { 353 return nil, nil // empty strings are allowed 354 } 355 if !bytesHave0xPrefix(input) { 356 return nil, ErrMissingPrefix 357 } 358 input = input[2:] 359 if len(input) == 0 { 360 return nil, ErrEmptyNumber 361 } 362 if len(input) > 1 && input[0] == '0' { 363 return nil, ErrLeadingZero 364 } 365 return input, nil 366 } 367 368 func wrapTypeError(err error, typ reflect.Type) error { 369 if _, ok := err.(*decError); ok { 370 return &json.UnmarshalTypeError{Value: err.Error(), Type: typ} 371 } 372 return err 373 } 374 375 func errNonString(typ reflect.Type) error { 376 return &json.UnmarshalTypeError{Value: "non-string", Type: typ} 377 }