github.com/snowblossomcoin/go-ethereum@v1.9.25/crypto/secp256k1/secp256.go (about)

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