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