github.com/luckypickle/go-ethereum-vet@v1.14.2/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 "database/sql/driver" 21 "encoding/hex" 22 "encoding/json" 23 "fmt" 24 "math/big" 25 "math/rand" 26 "reflect" 27 "strings" 28 29 "github.com/luckypickle/go-ethereum-vet/common/hexutil" 30 "github.com/luckypickle/go-ethereum-vet/crypto/sha3" 31 ) 32 33 // Lengths of hashes and addresses in bytes. 34 const ( 35 // HashLength is the expected length of the hash 36 HashLength = 32 37 // AddressLength is the expected length of the adddress 38 AddressLength = 20 39 ) 40 41 var ( 42 hashT = reflect.TypeOf(Hash{}) 43 addressT = reflect.TypeOf(Address{}) 44 ) 45 46 // Hash represents the 32 byte Keccak256 hash of arbitrary data. 47 type Hash [HashLength]byte 48 49 // BytesToHash sets b to hash. 50 // If b is larger than len(h), b will be cropped from the left. 51 func BytesToHash(b []byte) Hash { 52 var h Hash 53 h.SetBytes(b) 54 return h 55 } 56 57 // BigToHash sets byte representation of b to hash. 58 // If b is larger than len(h), b will be cropped from the left. 59 func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) } 60 61 // HexToHash sets byte representation of s to hash. 62 // If b is larger than len(h), b will be cropped from the left. 63 func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) } 64 65 // Bytes gets the byte representation of the underlying hash. 66 func (h Hash) Bytes() []byte { return h[:] } 67 68 // Big converts a hash to a big integer. 69 func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) } 70 71 // Hex converts a hash to a hex string. 72 func (h Hash) Hex() string { return hexutil.Encode(h[:]) } 73 74 // TerminalString implements log.TerminalStringer, formatting a string for console 75 // output during logging. 76 func (h Hash) TerminalString() string { 77 return fmt.Sprintf("%x…%x", h[:3], h[29:]) 78 } 79 80 // String implements the stringer interface and is used also by the logger when 81 // doing full logging into a file. 82 func (h Hash) String() string { 83 return h.Hex() 84 } 85 86 // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, 87 // without going through the stringer interface used for logging. 88 func (h Hash) Format(s fmt.State, c rune) { 89 fmt.Fprintf(s, "%"+string(c), h[:]) 90 } 91 92 // UnmarshalText parses a hash in hex syntax. 93 func (h *Hash) UnmarshalText(input []byte) error { 94 return hexutil.UnmarshalFixedText("Hash", input, h[:]) 95 } 96 97 // UnmarshalJSON parses a hash in hex syntax. 98 func (h *Hash) UnmarshalJSON(input []byte) error { 99 return hexutil.UnmarshalFixedJSON(hashT, input, h[:]) 100 } 101 102 // MarshalText returns the hex representation of h. 103 func (h Hash) MarshalText() ([]byte, error) { 104 return hexutil.Bytes(h[:]).MarshalText() 105 } 106 107 // SetBytes sets the hash to the value of b. 108 // If b is larger than len(h), b will be cropped from the left. 109 func (h *Hash) SetBytes(b []byte) { 110 if len(b) > len(h) { 111 b = b[len(b)-HashLength:] 112 } 113 114 copy(h[HashLength-len(b):], b) 115 } 116 117 // Generate implements testing/quick.Generator. 118 func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value { 119 m := rand.Intn(len(h)) 120 for i := len(h) - 1; i > m; i-- { 121 h[i] = byte(rand.Uint32()) 122 } 123 return reflect.ValueOf(h) 124 } 125 126 // Scan implements Scanner for database/sql. 127 func (h *Hash) Scan(src interface{}) error { 128 srcB, ok := src.([]byte) 129 if !ok { 130 return fmt.Errorf("can't scan %T into Hash", src) 131 } 132 if len(srcB) != HashLength { 133 return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength) 134 } 135 copy(h[:], srcB) 136 return nil 137 } 138 139 // Value implements valuer for database/sql. 140 func (h Hash) Value() (driver.Value, error) { 141 return h[:], nil 142 } 143 144 // UnprefixedHash allows marshaling a Hash without 0x prefix. 145 type UnprefixedHash Hash 146 147 // UnmarshalText decodes the hash from hex. The 0x prefix is optional. 148 func (h *UnprefixedHash) UnmarshalText(input []byte) error { 149 return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:]) 150 } 151 152 // MarshalText encodes the hash as hex. 153 func (h UnprefixedHash) MarshalText() ([]byte, error) { 154 return []byte(hex.EncodeToString(h[:])), nil 155 } 156 157 /////////// Address 158 159 // Address represents the 20 byte address of an Ethereum account. 160 type Address [AddressLength]byte 161 162 // BytesToAddress returns Address with value b. 163 // If b is larger than len(h), b will be cropped from the left. 164 func BytesToAddress(b []byte) Address { 165 var a Address 166 a.SetBytes(b) 167 return a 168 } 169 170 // BigToAddress returns Address with byte values of b. 171 // If b is larger than len(h), b will be cropped from the left. 172 func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) } 173 174 // HexToAddress returns Address with byte values of s. 175 // If s is larger than len(h), s will be cropped from the left. 176 func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) } 177 178 // IsHexAddress verifies whether a string can represent a valid hex-encoded 179 // Ethereum address or not. 180 func IsHexAddress(s string) bool { 181 if hasHexPrefix(s) { 182 s = s[2:] 183 } 184 return len(s) == 2*AddressLength && isHex(s) 185 } 186 187 // Bytes gets the string representation of the underlying address. 188 func (a Address) Bytes() []byte { return a[:] } 189 190 // Big converts an address to a big integer. 191 func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) } 192 193 // Hash converts an address to a hash by left-padding it with zeros. 194 func (a Address) Hash() Hash { return BytesToHash(a[:]) } 195 196 // Hex returns an EIP55-compliant hex string representation of the address. 197 func (a Address) Hex() string { 198 unchecksummed := hex.EncodeToString(a[:]) 199 sha := sha3.NewKeccak256() 200 sha.Write([]byte(unchecksummed)) 201 hash := sha.Sum(nil) 202 203 result := []byte(unchecksummed) 204 for i := 0; i < len(result); i++ { 205 hashByte := hash[i/2] 206 if i%2 == 0 { 207 hashByte = hashByte >> 4 208 } else { 209 hashByte &= 0xf 210 } 211 if result[i] > '9' && hashByte > 7 { 212 result[i] -= 32 213 } 214 } 215 return "0x" + string(result) 216 } 217 218 // String implements fmt.Stringer. 219 func (a Address) String() string { 220 return a.Hex() 221 } 222 223 // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, 224 // without going through the stringer interface used for logging. 225 func (a Address) Format(s fmt.State, c rune) { 226 fmt.Fprintf(s, "%"+string(c), a[:]) 227 } 228 229 // SetBytes sets the address to the value of b. 230 // If b is larger than len(a) it will panic. 231 func (a *Address) SetBytes(b []byte) { 232 if len(b) > len(a) { 233 b = b[len(b)-AddressLength:] 234 } 235 copy(a[AddressLength-len(b):], b) 236 } 237 238 // MarshalText returns the hex representation of a. 239 func (a Address) MarshalText() ([]byte, error) { 240 return hexutil.Bytes(a[:]).MarshalText() 241 } 242 243 // UnmarshalText parses a hash in hex syntax. 244 func (a *Address) UnmarshalText(input []byte) error { 245 return hexutil.UnmarshalFixedText("Address", input, a[:]) 246 } 247 248 // UnmarshalJSON parses a hash in hex syntax. 249 func (a *Address) UnmarshalJSON(input []byte) error { 250 return hexutil.UnmarshalFixedJSON(addressT, input, a[:]) 251 } 252 253 // Scan implements Scanner for database/sql. 254 func (a *Address) Scan(src interface{}) error { 255 srcB, ok := src.([]byte) 256 if !ok { 257 return fmt.Errorf("can't scan %T into Address", src) 258 } 259 if len(srcB) != AddressLength { 260 return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength) 261 } 262 copy(a[:], srcB) 263 return nil 264 } 265 266 // Value implements valuer for database/sql. 267 func (a Address) Value() (driver.Value, error) { 268 return a[:], nil 269 } 270 271 // UnprefixedAddress allows marshaling an Address without 0x prefix. 272 type UnprefixedAddress Address 273 274 // UnmarshalText decodes the address from hex. The 0x prefix is optional. 275 func (a *UnprefixedAddress) UnmarshalText(input []byte) error { 276 return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:]) 277 } 278 279 // MarshalText encodes the address as hex. 280 func (a UnprefixedAddress) MarshalText() ([]byte, error) { 281 return []byte(hex.EncodeToString(a[:])), nil 282 } 283 284 // MixedcaseAddress retains the original string, which may or may not be 285 // correctly checksummed 286 type MixedcaseAddress struct { 287 addr Address 288 original string 289 } 290 291 // NewMixedcaseAddress constructor (mainly for testing) 292 func NewMixedcaseAddress(addr Address) MixedcaseAddress { 293 return MixedcaseAddress{addr: addr, original: addr.Hex()} 294 } 295 296 // NewMixedcaseAddressFromString is mainly meant for unit-testing 297 func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) { 298 if !IsHexAddress(hexaddr) { 299 return nil, fmt.Errorf("Invalid address") 300 } 301 a := FromHex(hexaddr) 302 return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil 303 } 304 305 // UnmarshalJSON parses MixedcaseAddress 306 func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error { 307 if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil { 308 return err 309 } 310 return json.Unmarshal(input, &ma.original) 311 } 312 313 // MarshalJSON marshals the original value 314 func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) { 315 if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") { 316 return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:])) 317 } 318 return json.Marshal(fmt.Sprintf("0x%s", ma.original)) 319 } 320 321 // Address returns the address 322 func (ma *MixedcaseAddress) Address() Address { 323 return ma.addr 324 } 325 326 // String implements fmt.Stringer 327 func (ma *MixedcaseAddress) String() string { 328 if ma.ValidChecksum() { 329 return fmt.Sprintf("%s [chksum ok]", ma.original) 330 } 331 return fmt.Sprintf("%s [chksum INVALID]", ma.original) 332 } 333 334 // ValidChecksum returns true if the address has valid checksum 335 func (ma *MixedcaseAddress) ValidChecksum() bool { 336 return ma.original == ma.addr.Hex() 337 } 338 339 // Original returns the mixed-case input string 340 func (ma *MixedcaseAddress) Original() string { 341 return ma.original 342 }