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