secp256.go 5.3 KB

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