github.com/MaynardMiner/ethereumprogpow@v1.8.23/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  	"crypto/ecdsa"
    21  	"crypto/elliptic"
    22  	"crypto/rand"
    23  	"encoding/hex"
    24  	"errors"
    25  	"fmt"
    26  	"io"
    27  	"io/ioutil"
    28  	"math/big"
    29  	"os"
    30  
    31  	"github.com/ethereumprogpow/ethereumprogpow/common"
    32  	"github.com/ethereumprogpow/ethereumprogpow/common/math"
    33  	"github.com/ethereumprogpow/ethereumprogpow/rlp"
    34  	"golang.org/x/crypto/sha3"
    35  )
    36  
    37  var (
    38  	secp256k1N, _  = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
    39  	secp256k1halfN = new(big.Int).Div(secp256k1N, big.NewInt(2))
    40  )
    41  
    42  var errInvalidPubkey = errors.New("invalid secp256k1 public key")
    43  
    44  // Keccak256 calculates and returns the Keccak256 hash of the input data.
    45  func Keccak256(data ...[]byte) []byte {
    46  	d := sha3.NewLegacyKeccak256()
    47  	for _, b := range data {
    48  		d.Write(b)
    49  	}
    50  	return d.Sum(nil)
    51  }
    52  
    53  // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
    54  // converting it to an internal Hash data structure.
    55  func Keccak256Hash(data ...[]byte) (h common.Hash) {
    56  	d := sha3.NewLegacyKeccak256()
    57  	for _, b := range data {
    58  		d.Write(b)
    59  	}
    60  	d.Sum(h[:0])
    61  	return h
    62  }
    63  
    64  // Keccak512 calculates and returns the Keccak512 hash of the input data.
    65  func Keccak512(data ...[]byte) []byte {
    66  	d := sha3.NewLegacyKeccak512()
    67  	for _, b := range data {
    68  		d.Write(b)
    69  	}
    70  	return d.Sum(nil)
    71  }
    72  
    73  // CreateAddress creates an ethereum address given the bytes and the nonce
    74  func CreateAddress(b common.Address, nonce uint64) common.Address {
    75  	data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
    76  	return common.BytesToAddress(Keccak256(data)[12:])
    77  }
    78  
    79  // CreateAddress2 creates an ethereum address given the address bytes, initial
    80  // contract code hash and a salt.
    81  func CreateAddress2(b common.Address, salt [32]byte, inithash []byte) common.Address {
    82  	return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt[:], inithash)[12:])
    83  }
    84  
    85  // ToECDSA creates a private key with the given D value.
    86  func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
    87  	return toECDSA(d, true)
    88  }
    89  
    90  // ToECDSAUnsafe blindly converts a binary blob to a private key. It should almost
    91  // never be used unless you are sure the input is valid and want to avoid hitting
    92  // errors due to bad origin encoding (0 prefixes cut off).
    93  func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
    94  	priv, _ := toECDSA(d, false)
    95  	return priv
    96  }
    97  
    98  // toECDSA creates a private key with the given D value. The strict parameter
    99  // controls whether the key's length should be enforced at the curve size or
   100  // it can also accept legacy encodings (0 prefixes).
   101  func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
   102  	priv := new(ecdsa.PrivateKey)
   103  	priv.PublicKey.Curve = S256()
   104  	if strict && 8*len(d) != priv.Params().BitSize {
   105  		return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
   106  	}
   107  	priv.D = new(big.Int).SetBytes(d)
   108  
   109  	// The priv.D must < N
   110  	if priv.D.Cmp(secp256k1N) >= 0 {
   111  		return nil, fmt.Errorf("invalid private key, >=N")
   112  	}
   113  	// The priv.D must not be zero or negative.
   114  	if priv.D.Sign() <= 0 {
   115  		return nil, fmt.Errorf("invalid private key, zero or negative")
   116  	}
   117  
   118  	priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
   119  	if priv.PublicKey.X == nil {
   120  		return nil, errors.New("invalid private key")
   121  	}
   122  	return priv, nil
   123  }
   124  
   125  // FromECDSA exports a private key into a binary dump.
   126  func FromECDSA(priv *ecdsa.PrivateKey) []byte {
   127  	if priv == nil {
   128  		return nil
   129  	}
   130  	return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
   131  }
   132  
   133  // UnmarshalPubkey converts bytes to a secp256k1 public key.
   134  func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
   135  	x, y := elliptic.Unmarshal(S256(), pub)
   136  	if x == nil {
   137  		return nil, errInvalidPubkey
   138  	}
   139  	return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
   140  }
   141  
   142  func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
   143  	if pub == nil || pub.X == nil || pub.Y == nil {
   144  		return nil
   145  	}
   146  	return elliptic.Marshal(S256(), pub.X, pub.Y)
   147  }
   148  
   149  // HexToECDSA parses a secp256k1 private key.
   150  func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
   151  	b, err := hex.DecodeString(hexkey)
   152  	if err != nil {
   153  		return nil, errors.New("invalid hex string")
   154  	}
   155  	return ToECDSA(b)
   156  }
   157  
   158  // LoadECDSA loads a secp256k1 private key from the given file.
   159  func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
   160  	buf := make([]byte, 64)
   161  	fd, err := os.Open(file)
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  	defer fd.Close()
   166  	if _, err := io.ReadFull(fd, buf); err != nil {
   167  		return nil, err
   168  	}
   169  
   170  	key, err := hex.DecodeString(string(buf))
   171  	if err != nil {
   172  		return nil, err
   173  	}
   174  	return ToECDSA(key)
   175  }
   176  
   177  // SaveECDSA saves a secp256k1 private key to the given file with
   178  // restrictive permissions. The key data is saved hex-encoded.
   179  func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
   180  	k := hex.EncodeToString(FromECDSA(key))
   181  	return ioutil.WriteFile(file, []byte(k), 0600)
   182  }
   183  
   184  func GenerateKey() (*ecdsa.PrivateKey, error) {
   185  	return ecdsa.GenerateKey(S256(), rand.Reader)
   186  }
   187  
   188  // ValidateSignatureValues verifies whether the signature values are valid with
   189  // the given chain rules. The v value is assumed to be either 0 or 1.
   190  func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
   191  	if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
   192  		return false
   193  	}
   194  	// reject upper range of s values (ECDSA malleability)
   195  	// see discussion in secp256k1/libsecp256k1/include/secp256k1.h
   196  	if homestead && s.Cmp(secp256k1halfN) > 0 {
   197  		return false
   198  	}
   199  	// Frontier: allow s to be in full N range
   200  	return r.Cmp(secp256k1N) < 0 && s.Cmp(secp256k1N) < 0 && (v == 0 || v == 1)
   201  }
   202  
   203  func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
   204  	pubBytes := FromECDSAPub(&p)
   205  	return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
   206  }
   207  
   208  func zeroBytes(bytes []byte) {
   209  	for i := range bytes {
   210  		bytes[i] = 0
   211  	}
   212  }