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