github.com/dominant-strategies/go-quai@v0.28.2/crypto/crypto.go (about)

     1  // Copyright 2014 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 crypto
    18  
    19  import (
    20  	"bufio"
    21  	"crypto/ecdsa"
    22  	"crypto/elliptic"
    23  	"crypto/rand"
    24  	"encoding/binary"
    25  	"encoding/hex"
    26  	"errors"
    27  	"fmt"
    28  	"hash"
    29  	"io"
    30  	"io/ioutil"
    31  	"math/big"
    32  	"os"
    33  
    34  	"github.com/dominant-strategies/go-quai/common"
    35  	"github.com/dominant-strategies/go-quai/common/math"
    36  	"golang.org/x/crypto/sha3"
    37  )
    38  
    39  // SignatureLength indicates the byte length required to carry a signature with recovery id.
    40  const SignatureLength = 64 + 1 // 64 bytes ECDSA signature + 1 byte recovery id
    41  
    42  // RecoveryIDOffset points to the byte offset within the signature that contains the recovery id.
    43  const RecoveryIDOffset = 64
    44  
    45  // DigestLength sets the signature digest exact length
    46  const DigestLength = 32
    47  
    48  var (
    49  	secp256k1N, _  = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
    50  	secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
    51  )
    52  
    53  var errInvalidPubkey = errors.New("invalid secp256k1 public key")
    54  
    55  // KeccakState wraps sha3.state. In addition to the usual hash methods, it also supports
    56  // Read to get a variable amount of data from the hash state. Read is faster than Sum
    57  // because it doesn't copy the internal state, but also modifies the internal state.
    58  type KeccakState interface {
    59  	hash.Hash
    60  	Read([]byte) (int, error)
    61  }
    62  
    63  // NewKeccakState creates a new KeccakState
    64  func NewKeccakState() KeccakState {
    65  	return sha3.NewLegacyKeccak256().(KeccakState)
    66  }
    67  
    68  // HashData hashes the provided data using the KeccakState and returns a 32 byte hash
    69  func HashData(kh KeccakState, data []byte) (h common.Hash) {
    70  	kh.Reset()
    71  	kh.Write(data)
    72  	kh.Read(h[:])
    73  	return h
    74  }
    75  
    76  // Keccak256 calculates and returns the Keccak256 hash of the input data.
    77  func Keccak256(data ...[]byte) []byte {
    78  	b := make([]byte, 32)
    79  	d := NewKeccakState()
    80  	for _, b := range data {
    81  		d.Write(b)
    82  	}
    83  	d.Read(b)
    84  	return b
    85  }
    86  
    87  // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
    88  // converting it to an internal Hash data structure.
    89  func Keccak256Hash(data ...[]byte) (h common.Hash) {
    90  	d := NewKeccakState()
    91  	for _, b := range data {
    92  		d.Write(b)
    93  	}
    94  	d.Read(h[:])
    95  	return h
    96  }
    97  
    98  // Keccak512 calculates and returns the Keccak512 hash of the input data.
    99  func Keccak512(data ...[]byte) []byte {
   100  	d := sha3.NewLegacyKeccak512()
   101  	for _, b := range data {
   102  		d.Write(b)
   103  	}
   104  	return d.Sum(nil)
   105  }
   106  
   107  // CreateAddress creates an quai address given the bytes and the nonce
   108  func CreateAddress(b common.Address, nonce uint64, code []byte) common.Address {
   109  	nonceBytes := make([]byte, 8)
   110  	binary.BigEndian.PutUint64(nonceBytes, uint64(nonce))
   111  	return common.BytesToAddress(Keccak256(b.Bytes(), nonceBytes, code)[12:])
   112  }
   113  
   114  // CreateAddress2 creates an quai address given the address bytes, initial
   115  // contract code hash and a salt.
   116  func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
   117  	return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
   118  }
   119  
   120  // ToECDSA creates a private key with the given D value.
   121  func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
   122  	return toECDSA(d, true)
   123  }
   124  
   125  // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost
   126  // never be used unless you are sure the input is valid and want to avoid hitting
   127  // errors due to bad origin encoding (0 prefixes cut off).
   128  func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
   129  	priv, _ := toECDSA(d, false)
   130  	return priv
   131  }
   132  
   133  // toECDSA creates a private key with the given D value. The strict parameter
   134  // controls whether the key's length should be enforced at the curve size or
   135  // it can also accept legacy encodings (0 prefixes).
   136  func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
   137  	priv := new(ecdsa.PrivateKey)
   138  	priv.PublicKey.Curve = S256()
   139  	if strict && 8*len(d) != priv.Params().BitSize {
   140  		return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
   141  	}
   142  	priv.D = new(big.Int).SetBytes(d)
   143  
   144  	// The priv.D must < N
   145  	if priv.D.Cmp(secp256k1N) >= 0 {
   146  		return nil, fmt.Errorf("invalid private key, >=N")
   147  	}
   148  	// The priv.D must not be zero or negative.
   149  	if priv.D.Sign() <= 0 {
   150  		return nil, fmt.Errorf("invalid private key, zero or negative")
   151  	}
   152  
   153  	priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
   154  	if priv.PublicKey.X == nil {
   155  		return nil, errors.New("invalid private key")
   156  	}
   157  	return priv, nil
   158  }
   159  
   160  // FromECDSA exports a private key into a binary dump.
   161  func FromECDSA(priv *ecdsa.PrivateKey) []byte {
   162  	if priv == nil {
   163  		return nil
   164  	}
   165  	return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
   166  }
   167  
   168  // UnmarshalPubkey converts bytes to a secp256k1 public key.
   169  func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
   170  	x, y := elliptic.Unmarshal(S256(), pub)
   171  	if x == nil {
   172  		return nil, errInvalidPubkey
   173  	}
   174  	return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
   175  }
   176  
   177  func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
   178  	if pub == nil || pub.X == nil || pub.Y == nil {
   179  		return nil
   180  	}
   181  	return elliptic.Marshal(S256(), pub.X, pub.Y)
   182  }
   183  
   184  // HexToECDSA parses a secp256k1 private key.
   185  func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
   186  	b, err := hex.DecodeString(hexkey)
   187  	if byteErr, ok := err.(hex.InvalidByteError); ok {
   188  		return nil, fmt.Errorf("invalid hex character %q in private key", byte(byteErr))
   189  	} else if err != nil {
   190  		return nil, errors.New("invalid hex data for private key")
   191  	}
   192  	return ToECDSA(b)
   193  }
   194  
   195  // LoadECDSA loads a secp256k1 private key from the given file.
   196  func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
   197  	fd, err := os.Open(file)
   198  	if err != nil {
   199  		return nil, err
   200  	}
   201  	defer fd.Close()
   202  
   203  	r := bufio.NewReader(fd)
   204  	buf := make([]byte, 64)
   205  	n, err := readASCII(buf, r)
   206  	if err != nil {
   207  		return nil, err
   208  	} else if n != len(buf) {
   209  		return nil, fmt.Errorf("key file too short, want 64 hex characters")
   210  	}
   211  	if err := checkKeyFileEnd(r); err != nil {
   212  		return nil, err
   213  	}
   214  
   215  	return HexToECDSA(string(buf))
   216  }
   217  
   218  // readASCII reads into 'buf', stopping when the buffer is full or
   219  // when a non-printable control character is encountered.
   220  func readASCII(buf []byte, r *bufio.Reader) (n int, err error) {
   221  	for ; n < len(buf); n++ {
   222  		buf[n], err = r.ReadByte()
   223  		switch {
   224  		case err == io.EOF || buf[n] < '!':
   225  			return n, nil
   226  		case err != nil:
   227  			return n, err
   228  		}
   229  	}
   230  	return n, nil
   231  }
   232  
   233  // checkKeyFileEnd skips over additional newlines at the end of a key file.
   234  func checkKeyFileEnd(r *bufio.Reader) error {
   235  	for i := 0; ; i++ {
   236  		b, err := r.ReadByte()
   237  		switch {
   238  		case err == io.EOF:
   239  			return nil
   240  		case err != nil:
   241  			return err
   242  		case b != '\n' && b != '\r':
   243  			return fmt.Errorf("invalid character %q at end of key file", b)
   244  		case i >= 2:
   245  			return errors.New("key file too long, want 64 hex characters")
   246  		}
   247  	}
   248  }
   249  
   250  // SaveECDSA saves a secp256k1 private key to the given file with
   251  // restrictive permissions. The key data is saved hex-encoded.
   252  func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
   253  	k := hex.EncodeToString(FromECDSA(key))
   254  	return ioutil.WriteFile(file, []byte(k), 0600)
   255  }
   256  
   257  // GenerateKey generates a new private key.
   258  func GenerateKey() (*ecdsa.PrivateKey, error) {
   259  	return ecdsa.GenerateKey(S256(), rand.Reader)
   260  }
   261  
   262  // ValidateSignatureValues verifies whether the signature values are valid with
   263  // the given chain rules. The v value is assumed to be either 0 or 1.
   264  func ValidateSignatureValues(v byte, r, s *big.Int) bool {
   265  	if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
   266  		return false
   267  	}
   268  	// reject upper range of s values (ECDSA malleability)
   269  	// see discussion in secp256k1/libsecp256k1/include/secp256k1.h
   270  	if s.Cmp(secp256k1halfN) > 0 {
   271  		return false
   272  	}
   273  	// allow s to be in full N range
   274  	return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
   275  }
   276  
   277  func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
   278  	pubBytes := FromECDSAPub(&p)
   279  	return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
   280  }
   281  
   282  func zeroBytes(bytes []byte) {
   283  	for i := range bytes {
   284  		bytes[i] = 0
   285  	}
   286  }