github.com/coltonfike/e2c@v21.1.0+incompatible/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/base64" 22 "encoding/hex" 23 "encoding/json" 24 "errors" 25 "fmt" 26 "math/big" 27 "math/rand" 28 "reflect" 29 "strings" 30 31 "github.com/ethereum/go-ethereum/common/hexutil" 32 "golang.org/x/crypto/sha3" 33 ) 34 35 // Lengths of hashes and addresses in bytes. 36 const ( 37 // HashLength is the expected length of the hash 38 HashLength = 32 39 // AddressLength is the expected length of the address 40 AddressLength = 20 41 // length of the hash returned by Private Transaction Manager 42 EncryptedPayloadHashLength = 64 43 ) 44 45 var ( 46 ErrNotPrivateContract = errors.New("the provided address is not a private contract") 47 ErrNoAccountExtraData = errors.New("no account extra data found") 48 49 hashT = reflect.TypeOf(Hash{}) 50 addressT = reflect.TypeOf(Address{}) 51 ) 52 53 // Hash, returned by Private Transaction Manager, represents the 64-byte hash of encrypted payload 54 type EncryptedPayloadHash [EncryptedPayloadHashLength]byte 55 56 // Using map to enable fast lookup 57 type EncryptedPayloadHashes map[EncryptedPayloadHash]struct{} 58 59 // BytesToEncryptedPayloadHash sets b to EncryptedPayloadHash. 60 // If b is larger than len(h), b will be cropped from the left. 61 func BytesToEncryptedPayloadHash(b []byte) EncryptedPayloadHash { 62 var h EncryptedPayloadHash 63 h.SetBytes(b) 64 return h 65 } 66 67 func Base64ToEncryptedPayloadHash(b64 string) (EncryptedPayloadHash, error) { 68 bytes, err := base64.StdEncoding.DecodeString(b64) 69 if err != nil { 70 return EncryptedPayloadHash{}, fmt.Errorf("unable to convert base64 string %s to EncryptedPayloadHash. Cause: %v", b64, err) 71 } 72 return BytesToEncryptedPayloadHash(bytes), nil 73 } 74 75 func (eph *EncryptedPayloadHash) SetBytes(b []byte) { 76 if len(b) > len(eph) { 77 b = b[len(b)-EncryptedPayloadHashLength:] 78 } 79 80 copy(eph[EncryptedPayloadHashLength-len(b):], b) 81 } 82 83 func (eph EncryptedPayloadHash) Hex() string { 84 return hexutil.Encode(eph[:]) 85 } 86 87 func (eph EncryptedPayloadHash) Bytes() []byte { 88 return eph[:] 89 } 90 91 func (eph EncryptedPayloadHash) String() string { 92 return eph.Hex() 93 } 94 95 func (eph EncryptedPayloadHash) ToBase64() string { 96 return base64.StdEncoding.EncodeToString(eph[:]) 97 } 98 99 func (eph EncryptedPayloadHash) TerminalString() string { 100 return fmt.Sprintf("%x…%x", eph[:3], eph[EncryptedPayloadHashLength-3:]) 101 } 102 103 func (eph EncryptedPayloadHash) BytesTypeRef() *hexutil.Bytes { 104 b := hexutil.Bytes(eph.Bytes()) 105 return &b 106 } 107 108 func EmptyEncryptedPayloadHash(eph EncryptedPayloadHash) bool { 109 return eph == EncryptedPayloadHash{} 110 } 111 112 // Hash represents the 32 byte Keccak256 hash of arbitrary data. 113 type Hash [HashLength]byte 114 115 // BytesToHash sets b to hash. 116 // If b is larger than len(h), b will be cropped from the left. 117 func BytesToHash(b []byte) Hash { 118 var h Hash 119 h.SetBytes(b) 120 return h 121 } 122 123 func StringToHash(s string) Hash { return BytesToHash([]byte(s)) } // dep: Istanbul 124 125 // BigToHash sets byte representation of b to hash. 126 // If b is larger than len(h), b will be cropped from the left. 127 func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) } 128 129 // HexToHash sets byte representation of s to hash. 130 // If b is larger than len(h), b will be cropped from the left. 131 func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) } 132 133 // Bytes gets the byte representation of the underlying hash. 134 func (h Hash) Bytes() []byte { return h[:] } 135 136 // Big converts a hash to a big integer. 137 func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) } 138 139 // Hex converts a hash to a hex string. 140 func (h Hash) Hex() string { return hexutil.Encode(h[:]) } 141 142 // TerminalString implements log.TerminalStringer, formatting a string for console 143 // output during logging. 144 func (h Hash) TerminalString() string { 145 return fmt.Sprintf("%x…%x", h[:3], h[29:]) 146 } 147 148 // String implements the stringer interface and is used also by the logger when 149 // doing full logging into a file. 150 func (h Hash) String() string { 151 return h.Hex() 152 } 153 154 // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, 155 // without going through the stringer interface used for logging. 156 func (h Hash) Format(s fmt.State, c rune) { 157 fmt.Fprintf(s, "%"+string(c), h[:]) 158 } 159 160 // UnmarshalText parses a hash in hex syntax. 161 func (h *Hash) UnmarshalText(input []byte) error { 162 return hexutil.UnmarshalFixedText("Hash", input, h[:]) 163 } 164 165 // UnmarshalJSON parses a hash in hex syntax. 166 func (h *Hash) UnmarshalJSON(input []byte) error { 167 return hexutil.UnmarshalFixedJSON(hashT, input, h[:]) 168 } 169 170 // MarshalText returns the hex representation of h. 171 func (h Hash) MarshalText() ([]byte, error) { 172 return hexutil.Bytes(h[:]).MarshalText() 173 } 174 175 // SetBytes sets the hash to the value of b. 176 // If b is larger than len(h), b will be cropped from the left. 177 func (h *Hash) SetBytes(b []byte) { 178 if len(b) > len(h) { 179 b = b[len(b)-HashLength:] 180 } 181 182 copy(h[HashLength-len(b):], b) 183 } 184 185 func EmptyHash(h Hash) bool { 186 return h == Hash{} 187 } 188 189 // Generate implements testing/quick.Generator. 190 func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value { 191 m := rand.Intn(len(h)) 192 for i := len(h) - 1; i > m; i-- { 193 h[i] = byte(rand.Uint32()) 194 } 195 return reflect.ValueOf(h) 196 } 197 198 func (h Hash) ToBase64() string { 199 return base64.StdEncoding.EncodeToString(h.Bytes()) 200 } 201 202 // Decode base64 string to Hash 203 // if String is empty then return empty hash 204 func Base64ToHash(b64 string) (Hash, error) { 205 if b64 == "" { 206 return Hash{}, nil 207 } 208 bytes, err := base64.StdEncoding.DecodeString(b64) 209 if err != nil { 210 return Hash{}, fmt.Errorf("unable to convert base64 string %s to Hash. Cause: %v", b64, err) 211 } 212 return BytesToHash(bytes), nil 213 } 214 215 // Scan implements Scanner for database/sql. 216 func (h *Hash) Scan(src interface{}) error { 217 srcB, ok := src.([]byte) 218 if !ok { 219 return fmt.Errorf("can't scan %T into Hash", src) 220 } 221 if len(srcB) != HashLength { 222 return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength) 223 } 224 copy(h[:], srcB) 225 return nil 226 } 227 228 // Value implements valuer for database/sql. 229 func (h Hash) Value() (driver.Value, error) { 230 return h[:], nil 231 } 232 233 // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type. 234 func (_ Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" } 235 236 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 237 func (h *Hash) UnmarshalGraphQL(input interface{}) error { 238 var err error 239 switch input := input.(type) { 240 case string: 241 err = h.UnmarshalText([]byte(input)) 242 default: 243 err = fmt.Errorf("Unexpected type for Bytes32: %v", input) 244 } 245 return err 246 } 247 248 // UnprefixedHash allows marshaling a Hash without 0x prefix. 249 type UnprefixedHash Hash 250 251 // UnmarshalText decodes the hash from hex. The 0x prefix is optional. 252 func (h *UnprefixedHash) UnmarshalText(input []byte) error { 253 return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:]) 254 } 255 256 // MarshalText encodes the hash as hex. 257 func (h UnprefixedHash) MarshalText() ([]byte, error) { 258 return []byte(hex.EncodeToString(h[:])), nil 259 } 260 261 func (ephs EncryptedPayloadHashes) ToBase64s() []string { 262 a := make([]string, 0, len(ephs)) 263 for eph := range ephs { 264 a = append(a, eph.ToBase64()) 265 } 266 return a 267 } 268 269 func (ephs EncryptedPayloadHashes) NotExist(eph EncryptedPayloadHash) bool { 270 _, ok := ephs[eph] 271 return !ok 272 } 273 274 func (ephs EncryptedPayloadHashes) Add(eph EncryptedPayloadHash) { 275 ephs[eph] = struct{}{} 276 } 277 278 func Base64sToEncryptedPayloadHashes(b64s []string) (EncryptedPayloadHashes, error) { 279 ephs := make(EncryptedPayloadHashes) 280 for _, b64 := range b64s { 281 data, err := Base64ToEncryptedPayloadHash(b64) 282 if err != nil { 283 return nil, err 284 } 285 ephs.Add(data) 286 } 287 return ephs, nil 288 } 289 290 // Print hex but only first 3 and last 3 bytes 291 func FormatTerminalString(data []byte) string { 292 l := len(data) 293 if l > 0 { 294 if l > 6 { 295 return fmt.Sprintf("%x…%x", data[:3], data[l-3:]) 296 } else { 297 return fmt.Sprintf("%x", data[:]) 298 } 299 } 300 return "" 301 } 302 303 /////////// Address 304 305 // Address represents the 20 byte address of an Ethereum account. 306 type Address [AddressLength]byte 307 308 // BytesToAddress returns Address with value b. 309 // If b is larger than len(h), b will be cropped from the left. 310 func BytesToAddress(b []byte) Address { 311 var a Address 312 a.SetBytes(b) 313 return a 314 } 315 316 func StringToAddress(s string) Address { return BytesToAddress([]byte(s)) } // dep: Istanbul 317 318 // BigToAddress returns Address with byte values of b. 319 // If b is larger than len(h), b will be cropped from the left. 320 func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) } 321 322 // HexToAddress returns Address with byte values of s. 323 // If s is larger than len(h), s will be cropped from the left. 324 func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) } 325 326 // IsHexAddress verifies whether a string can represent a valid hex-encoded 327 // Ethereum address or not. 328 func IsHexAddress(s string) bool { 329 if has0xPrefix(s) { 330 s = s[2:] 331 } 332 return len(s) == 2*AddressLength && isHex(s) 333 } 334 335 // Bytes gets the string representation of the underlying address. 336 func (a Address) Bytes() []byte { return a[:] } 337 338 // Hash converts an address to a hash by left-padding it with zeros. 339 func (a Address) Hash() Hash { return BytesToHash(a[:]) } 340 341 // Hex returns an EIP55-compliant hex string representation of the address. 342 func (a Address) Hex() string { 343 unchecksummed := hex.EncodeToString(a[:]) 344 sha := sha3.NewLegacyKeccak256() 345 sha.Write([]byte(unchecksummed)) 346 hash := sha.Sum(nil) 347 348 result := []byte(unchecksummed) 349 for i := 0; i < len(result); i++ { 350 hashByte := hash[i/2] 351 if i%2 == 0 { 352 hashByte = hashByte >> 4 353 } else { 354 hashByte &= 0xf 355 } 356 if result[i] > '9' && hashByte > 7 { 357 result[i] -= 32 358 } 359 } 360 return "0x" + string(result) 361 } 362 363 // String implements fmt.Stringer. 364 func (a Address) String() string { 365 return a.Hex() 366 } 367 368 // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, 369 // without going through the stringer interface used for logging. 370 func (a Address) Format(s fmt.State, c rune) { 371 fmt.Fprintf(s, "%"+string(c), a[:]) 372 } 373 374 // SetBytes sets the address to the value of b. 375 // If b is larger than len(a) it will panic. 376 func (a *Address) SetBytes(b []byte) { 377 if len(b) > len(a) { 378 b = b[len(b)-AddressLength:] 379 } 380 copy(a[AddressLength-len(b):], b) 381 } 382 383 // MarshalText returns the hex representation of a. 384 func (a Address) MarshalText() ([]byte, error) { 385 return hexutil.Bytes(a[:]).MarshalText() 386 } 387 388 // UnmarshalText parses a hash in hex syntax. 389 func (a *Address) UnmarshalText(input []byte) error { 390 return hexutil.UnmarshalFixedText("Address", input, a[:]) 391 } 392 393 // UnmarshalJSON parses a hash in hex syntax. 394 func (a *Address) UnmarshalJSON(input []byte) error { 395 return hexutil.UnmarshalFixedJSON(addressT, input, a[:]) 396 } 397 398 // Scan implements Scanner for database/sql. 399 func (a *Address) Scan(src interface{}) error { 400 srcB, ok := src.([]byte) 401 if !ok { 402 return fmt.Errorf("can't scan %T into Address", src) 403 } 404 if len(srcB) != AddressLength { 405 return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength) 406 } 407 copy(a[:], srcB) 408 return nil 409 } 410 411 // Value implements valuer for database/sql. 412 func (a Address) Value() (driver.Value, error) { 413 return a[:], nil 414 } 415 416 // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type. 417 func (a Address) ImplementsGraphQLType(name string) bool { return name == "Address" } 418 419 // UnmarshalGraphQL unmarshals the provided GraphQL query data. 420 func (a *Address) UnmarshalGraphQL(input interface{}) error { 421 var err error 422 switch input := input.(type) { 423 case string: 424 err = a.UnmarshalText([]byte(input)) 425 default: 426 err = fmt.Errorf("Unexpected type for Address: %v", input) 427 } 428 return err 429 } 430 431 // UnprefixedAddress allows marshaling an Address without 0x prefix. 432 type UnprefixedAddress Address 433 434 // UnmarshalText decodes the address from hex. The 0x prefix is optional. 435 func (a *UnprefixedAddress) UnmarshalText(input []byte) error { 436 return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:]) 437 } 438 439 // MarshalText encodes the address as hex. 440 func (a UnprefixedAddress) MarshalText() ([]byte, error) { 441 return []byte(hex.EncodeToString(a[:])), nil 442 } 443 444 // MixedcaseAddress retains the original string, which may or may not be 445 // correctly checksummed 446 type MixedcaseAddress struct { 447 addr Address 448 original string 449 } 450 451 // NewMixedcaseAddress constructor (mainly for testing) 452 func NewMixedcaseAddress(addr Address) MixedcaseAddress { 453 return MixedcaseAddress{addr: addr, original: addr.Hex()} 454 } 455 456 // NewMixedcaseAddressFromString is mainly meant for unit-testing 457 func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) { 458 if !IsHexAddress(hexaddr) { 459 return nil, fmt.Errorf("Invalid address") 460 } 461 a := FromHex(hexaddr) 462 return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil 463 } 464 465 // UnmarshalJSON parses MixedcaseAddress 466 func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error { 467 if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil { 468 return err 469 } 470 return json.Unmarshal(input, &ma.original) 471 } 472 473 // MarshalJSON marshals the original value 474 func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) { 475 if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") { 476 return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:])) 477 } 478 return json.Marshal(fmt.Sprintf("0x%s", ma.original)) 479 } 480 481 // Address returns the address 482 func (ma *MixedcaseAddress) Address() Address { 483 return ma.addr 484 } 485 486 // String implements fmt.Stringer 487 func (ma *MixedcaseAddress) String() string { 488 if ma.ValidChecksum() { 489 return fmt.Sprintf("%s [chksum ok]", ma.original) 490 } 491 return fmt.Sprintf("%s [chksum INVALID]", ma.original) 492 } 493 494 // ValidChecksum returns true if the address has valid checksum 495 func (ma *MixedcaseAddress) ValidChecksum() bool { 496 return ma.original == ma.addr.Hex() 497 } 498 499 // Original returns the mixed-case input string 500 func (ma *MixedcaseAddress) Original() string { 501 return ma.original 502 } 503 504 type DecryptRequest struct { 505 SenderKey []byte `json:"senderKey"` 506 CipherText []byte `json:"cipherText"` 507 CipherTextNonce []byte `json:"cipherTextNonce"` 508 RecipientBoxes []string `json:"recipientBoxes"` 509 RecipientNonce []byte `json:"recipientNonce"` 510 RecipientKeys []string `json:"recipientKeys"` 511 }