github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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/hex"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"math/big"
    27  	"math/rand"
    28  	"reflect"
    29  	"strings"
    30  
    31  	"golang.org/x/crypto/sha3"
    32  
    33  	"github.com/scroll-tech/go-ethereum/common/hexutil"
    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  )
    43  
    44  var (
    45  	hashT    = reflect.TypeOf(Hash{})
    46  	addressT = reflect.TypeOf(Address{})
    47  )
    48  
    49  // Hash represents the 32 byte Keccak256 hash of arbitrary data.
    50  type Hash [HashLength]byte
    51  
    52  // BytesToHash sets b to hash.
    53  // If b is larger than len(h), b will be cropped from the left.
    54  func BytesToHash(b []byte) Hash {
    55  	var h Hash
    56  	h.SetBytes(b)
    57  	return h
    58  }
    59  
    60  // BigToHash sets byte representation of b to hash.
    61  // If b is larger than len(h), b will be cropped from the left.
    62  func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
    63  
    64  // HexToHash sets byte representation of s to hash.
    65  // If b is larger than len(h), b will be cropped from the left.
    66  func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
    67  
    68  // Bytes gets the byte representation of the underlying hash.
    69  func (h Hash) Bytes() []byte { return h[:] }
    70  
    71  // Big converts a hash to a big integer.
    72  func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
    73  
    74  // Hex converts a hash to a hex string.
    75  func (h Hash) Hex() string { return hexutil.Encode(h[:]) }
    76  
    77  // TerminalString implements log.TerminalStringer, formatting a string for console
    78  // output during logging.
    79  func (h Hash) TerminalString() string {
    80  	return fmt.Sprintf("%x..%x", h[:3], h[29:])
    81  }
    82  
    83  // String implements the stringer interface and is used also by the logger when
    84  // doing full logging into a file.
    85  func (h Hash) String() string {
    86  	return h.Hex()
    87  }
    88  
    89  // Format implements fmt.Formatter.
    90  // Hash supports the %v, %s, %q, %x, %X and %d format verbs.
    91  func (h Hash) Format(s fmt.State, c rune) {
    92  	hexb := make([]byte, 2+len(h)*2)
    93  	copy(hexb, "0x")
    94  	hex.Encode(hexb[2:], h[:])
    95  
    96  	switch c {
    97  	case 'x', 'X':
    98  		if !s.Flag('#') {
    99  			hexb = hexb[2:]
   100  		}
   101  		if c == 'X' {
   102  			hexb = bytes.ToUpper(hexb)
   103  		}
   104  		fallthrough
   105  	case 'v', 's':
   106  		s.Write(hexb)
   107  	case 'q':
   108  		q := []byte{'"'}
   109  		s.Write(q)
   110  		s.Write(hexb)
   111  		s.Write(q)
   112  	case 'd':
   113  		fmt.Fprint(s, ([len(h)]byte)(h))
   114  	default:
   115  		fmt.Fprintf(s, "%%!%c(hash=%x)", c, h)
   116  	}
   117  }
   118  
   119  // UnmarshalText parses a hash in hex syntax.
   120  func (h *Hash) UnmarshalText(input []byte) error {
   121  	return hexutil.UnmarshalFixedText("Hash", input, h[:])
   122  }
   123  
   124  // UnmarshalJSON parses a hash in hex syntax.
   125  func (h *Hash) UnmarshalJSON(input []byte) error {
   126  	return hexutil.UnmarshalFixedJSON(hashT, input, h[:])
   127  }
   128  
   129  // MarshalText returns the hex representation of h.
   130  func (h Hash) MarshalText() ([]byte, error) {
   131  	return hexutil.Bytes(h[:]).MarshalText()
   132  }
   133  
   134  // SetBytes sets the hash to the value of b.
   135  // If b is larger than len(h), b will be cropped from the left.
   136  func (h *Hash) SetBytes(b []byte) {
   137  	if len(b) > len(h) {
   138  		b = b[len(b)-HashLength:]
   139  	}
   140  
   141  	copy(h[HashLength-len(b):], b)
   142  }
   143  
   144  // Generate implements testing/quick.Generator.
   145  func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
   146  	m := rand.Intn(len(h))
   147  	for i := len(h) - 1; i > m; i-- {
   148  		h[i] = byte(rand.Uint32())
   149  	}
   150  	return reflect.ValueOf(h)
   151  }
   152  
   153  // Scan implements Scanner for database/sql.
   154  func (h *Hash) Scan(src interface{}) error {
   155  	srcB, ok := src.([]byte)
   156  	if !ok {
   157  		return fmt.Errorf("can't scan %T into Hash", src)
   158  	}
   159  	if len(srcB) != HashLength {
   160  		return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength)
   161  	}
   162  	copy(h[:], srcB)
   163  	return nil
   164  }
   165  
   166  // Value implements valuer for database/sql.
   167  func (h Hash) Value() (driver.Value, error) {
   168  	return h[:], nil
   169  }
   170  
   171  // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
   172  func (Hash) ImplementsGraphQLType(name string) bool { return name == "Bytes32" }
   173  
   174  // UnmarshalGraphQL unmarshals the provided GraphQL query data.
   175  func (h *Hash) UnmarshalGraphQL(input interface{}) error {
   176  	var err error
   177  	switch input := input.(type) {
   178  	case string:
   179  		err = h.UnmarshalText([]byte(input))
   180  	default:
   181  		err = fmt.Errorf("unexpected type %T for Hash", input)
   182  	}
   183  	return err
   184  }
   185  
   186  // UnprefixedHash allows marshaling a Hash without 0x prefix.
   187  type UnprefixedHash Hash
   188  
   189  // UnmarshalText decodes the hash from hex. The 0x prefix is optional.
   190  func (h *UnprefixedHash) UnmarshalText(input []byte) error {
   191  	return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:])
   192  }
   193  
   194  // MarshalText encodes the hash as hex.
   195  func (h UnprefixedHash) MarshalText() ([]byte, error) {
   196  	return []byte(hex.EncodeToString(h[:])), nil
   197  }
   198  
   199  /////////// Address
   200  
   201  // Address represents the 20 byte address of an Ethereum account.
   202  type Address [AddressLength]byte
   203  
   204  // BytesToAddress returns Address with value b.
   205  // If b is larger than len(h), b will be cropped from the left.
   206  func BytesToAddress(b []byte) Address {
   207  	var a Address
   208  	a.SetBytes(b)
   209  	return a
   210  }
   211  
   212  // BigToAddress returns Address with byte values of b.
   213  // If b is larger than len(h), b will be cropped from the left.
   214  func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }
   215  
   216  // HexToAddress returns Address with byte values of s.
   217  // If s is larger than len(h), s will be cropped from the left.
   218  func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }
   219  
   220  // IsHexAddress verifies whether a string can represent a valid hex-encoded
   221  // Ethereum address or not.
   222  func IsHexAddress(s string) bool {
   223  	if has0xPrefix(s) {
   224  		s = s[2:]
   225  	}
   226  	return len(s) == 2*AddressLength && isHex(s)
   227  }
   228  
   229  // Bytes gets the string representation of the underlying address.
   230  func (a Address) Bytes() []byte { return a[:] }
   231  
   232  func (a Address) Bytes32() []byte {
   233  	ret := make([]byte, 32)
   234  	copy(ret, a.Bytes())
   235  	return ret
   236  }
   237  
   238  // Hash converts an address to a hash by left-padding it with zeros.
   239  func (a Address) Hash() Hash { return BytesToHash(a[:]) }
   240  
   241  // Hex returns an EIP55-compliant hex string representation of the address.
   242  func (a Address) Hex() string {
   243  	return string(a.checksumHex())
   244  }
   245  
   246  // String implements fmt.Stringer.
   247  func (a Address) String() string {
   248  	return a.Hex()
   249  }
   250  
   251  func (a *Address) checksumHex() []byte {
   252  	buf := a.hex()
   253  
   254  	// compute checksum
   255  	sha := sha3.NewLegacyKeccak256()
   256  	sha.Write(buf[2:])
   257  	hash := sha.Sum(nil)
   258  	for i := 2; i < len(buf); i++ {
   259  		hashByte := hash[(i-2)/2]
   260  		if i%2 == 0 {
   261  			hashByte = hashByte >> 4
   262  		} else {
   263  			hashByte &= 0xf
   264  		}
   265  		if buf[i] > '9' && hashByte > 7 {
   266  			buf[i] -= 32
   267  		}
   268  	}
   269  	return buf[:]
   270  }
   271  
   272  func (a Address) hex() []byte {
   273  	var buf [len(a)*2 + 2]byte
   274  	copy(buf[:2], "0x")
   275  	hex.Encode(buf[2:], a[:])
   276  	return buf[:]
   277  }
   278  
   279  // Format implements fmt.Formatter.
   280  // Address supports the %v, %s, %q, %x, %X and %d format verbs.
   281  func (a Address) Format(s fmt.State, c rune) {
   282  	switch c {
   283  	case 'v', 's':
   284  		s.Write(a.checksumHex())
   285  	case 'q':
   286  		q := []byte{'"'}
   287  		s.Write(q)
   288  		s.Write(a.checksumHex())
   289  		s.Write(q)
   290  	case 'x', 'X':
   291  		// %x disables the checksum.
   292  		hex := a.hex()
   293  		if !s.Flag('#') {
   294  			hex = hex[2:]
   295  		}
   296  		if c == 'X' {
   297  			hex = bytes.ToUpper(hex)
   298  		}
   299  		s.Write(hex)
   300  	case 'd':
   301  		fmt.Fprint(s, ([len(a)]byte)(a))
   302  	default:
   303  		fmt.Fprintf(s, "%%!%c(address=%x)", c, a)
   304  	}
   305  }
   306  
   307  // SetBytes sets the address to the value of b.
   308  // If b is larger than len(a), b will be cropped from the left.
   309  func (a *Address) SetBytes(b []byte) {
   310  	if len(b) > len(a) {
   311  		b = b[len(b)-AddressLength:]
   312  	}
   313  	copy(a[AddressLength-len(b):], b)
   314  }
   315  
   316  // MarshalText returns the hex representation of a.
   317  func (a Address) MarshalText() ([]byte, error) {
   318  	return hexutil.Bytes(a[:]).MarshalText()
   319  }
   320  
   321  // UnmarshalText parses a hash in hex syntax.
   322  func (a *Address) UnmarshalText(input []byte) error {
   323  	return hexutil.UnmarshalFixedText("Address", input, a[:])
   324  }
   325  
   326  // UnmarshalJSON parses a hash in hex syntax.
   327  func (a *Address) UnmarshalJSON(input []byte) error {
   328  	return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
   329  }
   330  
   331  // Scan implements Scanner for database/sql.
   332  func (a *Address) Scan(src interface{}) error {
   333  	srcB, ok := src.([]byte)
   334  	if !ok {
   335  		return fmt.Errorf("can't scan %T into Address", src)
   336  	}
   337  	if len(srcB) != AddressLength {
   338  		return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength)
   339  	}
   340  	copy(a[:], srcB)
   341  	return nil
   342  }
   343  
   344  // Value implements valuer for database/sql.
   345  func (a Address) Value() (driver.Value, error) {
   346  	return a[:], nil
   347  }
   348  
   349  // ImplementsGraphQLType returns true if Hash implements the specified GraphQL type.
   350  func (a Address) ImplementsGraphQLType(name string) bool { return name == "Address" }
   351  
   352  // UnmarshalGraphQL unmarshals the provided GraphQL query data.
   353  func (a *Address) UnmarshalGraphQL(input interface{}) error {
   354  	var err error
   355  	switch input := input.(type) {
   356  	case string:
   357  		err = a.UnmarshalText([]byte(input))
   358  	default:
   359  		err = fmt.Errorf("unexpected type %T for Address", input)
   360  	}
   361  	return err
   362  }
   363  
   364  // UnprefixedAddress allows marshaling an Address without 0x prefix.
   365  type UnprefixedAddress Address
   366  
   367  // UnmarshalText decodes the address from hex. The 0x prefix is optional.
   368  func (a *UnprefixedAddress) UnmarshalText(input []byte) error {
   369  	return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:])
   370  }
   371  
   372  // MarshalText encodes the address as hex.
   373  func (a UnprefixedAddress) MarshalText() ([]byte, error) {
   374  	return []byte(hex.EncodeToString(a[:])), nil
   375  }
   376  
   377  // MixedcaseAddress retains the original string, which may or may not be
   378  // correctly checksummed
   379  type MixedcaseAddress struct {
   380  	addr     Address
   381  	original string
   382  }
   383  
   384  // NewMixedcaseAddress constructor (mainly for testing)
   385  func NewMixedcaseAddress(addr Address) MixedcaseAddress {
   386  	return MixedcaseAddress{addr: addr, original: addr.Hex()}
   387  }
   388  
   389  // NewMixedcaseAddressFromString is mainly meant for unit-testing
   390  func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) {
   391  	if !IsHexAddress(hexaddr) {
   392  		return nil, errors.New("invalid address")
   393  	}
   394  	a := FromHex(hexaddr)
   395  	return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil
   396  }
   397  
   398  // UnmarshalJSON parses MixedcaseAddress
   399  func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error {
   400  	if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil {
   401  		return err
   402  	}
   403  	return json.Unmarshal(input, &ma.original)
   404  }
   405  
   406  // MarshalJSON marshals the original value
   407  func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) {
   408  	if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") {
   409  		return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:]))
   410  	}
   411  	return json.Marshal(fmt.Sprintf("0x%s", ma.original))
   412  }
   413  
   414  // Address returns the address
   415  func (ma *MixedcaseAddress) Address() Address {
   416  	return ma.addr
   417  }
   418  
   419  // String implements fmt.Stringer
   420  func (ma *MixedcaseAddress) String() string {
   421  	if ma.ValidChecksum() {
   422  		return fmt.Sprintf("%s [chksum ok]", ma.original)
   423  	}
   424  	return fmt.Sprintf("%s [chksum INVALID]", ma.original)
   425  }
   426  
   427  // ValidChecksum returns true if the address has valid checksum
   428  func (ma *MixedcaseAddress) ValidChecksum() bool {
   429  	return ma.original == ma.addr.Hex()
   430  }
   431  
   432  // Original returns the mixed-case input string
   433  func (ma *MixedcaseAddress) Original() string {
   434  	return ma.original
   435  }