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