github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/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  	"database/sql/driver"
    21  	"encoding/hex"
    22  	"encoding/json"
    23  	"fmt"
    24  	"math/big"
    25  	"math/rand"
    26  	"reflect"
    27  	"strings"
    28  
    29  	"github.com/ethereum/go-ethereum/common/hexutil"
    30  	"golang.org/x/crypto/sha3"
    31  )
    32  
    33  // Lengths of hashes and addresses in bytes.
    34  const (
    35  	// HashLength is the expected length of the hash
    36  	HashLength = 32
    37  	// AddressLength is the expected length of the address
    38  	AddressLength = 20
    39  )
    40  
    41  var (
    42  	hashT       = reflect.TypeOf(Hash{})
    43  	addressT    = reflect.TypeOf(Address{})
    44  	ZeroAddress = BytesToAddress([]byte{})
    45  )
    46  
    47  // Hash represents the 32 byte Keccak256 hash of arbitrary data.
    48  type Hash [HashLength]byte
    49  
    50  // BytesToHash sets b to hash.
    51  // If b is larger than len(h), b will be cropped from the left.
    52  func BytesToHash(b []byte) Hash {
    53  	var h Hash
    54  	h.SetBytes(b)
    55  	return h
    56  }
    57  
    58  // BigToHash sets byte representation of b to hash.
    59  // If b is larger than len(h), b will be cropped from the left.
    60  func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }
    61  
    62  // HexToHash sets byte representation of s to hash.
    63  // If b is larger than len(h), b will be cropped from the left.
    64  func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }
    65  
    66  // Bytes gets the byte representation of the underlying hash.
    67  func (h Hash) Bytes() []byte { return h[:] }
    68  
    69  // Big converts a hash to a big integer.
    70  func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
    71  
    72  // Hex converts a hash to a hex string.
    73  func (h Hash) Hex() string { return hexutil.Encode(h[:]) }
    74  
    75  // TerminalString implements log.TerminalStringer, formatting a string for console
    76  // output during logging.
    77  func (h Hash) TerminalString() string {
    78  	return fmt.Sprintf("%x…%x", h[:3], h[29:])
    79  }
    80  
    81  // String implements the stringer interface and is used also by the logger when
    82  // doing full logging into a file.
    83  func (h Hash) String() string {
    84  	return h.Hex()
    85  }
    86  
    87  // Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
    88  // without going through the stringer interface used for logging.
    89  func (h Hash) Format(s fmt.State, c rune) {
    90  	fmt.Fprintf(s, "%"+string(c), h[:])
    91  }
    92  
    93  // UnmarshalText parses a hash in hex syntax.
    94  func (h *Hash) UnmarshalText(input []byte) error {
    95  	return hexutil.UnmarshalFixedText("Hash", input, h[:])
    96  }
    97  
    98  // UnmarshalJSON parses a hash in hex syntax.
    99  func (h *Hash) UnmarshalJSON(input []byte) error {
   100  	return hexutil.UnmarshalFixedJSON(hashT, input, h[:])
   101  }
   102  
   103  // MarshalText returns the hex representation of h.
   104  func (h Hash) MarshalText() ([]byte, error) {
   105  	return hexutil.Bytes(h[:]).MarshalText()
   106  }
   107  
   108  // SetBytes sets the hash to the value of b.
   109  // If b is larger than len(h), b will be cropped from the left.
   110  func (h *Hash) SetBytes(b []byte) {
   111  	if len(b) > len(h) {
   112  		b = b[len(b)-HashLength:]
   113  	}
   114  
   115  	copy(h[HashLength-len(b):], b)
   116  }
   117  
   118  // Generate implements testing/quick.Generator.
   119  func (h Hash) Generate(rand *rand.Rand, size int) reflect.Value {
   120  	m := rand.Intn(len(h))
   121  	for i := len(h) - 1; i > m; i-- {
   122  		h[i] = byte(rand.Uint32())
   123  	}
   124  	return reflect.ValueOf(h)
   125  }
   126  
   127  // Scan implements Scanner for database/sql.
   128  func (h *Hash) Scan(src interface{}) error {
   129  	srcB, ok := src.([]byte)
   130  	if !ok {
   131  		return fmt.Errorf("can't scan %T into Hash", src)
   132  	}
   133  	if len(srcB) != HashLength {
   134  		return fmt.Errorf("can't scan []byte of len %d into Hash, want %d", len(srcB), HashLength)
   135  	}
   136  	copy(h[:], srcB)
   137  	return nil
   138  }
   139  
   140  // Value implements valuer for database/sql.
   141  func (h Hash) Value() (driver.Value, error) {
   142  	return h[:], nil
   143  }
   144  
   145  // UnprefixedHash allows marshaling a Hash without 0x prefix.
   146  type UnprefixedHash Hash
   147  
   148  // UnmarshalText decodes the hash from hex. The 0x prefix is optional.
   149  func (h *UnprefixedHash) UnmarshalText(input []byte) error {
   150  	return hexutil.UnmarshalFixedUnprefixedText("UnprefixedHash", input, h[:])
   151  }
   152  
   153  // MarshalText encodes the hash as hex.
   154  func (h UnprefixedHash) MarshalText() ([]byte, error) {
   155  	return []byte(hex.EncodeToString(h[:])), nil
   156  }
   157  
   158  /////////// Address
   159  
   160  // Address represents the 20 byte address of an Ethereum account.
   161  type Address [AddressLength]byte
   162  
   163  // BytesToAddress returns Address with value b.
   164  // If b is larger than len(h), b will be cropped from the left.
   165  func BytesToAddress(b []byte) Address {
   166  	var a Address
   167  	a.SetBytes(b)
   168  	return a
   169  }
   170  
   171  // BigToAddress returns Address with byte values of b.
   172  // If b is larger than len(h), b will be cropped from the left.
   173  func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) }
   174  
   175  // HexToAddress returns Address with byte values of s.
   176  // If s is larger than len(h), s will be cropped from the left.
   177  func HexToAddress(s string) Address { return BytesToAddress(FromHex(s)) }
   178  
   179  // IsHexAddress verifies whether a string can represent a valid hex-encoded
   180  // Ethereum address or not.
   181  func IsHexAddress(s string) bool {
   182  	if hasHexPrefix(s) {
   183  		s = s[2:]
   184  	}
   185  	return len(s) == 2*AddressLength && isHex(s)
   186  }
   187  
   188  // Bytes gets the string representation of the underlying address.
   189  func (a Address) Bytes() []byte { return a[:] }
   190  
   191  // Big converts an address to a big integer.
   192  func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) }
   193  
   194  // Hash converts an address to a hash by left-padding it with zeros.
   195  func (a Address) Hash() Hash { return BytesToHash(a[:]) }
   196  
   197  // Hex returns an EIP55-compliant hex string representation of the address.
   198  func (a Address) Hex() string {
   199  	unchecksummed := hex.EncodeToString(a[:])
   200  	sha := sha3.NewLegacyKeccak256()
   201  	sha.Write([]byte(unchecksummed))
   202  	hash := sha.Sum(nil)
   203  
   204  	result := []byte(unchecksummed)
   205  	for i := 0; i < len(result); i++ {
   206  		hashByte := hash[i/2]
   207  		if i%2 == 0 {
   208  			hashByte = hashByte >> 4
   209  		} else {
   210  			hashByte &= 0xf
   211  		}
   212  		if result[i] > '9' && hashByte > 7 {
   213  			result[i] -= 32
   214  		}
   215  	}
   216  	return "0x" + string(result)
   217  }
   218  
   219  // String implements fmt.Stringer.
   220  func (a Address) String() string {
   221  	return a.Hex()
   222  }
   223  
   224  // Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
   225  // without going through the stringer interface used for logging.
   226  func (a Address) Format(s fmt.State, c rune) {
   227  	fmt.Fprintf(s, "%"+string(c), a[:])
   228  }
   229  
   230  // SetBytes sets the address to the value of b.
   231  // If b is larger than len(a) it will panic.
   232  func (a *Address) SetBytes(b []byte) {
   233  	if len(b) > len(a) {
   234  		b = b[len(b)-AddressLength:]
   235  	}
   236  	copy(a[AddressLength-len(b):], b)
   237  }
   238  
   239  // MarshalText returns the hex representation of a.
   240  func (a Address) MarshalText() ([]byte, error) {
   241  	return hexutil.Bytes(a[:]).MarshalText()
   242  }
   243  
   244  // UnmarshalText parses a hash in hex syntax.
   245  func (a *Address) UnmarshalText(input []byte) error {
   246  	return hexutil.UnmarshalFixedText("Address", input, a[:])
   247  }
   248  
   249  // UnmarshalJSON parses a hash in hex syntax.
   250  func (a *Address) UnmarshalJSON(input []byte) error {
   251  	return hexutil.UnmarshalFixedJSON(addressT, input, a[:])
   252  }
   253  
   254  // Scan implements Scanner for database/sql.
   255  func (a *Address) Scan(src interface{}) error {
   256  	srcB, ok := src.([]byte)
   257  	if !ok {
   258  		return fmt.Errorf("can't scan %T into Address", src)
   259  	}
   260  	if len(srcB) != AddressLength {
   261  		return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength)
   262  	}
   263  	copy(a[:], srcB)
   264  	return nil
   265  }
   266  
   267  // Value implements valuer for database/sql.
   268  func (a Address) Value() (driver.Value, error) {
   269  	return a[:], nil
   270  }
   271  
   272  // Converts an array of addresses to an array of their hex strings.  Used for printing out an array of addresses
   273  func ConvertToStringSlice(addresses []Address) []string {
   274  	returnList := make([]string, len(addresses))
   275  
   276  	for i, address := range addresses {
   277  		returnList[i] = address.Hex()
   278  	}
   279  
   280  	return returnList
   281  }
   282  
   283  // UnprefixedAddress allows marshaling an Address without 0x prefix.
   284  type UnprefixedAddress Address
   285  
   286  // UnmarshalText decodes the address from hex. The 0x prefix is optional.
   287  func (a *UnprefixedAddress) UnmarshalText(input []byte) error {
   288  	return hexutil.UnmarshalFixedUnprefixedText("UnprefixedAddress", input, a[:])
   289  }
   290  
   291  // MarshalText encodes the address as hex.
   292  func (a UnprefixedAddress) MarshalText() ([]byte, error) {
   293  	return []byte(hex.EncodeToString(a[:])), nil
   294  }
   295  
   296  // MixedcaseAddress retains the original string, which may or may not be
   297  // correctly checksummed
   298  type MixedcaseAddress struct {
   299  	addr     Address
   300  	original string
   301  }
   302  
   303  // NewMixedcaseAddress constructor (mainly for testing)
   304  func NewMixedcaseAddress(addr Address) MixedcaseAddress {
   305  	return MixedcaseAddress{addr: addr, original: addr.Hex()}
   306  }
   307  
   308  // NewMixedcaseAddressFromString is mainly meant for unit-testing
   309  func NewMixedcaseAddressFromString(hexaddr string) (*MixedcaseAddress, error) {
   310  	if !IsHexAddress(hexaddr) {
   311  		return nil, fmt.Errorf("Invalid address")
   312  	}
   313  	a := FromHex(hexaddr)
   314  	return &MixedcaseAddress{addr: BytesToAddress(a), original: hexaddr}, nil
   315  }
   316  
   317  // UnmarshalJSON parses MixedcaseAddress
   318  func (ma *MixedcaseAddress) UnmarshalJSON(input []byte) error {
   319  	if err := hexutil.UnmarshalFixedJSON(addressT, input, ma.addr[:]); err != nil {
   320  		return err
   321  	}
   322  	return json.Unmarshal(input, &ma.original)
   323  }
   324  
   325  // MarshalJSON marshals the original value
   326  func (ma *MixedcaseAddress) MarshalJSON() ([]byte, error) {
   327  	if strings.HasPrefix(ma.original, "0x") || strings.HasPrefix(ma.original, "0X") {
   328  		return json.Marshal(fmt.Sprintf("0x%s", ma.original[2:]))
   329  	}
   330  	return json.Marshal(fmt.Sprintf("0x%s", ma.original))
   331  }
   332  
   333  // Address returns the address
   334  func (ma *MixedcaseAddress) Address() Address {
   335  	return ma.addr
   336  }
   337  
   338  // String implements fmt.Stringer
   339  func (ma *MixedcaseAddress) String() string {
   340  	if ma.ValidChecksum() {
   341  		return fmt.Sprintf("%s [chksum ok]", ma.original)
   342  	}
   343  	return fmt.Sprintf("%s [chksum INVALID]", ma.original)
   344  }
   345  
   346  // ValidChecksum returns true if the address has valid checksum
   347  func (ma *MixedcaseAddress) ValidChecksum() bool {
   348  	return ma.original == ma.addr.Hex()
   349  }
   350  
   351  // Original returns the mixed-case input string
   352  func (ma *MixedcaseAddress) Original() string {
   353  	return ma.original
   354  }