github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/common/types.go (about)

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