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