github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/common/types.go (about)

     1  // Copyright 2015 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum 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 Spectrum 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 Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package common
    18  
    19  import (
    20  	"encoding/hex"
    21  	"fmt"
    22  	"math/big"
    23  	"math/rand"
    24  	"reflect"
    25  
    26  	"github.com/SmartMeshFoundation/Spectrum/common/hexutil"
    27  	"github.com/SmartMeshFoundation/Spectrum/crypto/sha3"
    28  )
    29  
    30  const (
    31  	HashLength    = 32
    32  	AddressLength = 20
    33  )
    34  
    35  var (
    36  	hashT    = reflect.TypeOf(Hash{})
    37  	addressT = reflect.TypeOf(Address{})
    38  )
    39  
    40  // Hash represents the 32 byte Keccak256 hash of arbitrary data.
    41  type Hash [HashLength]byte
    42  
    43  func BytesToHash(b []byte) Hash {
    44  	var h Hash
    45  	h.SetBytes(b)
    46  	return h
    47  }
    48  func StringToHash(s string) Hash { return BytesToHash([]byte(s)) }
    49  func BigToHash(b *big.Int) Hash  { return BytesToHash(b.Bytes()) }
    50  func HexToHash(s string) Hash    { return BytesToHash(FromHex(s)) }
    51  
    52  // Get the string representation of the underlying hash
    53  func (h Hash) Str() string   { return string(h[:]) }
    54  func (h Hash) Bytes() []byte { return h[:] }
    55  func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
    56  func (h Hash) Hex() string   { return hexutil.Encode(h[:]) }
    57  
    58  // TerminalString implements log.TerminalStringer, formatting a string for console
    59  // output during logging.
    60  func (h Hash) TerminalString() string {
    61  	return fmt.Sprintf("%x…%x", h[:3], h[29:])
    62  }
    63  
    64  // String implements the stringer interface and is used also by the logger when
    65  // doing full logging into a file.
    66  func (h Hash) String() string {
    67  	return h.Hex()
    68  }
    69  
    70  // Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
    71  // without going through the stringer interface used for logging.
    72  func (h Hash) Format(s fmt.State, c rune) {
    73  	fmt.Fprintf(s, "%"+string(c), h[:])
    74  }
    75  
    76  // UnmarshalText parses a hash in hex syntax.
    77  func (h *Hash) UnmarshalText(input []byte) error {
    78  	return hexutil.UnmarshalFixedText("Hash", input, h[:])
    79  }
    80  
    81  // UnmarshalJSON parses a hash in hex syntax.
    82  func (h *Hash) UnmarshalJSON(input []byte) error {
    83  	return hexutil.UnmarshalFixedJSON(hashT, input, h[:])
    84  }
    85  
    86  // MarshalText returns the hex representation of h.
    87  func (h Hash) MarshalText() ([]byte, error) {
    88  	return hexutil.Bytes(h[:]).MarshalText()
    89  }
    90  
    91  // Sets the hash to the value of b. If b is larger than len(h), 'b' will be cropped (from the left).
    92  func (h *Hash) SetBytes(b []byte) {
    93  	if len(b) > len(h) {
    94  		b = b[len(b)-HashLength:]
    95  	}
    96  
    97  	copy(h[HashLength-len(b):], b)
    98  }
    99  
   100  // Set string `s` to h. If s is larger than len(h) s will be cropped (from left) to fit.
   101  func (h *Hash) SetString(s string) { h.SetBytes([]byte(s)) }
   102  
   103  // Sets h to other
   104  func (h *Hash) Set(other Hash) {
   105  	for i, v := range other {
   106  		h[i] = v
   107  	}
   108  }
   109  
   110  // Generate implements testing/quick.Generator.
   111  func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
   112  	m := rand.Intn(len(h))
   113  	for i := len(h) - 1; i > m; i-- {
   114  		h[i] = byte(rand.Uint32())
   115  	}
   116  	return reflect.ValueOf(h)
   117  }
   118  
   119  func EmptyHash(h Hash) bool {
   120  	return h == Hash{}
   121  }
   122  
   123  // UnprefixedHash allows marshaling a Hash without 0x prefix.
   124  type UnprefixedHash Hash
   125  
   126  // UnmarshalText decodes the hash from hex. The 0x prefix is optional.
   127  func (h *UnprefixedHash) UnmarshalText(input []byte) error {
   128  	return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:])
   129  }
   130  
   131  // MarshalText encodes the hash as hex.
   132  func (h UnprefixedHash) MarshalText() ([]byte, error) {
   133  	return []byte(hex.EncodeToString(h[:])), nil
   134  }
   135  
   136  /////////// Address
   137  
   138  // Address represents the 20 byte address of an Ethereum account.
   139  type Address [AddressLength]byte
   140  
   141  func BytesToAddress(b []byte) Address {
   142  	var a Address
   143  	a.SetBytes(b)
   144  	return a
   145  }
   146  func StringToAddress(s string) Address { return BytesToAddress([]byte(s)) }
   147  func BigToAddress(b *big.Int) Address  { return BytesToAddress(b.Bytes()) }
   148  func HexToAddress(s string) Address    { return BytesToAddress(FromHex(s)) }
   149  
   150  // IsHexAddress verifies whether a string can represent a valid hex-encoded
   151  // Ethereum address or not.
   152  func IsHexAddress(s string) bool {
   153  	if hasHexPrefix(s) {
   154  		s = s[2:]
   155  	}
   156  	return len(s) == 2*AddressLength && isHex(s)
   157  }
   158  
   159  // Get the string representation of the underlying address
   160  func (a Address) Str() string   { return string(a[:]) }
   161  func (a Address) Bytes() []byte { return a[:] }
   162  func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }
   163  func (a Address) Hash() Hash    { return BytesToHash(a[:]) }
   164  
   165  // Hex returns an EIP55-compliant hex string representation of the address.
   166  func (a Address) Hex() string {
   167  	unchecksummed := hex.EncodeToString(a[:])
   168  	sha := sha3.NewKeccak256()
   169  	sha.Write([]byte(unchecksummed))
   170  	hash := sha.Sum(nil)
   171  
   172  	result := []byte(unchecksummed)
   173  	for i := 0; i < len(result); i++ {
   174  		hashByte := hash[i/2]
   175  		if i%2 == 0 {
   176  			hashByte = hashByte >> 4
   177  		} else {
   178  			hashByte &= 0xf
   179  		}
   180  		if result[i] > '9' && hashByte > 7 {
   181  			result[i] -= 32
   182  		}
   183  	}
   184  	return "0x" + string(result)
   185  }
   186  
   187  // String implements the stringer interface and is used also by the logger.
   188  func (a Address) String() string {
   189  	return a.Hex()
   190  }
   191  
   192  // Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
   193  // without going through the stringer interface used for logging.
   194  func (a Address) Format(s fmt.State, c rune) {
   195  	fmt.Fprintf(s, "%"+string(c), a[:])
   196  }
   197  
   198  // Sets the address to the value of b. If b is larger than len(a) it will panic
   199  func (a *Address) SetBytes(b []byte) {
   200  	if len(b) > len(a) {
   201  		b = b[len(b)-AddressLength:]
   202  	}
   203  	copy(a[AddressLength-len(b):], b)
   204  }
   205  
   206  // Set string `s` to a. If s is larger than len(a) it will panic
   207  func (a *Address) SetString(s string) { a.SetBytes([]byte(s)) }
   208  
   209  // Sets a to other
   210  func (a *Address) Set(other Address) {
   211  	for i, v := range other {
   212  		a[i] = v
   213  	}
   214  }
   215  
   216  // MarshalText returns the hex representation of a.
   217  func (a Address) MarshalText() ([]byte, error) {
   218  	return hexutil.Bytes(a[:]).MarshalText()
   219  }
   220  
   221  // UnmarshalText parses a hash in hex syntax.
   222  func (a *Address) UnmarshalText(input []byte) error {
   223  	return hexutil.UnmarshalFixedText("Address", input, a[:])
   224  }
   225  
   226  // UnmarshalJSON parses a hash in hex syntax.
   227  func (a *Address) UnmarshalJSON(input []byte) error {
   228  	return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
   229  }
   230  
   231  // UnprefixedHash allows marshaling an Address without 0x prefix.
   232  type UnprefixedAddress Address
   233  
   234  // UnmarshalText decodes the address from hex. The 0x prefix is optional.
   235  func (a *UnprefixedAddress) UnmarshalText(input []byte) error {
   236  	return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:])
   237  }
   238  
   239  // MarshalText encodes the address as hex.
   240  func (a UnprefixedAddress) MarshalText() ([]byte, error) {
   241  	return []byte(hex.EncodeToString(a[:])), nil
   242  }