secp256.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. // Copyright 2015 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. // Package secp256k1 wraps the bitcoin secp256k1 C library.
  17. package secp256k1
  18. /*
  19. #cgo CFLAGS: -I./libsecp256k1
  20. #cgo CFLAGS: -I./libsecp256k1/src/
  21. #define USE_NUM_NONE
  22. #define USE_FIELD_10X26
  23. #define USE_FIELD_INV_BUILTIN
  24. #define USE_SCALAR_8X32
  25. #define USE_SCALAR_INV_BUILTIN
  26. #define NDEBUG
  27. #include "./libsecp256k1/src/secp256k1.c"
  28. #include "./libsecp256k1/src/modules/recovery/main_impl.h"
  29. #include "ext.h"
  30. typedef void (*callbackFunc) (const char* msg, void* data);
  31. extern void secp256k1GoPanicIllegal(const char* msg, void* data);
  32. extern void secp256k1GoPanicError(const char* msg, void* data);
  33. */
  34. import "C"
  35. import (
  36. "errors"
  37. "math/big"
  38. "unsafe"
  39. )
  40. var context *C.secp256k1_context
  41. func init() {
  42. // around 20 ms on a modern CPU.
  43. context = C.secp256k1_context_create_sign_verify()
  44. C.secp256k1_context_set_illegal_callback(context, C.callbackFunc(C.secp256k1GoPanicIllegal), nil)
  45. C.secp256k1_context_set_error_callback(context, C.callbackFunc(C.secp256k1GoPanicError), nil)
  46. }
  47. var (
  48. ErrInvalidMsgLen = errors.New("invalid message length, need 32 bytes")
  49. ErrInvalidSignatureLen = errors.New("invalid signature length")
  50. ErrInvalidRecoveryID = errors.New("invalid signature recovery id")
  51. ErrInvalidKey = errors.New("invalid private key")
  52. ErrSignFailed = errors.New("signing failed")
  53. ErrRecoverFailed = errors.New("recovery failed")
  54. )
  55. // Sign creates a recoverable ECDSA signature.
  56. // The produced signature is in the 65-byte [R || S || V] format where V is 0 or 1.
  57. //
  58. // The caller is responsible for ensuring that msg cannot be chosen
  59. // directly by an attacker. It is usually preferable to use a cryptographic
  60. // hash function on any input before handing it to this function.
  61. func Sign(msg []byte, seckey []byte) ([]byte, error) {
  62. if len(msg) != 32 {
  63. return nil, ErrInvalidMsgLen
  64. }
  65. if len(seckey) != 32 {
  66. return nil, ErrInvalidKey
  67. }
  68. seckeydata := (*C.uchar)(unsafe.Pointer(&seckey[0]))
  69. if C.secp256k1_ec_seckey_verify(context, seckeydata) != 1 {
  70. return nil, ErrInvalidKey
  71. }
  72. var (
  73. msgdata = (*C.uchar)(unsafe.Pointer(&msg[0]))
  74. noncefunc = C.secp256k1_nonce_function_rfc6979
  75. sigstruct C.secp256k1_ecdsa_recoverable_signature
  76. )
  77. if C.secp256k1_ecdsa_sign_recoverable(context, &sigstruct, msgdata, seckeydata, noncefunc, nil) == 0 {
  78. return nil, ErrSignFailed
  79. }
  80. var (
  81. sig = make([]byte, 65)
  82. sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
  83. recid C.int
  84. )
  85. C.secp256k1_ecdsa_recoverable_signature_serialize_compact(context, sigdata, &recid, &sigstruct)
  86. sig[64] = byte(recid) // add back recid to get 65 bytes sig
  87. return sig, nil
  88. }
  89. // RecoverPubkey returns the the public key of the signer.
  90. // msg must be the 32-byte hash of the message to be signed.
  91. // sig must be a 65-byte compact ECDSA signature containing the
  92. // recovery id as the last element.
  93. func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
  94. if len(msg) != 32 {
  95. return nil, ErrInvalidMsgLen
  96. }
  97. if err := checkSignature(sig); err != nil {
  98. return nil, err
  99. }
  100. var (
  101. pubkey = make([]byte, 65)
  102. sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
  103. msgdata = (*C.uchar)(unsafe.Pointer(&msg[0]))
  104. )
  105. if C.secp256k1_ecdsa_recover_pubkey(context, (*C.uchar)(unsafe.Pointer(&pubkey[0])), sigdata, msgdata) == 0 {
  106. return nil, ErrRecoverFailed
  107. }
  108. return pubkey, nil
  109. }
  110. func checkSignature(sig []byte) error {
  111. if len(sig) != 65 {
  112. return ErrInvalidSignatureLen
  113. }
  114. if sig[64] >= 4 {
  115. return ErrInvalidRecoveryID
  116. }
  117. return nil
  118. }
  119. // reads num into buf as big-endian bytes.
  120. func readBits(buf []byte, num *big.Int) {
  121. const wordLen = int(unsafe.Sizeof(big.Word(0)))
  122. i := len(buf)
  123. for _, d := range num.Bits() {
  124. for j := 0; j < wordLen && i > 0; j++ {
  125. i--
  126. buf[i] = byte(d)
  127. d >>= 8
  128. }
  129. }
  130. }