signature_nocgo.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. // Copyright 2017 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. //go:build nacl || js || !cgo || gofuzz
  17. // +build nacl js !cgo gofuzz
  18. package crypto
  19. import (
  20. "crypto/ecdsa"
  21. "crypto/elliptic"
  22. "errors"
  23. "fmt"
  24. "github.com/btcsuite/btcd/btcec/v2"
  25. btc_ecdsa "github.com/btcsuite/btcd/btcec/v2/ecdsa"
  26. )
  27. // Ecrecover returns the uncompressed public key that created the given signature.
  28. func Ecrecover(hash, sig []byte) ([]byte, error) {
  29. pub, err := sigToPub(hash, sig)
  30. if err != nil {
  31. return nil, err
  32. }
  33. bytes := pub.SerializeUncompressed()
  34. return bytes, err
  35. }
  36. func sigToPub(hash, sig []byte) (*btcec.PublicKey, error) {
  37. if len(sig) != SignatureLength {
  38. return nil, errors.New("invalid signature")
  39. }
  40. // Convert to btcec input format with 'recovery id' v at the beginning.
  41. btcsig := make([]byte, SignatureLength)
  42. btcsig[0] = sig[RecoveryIDOffset] + 27
  43. copy(btcsig[1:], sig)
  44. pub, _, err := btc_ecdsa.RecoverCompact(btcsig, hash)
  45. return pub, err
  46. }
  47. // SigToPub returns the public key that created the given signature.
  48. func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
  49. pub, err := sigToPub(hash, sig)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return pub.ToECDSA(), nil
  54. }
  55. // Sign calculates an ECDSA signature.
  56. //
  57. // This function is susceptible to chosen plaintext attacks that can leak
  58. // information about the private key that is used for signing. Callers must
  59. // be aware that the given hash cannot be chosen by an adversary. Common
  60. // solution is to hash any input before calculating the signature.
  61. //
  62. // The produced signature is in the [R || S || V] format where V is 0 or 1.
  63. func Sign(hash []byte, prv *ecdsa.PrivateKey) ([]byte, error) {
  64. if len(hash) != 32 {
  65. return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
  66. }
  67. if prv.Curve != btcec.S256() {
  68. return nil, fmt.Errorf("private key curve is not secp256k1")
  69. }
  70. // ecdsa.PrivateKey -> btcec.PrivateKey
  71. var priv btcec.PrivateKey
  72. if overflow := priv.Key.SetByteSlice(prv.D.Bytes()); overflow || priv.Key.IsZero() {
  73. return nil, fmt.Errorf("invalid private key")
  74. }
  75. defer priv.Zero()
  76. sig, err := btc_ecdsa.SignCompact(&priv, hash, false) // ref uncompressed pubkey
  77. if err != nil {
  78. return nil, err
  79. }
  80. // Convert to Ethereum signature format with 'recovery id' v at the end.
  81. v := sig[0] - 27
  82. copy(sig, sig[1:])
  83. sig[RecoveryIDOffset] = v
  84. return sig, nil
  85. }
  86. // VerifySignature checks that the given public key created signature over hash.
  87. // The public key should be in compressed (33 bytes) or uncompressed (65 bytes) format.
  88. // The signature should have the 64 byte [R || S] format.
  89. func VerifySignature(pubkey, hash, signature []byte) bool {
  90. if len(signature) != 64 {
  91. return false
  92. }
  93. var r, s btcec.ModNScalar
  94. if r.SetByteSlice(signature[:32]) {
  95. return false // overflow
  96. }
  97. if s.SetByteSlice(signature[32:]) {
  98. return false
  99. }
  100. sig := btc_ecdsa.NewSignature(&r, &s)
  101. key, err := btcec.ParsePubKey(pubkey)
  102. if err != nil {
  103. return false
  104. }
  105. // Reject malleable signatures. libsecp256k1 does this check but btcec doesn't.
  106. if s.IsOverHalfOrder() {
  107. return false
  108. }
  109. return sig.Verify(hash, key)
  110. }
  111. // DecompressPubkey parses a public key in the 33-byte compressed format.
  112. func DecompressPubkey(pubkey []byte) (*ecdsa.PublicKey, error) {
  113. if len(pubkey) != 33 {
  114. return nil, errors.New("invalid compressed public key length")
  115. }
  116. key, err := btcec.ParsePubKey(pubkey)
  117. if err != nil {
  118. return nil, err
  119. }
  120. return key.ToECDSA(), nil
  121. }
  122. // CompressPubkey encodes a public key to the 33-byte compressed format. The
  123. // provided PublicKey must be valid. Namely, the coordinates must not be larger
  124. // than 32 bytes each, they must be less than the field prime, and it must be a
  125. // point on the secp256k1 curve. This is the case for a PublicKey constructed by
  126. // elliptic.Unmarshal (see UnmarshalPubkey), or by ToECDSA and ecdsa.GenerateKey
  127. // when constructing a PrivateKey.
  128. func CompressPubkey(pubkey *ecdsa.PublicKey) []byte {
  129. // NOTE: the coordinates may be validated with
  130. // btcec.ParsePubKey(FromECDSAPub(pubkey))
  131. var x, y btcec.FieldVal
  132. x.SetByteSlice(pubkey.X.Bytes())
  133. y.SetByteSlice(pubkey.Y.Bytes())
  134. return btcec.NewPublicKey(&x, &y).SerializeCompressed()
  135. }
  136. // S256 returns an instance of the secp256k1 curve.
  137. func S256() elliptic.Curve {
  138. return btcec.S256()
  139. }