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