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