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