github.com/amazechain/amc@v0.1.3/internal/avm/common/types.go (about)

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