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