secp256.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // Copyright 2015 Jeffrey Wilcke, Felix Lange, Gustav Simonsson. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. // Package secp256k1 wraps the bitcoin secp256k1 C library.
  5. package secp256k1
  6. /*
  7. #cgo CFLAGS: -I./libsecp256k1
  8. #cgo CFLAGS: -I./libsecp256k1/src/
  9. #ifdef __SIZEOF_INT128__
  10. # define HAVE___INT128
  11. # define USE_FIELD_5X52
  12. # define USE_SCALAR_4X64
  13. #else
  14. # define USE_FIELD_10X26
  15. # define USE_SCALAR_8X32
  16. #endif
  17. #define USE_ENDOMORPHISM
  18. #define USE_NUM_NONE
  19. #define USE_FIELD_INV_BUILTIN
  20. #define USE_SCALAR_INV_BUILTIN
  21. #define NDEBUG
  22. #include "./libsecp256k1/src/secp256k1.c"
  23. #include "./libsecp256k1/src/modules/recovery/main_impl.h"
  24. #include "ext.h"
  25. typedef void (*callbackFunc) (const char* msg, void* data);
  26. extern void secp256k1GoPanicIllegal(const char* msg, void* data);
  27. extern void secp256k1GoPanicError(const char* msg, void* data);
  28. */
  29. import "C"
  30. import (
  31. "errors"
  32. "math/big"
  33. "unsafe"
  34. )
  35. var context *C.secp256k1_context
  36. func init() {
  37. // around 20 ms on a modern CPU.
  38. context = C.secp256k1_context_create_sign_verify()
  39. C.secp256k1_context_set_illegal_callback(context, C.callbackFunc(C.secp256k1GoPanicIllegal), nil)
  40. C.secp256k1_context_set_error_callback(context, C.callbackFunc(C.secp256k1GoPanicError), nil)
  41. }
  42. var (
  43. ErrInvalidMsgLen = errors.New("invalid message length, need 32 bytes")
  44. ErrInvalidSignatureLen = errors.New("invalid signature length")
  45. ErrInvalidRecoveryID = errors.New("invalid signature recovery id")
  46. ErrInvalidKey = errors.New("invalid private key")
  47. ErrInvalidPubkey = errors.New("invalid public key")
  48. ErrSignFailed = errors.New("signing failed")
  49. ErrRecoverFailed = errors.New("recovery failed")
  50. )
  51. // Sign creates a recoverable ECDSA signature.
  52. // The produced signature is in the 65-byte [R || S || V] format where V is 0 or 1.
  53. //
  54. // The caller is responsible for ensuring that msg cannot be chosen
  55. // directly by an attacker. It is usually preferable to use a cryptographic
  56. // hash function on any input before handing it to this function.
  57. func Sign(msg []byte, seckey []byte) ([]byte, error) {
  58. if len(msg) != 32 {
  59. return nil, ErrInvalidMsgLen
  60. }
  61. if len(seckey) != 32 {
  62. return nil, ErrInvalidKey
  63. }
  64. seckeydata := (*C.uchar)(unsafe.Pointer(&seckey[0]))
  65. if C.secp256k1_ec_seckey_verify(context, seckeydata) != 1 {
  66. return nil, ErrInvalidKey
  67. }
  68. var (
  69. msgdata = (*C.uchar)(unsafe.Pointer(&msg[0]))
  70. noncefunc = C.secp256k1_nonce_function_rfc6979
  71. sigstruct C.secp256k1_ecdsa_recoverable_signature
  72. )
  73. if C.secp256k1_ecdsa_sign_recoverable(context, &sigstruct, msgdata, seckeydata, noncefunc, nil) == 0 {
  74. return nil, ErrSignFailed
  75. }
  76. var (
  77. sig = make([]byte, 65)
  78. sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
  79. recid C.int
  80. )
  81. C.secp256k1_ecdsa_recoverable_signature_serialize_compact(context, sigdata, &recid, &sigstruct)
  82. sig[64] = byte(recid) // add back recid to get 65 bytes sig
  83. return sig, nil
  84. }
  85. // RecoverPubkey returns the public key of the signer.
  86. // msg must be the 32-byte hash of the message to be signed.
  87. // sig must be a 65-byte compact ECDSA signature containing the
  88. // recovery id as the last element.
  89. func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
  90. if len(msg) != 32 {
  91. return nil, ErrInvalidMsgLen
  92. }
  93. if err := checkSignature(sig); err != nil {
  94. return nil, err
  95. }
  96. var (
  97. pubkey = make([]byte, 65)
  98. sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
  99. msgdata = (*C.uchar)(unsafe.Pointer(&msg[0]))
  100. )
  101. if C.secp256k1_ext_ecdsa_recover(context, (*C.uchar)(unsafe.Pointer(&pubkey[0])), sigdata, msgdata) == 0 {
  102. return nil, ErrRecoverFailed
  103. }
  104. return pubkey, nil
  105. }
  106. // VerifySignature checks that the given pubkey created signature over message.
  107. // The signature should be in [R || S] format.
  108. func VerifySignature(pubkey, msg, signature []byte) bool {
  109. if len(msg) != 32 || len(signature) != 64 || len(pubkey) == 0 {
  110. return false
  111. }
  112. sigdata := (*C.uchar)(unsafe.Pointer(&signature[0]))
  113. msgdata := (*C.uchar)(unsafe.Pointer(&msg[0]))
  114. keydata := (*C.uchar)(unsafe.Pointer(&pubkey[0]))
  115. return C.secp256k1_ext_ecdsa_verify(context, sigdata, msgdata, keydata, C.size_t(len(pubkey))) != 0
  116. }
  117. // DecompressPubkey parses a public key in the 33-byte compressed format.
  118. // It returns non-nil coordinates if the public key is valid.
  119. func DecompressPubkey(pubkey []byte) (x, y *big.Int) {
  120. if len(pubkey) != 33 {
  121. return nil, nil
  122. }
  123. var (
  124. pubkeydata = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
  125. pubkeylen = C.size_t(len(pubkey))
  126. out = make([]byte, 65)
  127. outdata = (*C.uchar)(unsafe.Pointer(&out[0]))
  128. outlen = C.size_t(len(out))
  129. )
  130. if C.secp256k1_ext_reencode_pubkey(context, outdata, outlen, pubkeydata, pubkeylen) == 0 {
  131. return nil, nil
  132. }
  133. return new(big.Int).SetBytes(out[1:33]), new(big.Int).SetBytes(out[33:])
  134. }
  135. // CompressPubkey encodes a public key to 33-byte compressed format.
  136. func CompressPubkey(x, y *big.Int) []byte {
  137. var (
  138. pubkey = S256().Marshal(x, y)
  139. pubkeydata = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
  140. pubkeylen = C.size_t(len(pubkey))
  141. out = make([]byte, 33)
  142. outdata = (*C.uchar)(unsafe.Pointer(&out[0]))
  143. outlen = C.size_t(len(out))
  144. )
  145. if C.secp256k1_ext_reencode_pubkey(context, outdata, outlen, pubkeydata, pubkeylen) == 0 {
  146. panic("libsecp256k1 error")
  147. }
  148. return out
  149. }
  150. func checkSignature(sig []byte) error {
  151. if len(sig) != 65 {
  152. return ErrInvalidSignatureLen
  153. }
  154. if sig[64] >= 4 {
  155. return ErrInvalidRecoveryID
  156. }
  157. return nil
  158. }