github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/common/types.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package common 18 19 import ( 20 "bytes" 21 "database/sql/driver" 22 "encoding/hex" 23 "encoding/json" 24 "errors" 25 "fmt" 26 "math/big" 27 "math/rand" 28 "reflect" 29 "strconv" 30 "strings" 31 32 "github.com/ethereum/go-ethereum/common/hexutil" 33 "golang.org/x/crypto/sha3" 34 ) 35 36 // Lengths of hashes and addresses in bytes. 37 const ( 38 // HashLength is the expected length of the hash 39 HashLength = 32 40 // AddressLength is the expected length of the address 41 AddressLength = 20 42 ) 43 44 var ( 45 hashT = reflect.TypeOf(Hash{}) 46 addressT = reflect.TypeOf(Address{}) 47 48 // MaxAddress represents the maximum possible address value. 49 MaxAddress = HexToAddress("0xffffffffffffffffffffffffffffffffffffffff") 50 51 // MaxHash represents the maximum possible hash value. 52 MaxHash = HexToHash("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") 53 ) 54 55 // Hash represents the 32 byte Keccak256 hash of arbitrary data. 56 type Hash [HashLength]byte 57 58 // BytesToHash sets b to hash. 59 // If b is larger than len(h), b will be cropped from the left. 60 func BytesToHash(b []byte) Hash { 61 var h Hash 62 h.SetBytes(b) 63 return h 64 } 65 66 // BigToHash sets byte representation of b to hash. 67 // If b is larger than len(h), b will be cropped from the left. 68 func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) } 69 70 // HexToHash sets byte representation of s to hash. 71 // If b is larger than len(h), b will be cropped from the left. 72 func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) } 73 74 // Cmp compares two hashes. 75 func (h Hash) Cmp(other Hash) int { 76 return bytes.Compare(h[:], other[:]) 77 } 78 79 // Bytes gets the byte representation of the underlying hash. 80 func (h Hash) Bytes() []byte { return h[:] } 81 82 // Big converts a hash to a big integer. 83 func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) } 84 85 // Hex converts a hash to a hex string. 86 func (h Hash) Hex() string { return hexutil.Encode(h[:]) } 87 88 // TerminalString implements log.TerminalStringer, formatting a string for console 89 // output during logging. 90 func (h Hash) TerminalString() string { 91 return fmt.Sprintf("%x..%x", h[:3], h[29:]) 92 } 93 94 // String implements the stringer interface and is used also by the logger when 95 // doing full logging into a file. 96 func (h Hash) String() string { 97 return h.Hex() 98 } 99 100 // Format implements fmt.Formatter. 101 // Hash supports the %v, %s, %q, %x, %X and %d format verbs. 102 func (h Hash) Format(s fmt.State, c rune) { 103 hexb := make([]byte, 2+len(h)*2) 104 copy(hexb, "0x") 105 hex.Encode(hexb[2:], h[:]) 106 107 switch c { 108 case 'x', 'X': 109 if !s.Flag('#') { 110 hexb = hexb[2:] 111 } 112 if c == 'X' { 113 hexb = bytes.ToUpper(hexb) 114 } 115 fallthrough 116 case 'v', 's': 117 s.Write(hexb) 118 case 'q': 119 q := []byte{'"'} 120 s.Write(q) 121 s.Write(hexb) 122 s.Write(q) 123 case 'd': 124 fmt.Fprint(s, ([len(h)]byte)(h)) 125 default: 126 fmt.Fprintf(s, "%%!%c(hash=%x)", c, h) 127 } 128 } 129 130 // UnmarshalText parses a hash in hex syntax. 131 func (h *Hash) UnmarshalText(input []byte) error { 132 return hexutil.UnmarshalFixedText("Hash", input, h[:]) 133 } 134 135 // UnmarshalJSON parses a hash in hex syntax. 136 func (h *Hash) UnmarshalJSON(input []byte) error { 137 return hexutil.UnmarshalFixedJSON(hashT, input, h[:]) 138 } 139 140 // MarshalText returns the hex representation of h. 141 func (h Hash) MarshalText() ([]byte, error) { 142 return hexutil.Bytes(h[:]).MarshalText() 143 } 144 145 // SetBytes sets the hash to the value of b. 146 // If b is larger than len(h), b will be cropped from the left. 147 func (h *Hash) SetBytes(b []byte) { 148 if len(b) > len(h) { 149 b = b[len(b)-HashLength:] 150 } 151 152 copy(h[HashLength-len(b):], b) 153 } 154 155 // Generate implements testing/quick.Generator. 156 func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value { 157 m := rand.Intn(len(h)) 158 for i := len(h) - 1; i > m; i-- { 159 h[i] = byte(rand.Uint32()) 160 } 161 return reflect.ValueOf(h) 162 } 163 164 // Scan implements Scanner for database/sql. 165 func (h *Hash) Scan(src interface{}) error { 166 srcB, ok := src.([]byte) 167 if !ok { 168 return fmt.Errorf("can't scan %T into Hash", src) 169 } 170 if len(srcB) != HashLength { 171 return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength) 172 } 173 copy(h[:], srcB) 174 return nil 175 } 176 177 // Value implements valuer for database/sql. 178 func (h Hash) Value() (driver.Value, error) { 179 return h[:], nil 180 } 181 182 // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type. 183 func (Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" } 184 185 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 186 func (h *Hash) UnmarshalGraphQL(input interface{}) error { 187 var err error 188 switch input := input.(type) { 189 case string: 190 err = h.UnmarshalText([]byte(input)) 191 default: 192 err = fmt.Errorf("unexpected type %T for Hash", input) 193 } 194 return err 195 } 196 197 // UnprefixedHash allows marshaling a Hash without 0x prefix. 198 type UnprefixedHash Hash 199 200 // UnmarshalText decodes the hash from hex. The 0x prefix is optional. 201 func (h *UnprefixedHash) UnmarshalText(input []byte) error { 202 return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:]) 203 } 204 205 // MarshalText encodes the hash as hex. 206 func (h UnprefixedHash) MarshalText() ([]byte, error) { 207 return []byte(hex.EncodeToString(h[:])), nil 208 } 209 210 /////////// Address 211 212 // Address represents the 20 byte address of an Ethereum account. 213 type Address [AddressLength]byte 214 215 // BytesToAddress returns Address with value b. 216 // If b is larger than len(h), b will be cropped from the left. 217 func BytesToAddress(b []byte) Address { 218 var a Address 219 a.SetBytes(b) 220 return a 221 } 222 223 // BigToAddress returns Address with byte values of b. 224 // If b is larger than len(h), b will be cropped from the left. 225 func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) } 226 227 // HexToAddress returns Address with byte values of s. 228 // If s is larger than len(h), s will be cropped from the left. 229 func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) } 230 231 // IsHexAddress verifies whether a string can represent a valid hex-encoded 232 // Ethereum address or not. 233 func IsHexAddress(s string) bool { 234 if has0xPrefix(s) { 235 s = s[2:] 236 } 237 return len(s) == 2*AddressLength && isHex(s) 238 } 239 240 // Cmp compares two addresses. 241 func (a Address) Cmp(other Address) int { 242 return bytes.Compare(a[:], other[:]) 243 } 244 245 // Bytes gets the string representation of the underlying address. 246 func (a Address) Bytes() []byte { return a[:] } 247 248 // Big converts an address to a big integer. 249 func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) } 250 251 // Hex returns an EIP55-compliant hex string representation of the address. 252 func (a Address) Hex() string { 253 return string(a.checksumHex()) 254 } 255 256 // String implements fmt.Stringer. 257 func (a Address) String() string { 258 return a.Hex() 259 } 260 261 func (a *Address) checksumHex() []byte { 262 buf := a.hex() 263 264 // compute checksum 265 sha := sha3.NewLegacyKeccak256() 266 sha.Write(buf[2:]) 267 hash := sha.Sum(nil) 268 for i := 2; i < len(buf); i++ { 269 hashByte := hash[(i-2)/2] 270 if i%2 == 0 { 271 hashByte = hashByte >> 4 272 } else { 273 hashByte &= 0xf 274 } 275 if buf[i] > '9' && hashByte > 7 { 276 buf[i] -= 32 277 } 278 } 279 return buf[:] 280 } 281 282 func (a Address) hex() []byte { 283 var buf [len(a)*2 + 2]byte 284 copy(buf[:2], "0x") 285 hex.Encode(buf[2:], a[:]) 286 return buf[:] 287 } 288 289 // Format implements fmt.Formatter. 290 // Address supports the %v, %s, %q, %x, %X and %d format verbs. 291 func (a Address) Format(s fmt.State, c rune) { 292 switch c { 293 case 'v', 's': 294 s.Write(a.checksumHex()) 295 case 'q': 296 q := []byte{'"'} 297 s.Write(q) 298 s.Write(a.checksumHex()) 299 s.Write(q) 300 case 'x', 'X': 301 // %x disables the checksum. 302 hex := a.hex() 303 if !s.Flag('#') { 304 hex = hex[2:] 305 } 306 if c == 'X' { 307 hex = bytes.ToUpper(hex) 308 } 309 s.Write(hex) 310 case 'd': 311 fmt.Fprint(s, ([len(a)]byte)(a)) 312 default: 313 fmt.Fprintf(s, "%%!%c(address=%x)", c, a) 314 } 315 } 316 317 // SetBytes sets the address to the value of b. 318 // If b is larger than len(a), b will be cropped from the left. 319 func (a *Address) SetBytes(b []byte) { 320 if len(b) > len(a) { 321 b = b[len(b)-AddressLength:] 322 } 323 copy(a[AddressLength-len(b):], b) 324 } 325 326 // MarshalText returns the hex representation of a. 327 func (a Address) MarshalText() ([]byte, error) { 328 return hexutil.Bytes(a[:]).MarshalText() 329 } 330 331 // UnmarshalText parses a hash in hex syntax. 332 func (a *Address) UnmarshalText(input []byte) error { 333 return hexutil.UnmarshalFixedText("Address", input, a[:]) 334 } 335 336 // UnmarshalJSON parses a hash in hex syntax. 337 func (a *Address) UnmarshalJSON(input []byte) error { 338 return hexutil.UnmarshalFixedJSON(addressT, input, a[:]) 339 } 340 341 // Scan implements Scanner for database/sql. 342 func (a *Address) Scan(src interface{}) error { 343 srcB, ok := src.([]byte) 344 if !ok { 345 return fmt.Errorf("can't scan %T into Address", src) 346 } 347 if len(srcB) != AddressLength { 348 return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength) 349 } 350 copy(a[:], srcB) 351 return nil 352 } 353 354 // Value implements valuer for database/sql. 355 func (a Address) Value() (driver.Value, error) { 356 return a[:], nil 357 } 358 359 // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type. 360 func (a Address) ImplementsGraphQLType(name string) bool { return name == "Address" } 361 362 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 363 func (a *Address) UnmarshalGraphQL(input interface{}) error { 364 var err error 365 switch input := input.(type) { 366 case string: 367 err = a.UnmarshalText([]byte(input)) 368 default: 369 err = fmt.Errorf("unexpected type %T for Address", input) 370 } 371 return err 372 } 373 374 // UnprefixedAddress allows marshaling an Address without 0x prefix. 375 type UnprefixedAddress Address 376 377 // UnmarshalText decodes the address from hex. The 0x prefix is optional. 378 func (a *UnprefixedAddress) UnmarshalText(input []byte) error { 379 return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:]) 380 } 381 382 // MarshalText encodes the address as hex. 383 func (a UnprefixedAddress) MarshalText() ([]byte, error) { 384 return []byte(hex.EncodeToString(a[:])), nil 385 } 386 387 // MixedcaseAddress retains the original string, which may or may not be 388 // correctly checksummed 389 type MixedcaseAddress struct { 390 addr Address 391 original string 392 } 393 394 // NewMixedcaseAddress constructor (mainly for testing) 395 func NewMixedcaseAddress(addr Address) MixedcaseAddress { 396 return MixedcaseAddress{addr: addr, original: addr.Hex()} 397 } 398 399 // NewMixedcaseAddressFromString is mainly meant for unit-testing 400 func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) { 401 if !IsHexAddress(hexaddr) { 402 return nil, errors.New("invalid address") 403 } 404 a := FromHex(hexaddr) 405 return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil 406 } 407 408 // UnmarshalJSON parses MixedcaseAddress 409 func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error { 410 if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil { 411 return err 412 } 413 return json.Unmarshal(input, &ma.original) 414 } 415 416 // MarshalJSON marshals the original value 417 func (ma MixedcaseAddress) MarshalJSON() ([]byte, error) { 418 if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") { 419 return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:])) 420 } 421 return json.Marshal(fmt.Sprintf("0x%s", ma.original)) 422 } 423 424 // Address returns the address 425 func (ma *MixedcaseAddress) Address() Address { 426 return ma.addr 427 } 428 429 // String implements fmt.Stringer 430 func (ma *MixedcaseAddress) String() string { 431 if ma.ValidChecksum() { 432 return fmt.Sprintf("%s [chksum ok]", ma.original) 433 } 434 return fmt.Sprintf("%s [chksum INVALID]", ma.original) 435 } 436 437 // ValidChecksum returns true if the address has valid checksum 438 func (ma *MixedcaseAddress) ValidChecksum() bool { 439 return ma.original == ma.addr.Hex() 440 } 441 442 // Original returns the mixed-case input string 443 func (ma *MixedcaseAddress) Original() string { 444 return ma.original 445 } 446 447 // AddressEIP55 is an alias of Address with a customized json marshaller 448 type AddressEIP55 Address 449 450 // String returns the hex representation of the address in the manner of EIP55. 451 func (addr AddressEIP55) String() string { 452 return Address(addr).Hex() 453 } 454 455 // MarshalJSON marshals the address in the manner of EIP55. 456 func (addr AddressEIP55) MarshalJSON() ([]byte, error) { 457 return json.Marshal(addr.String()) 458 } 459 460 type Decimal uint64 461 462 func isString(input []byte) bool { 463 return len(input) >= 2 && input[0] == '"' && input[len(input)-1] == '"' 464 } 465 466 // UnmarshalJSON parses a hash in hex syntax. 467 func (d *Decimal) UnmarshalJSON(input []byte) error { 468 if !isString(input) { 469 return &json.UnmarshalTypeError{Value: "non-string", Type: reflect.TypeOf(uint64(0))} 470 } 471 if i, err := strconv.ParseInt(string(input[1:len(input)-1]), 10, 64); err == nil { 472 *d = Decimal(i) 473 return nil 474 } else { 475 return err 476 } 477 } 478 479 type PrettyBytes []byte 480 481 // TerminalString implements log.TerminalStringer, formatting a string for console 482 // output during logging. 483 func (b PrettyBytes) TerminalString() string { 484 if len(b) < 7 { 485 return fmt.Sprintf("%x", b) 486 } 487 return fmt.Sprintf("%#x...%x (%dB)", b[:3], b[len(b)-3:], len(b)) 488 }