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