github.com/neatio-net/neatio@v1.7.3-0.20231114194659-f4d7a2226baa/utilities/crypto/signature_cgo.go (about)

     1  //go:build !nacl && !js && !nocgo
     2  // +build !nacl,!js,!nocgo
     3  
     4  package crypto
     5  
     6  import (
     7  	"crypto/ecdsa"
     8  	"crypto/elliptic"
     9  	"fmt"
    10  
    11  	"github.com/neatio-net/neatio/utilities/common/math"
    12  	"github.com/neatio-net/neatio/utilities/crypto/secp256k1"
    13  )
    14  
    15  func Ecrecover(hash, sig []byte) ([]byte, error) {
    16  	return secp256k1.RecoverPubkey(hash, sig)
    17  }
    18  
    19  func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
    20  	s, err := Ecrecover(hash, sig)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	x, y := elliptic.Unmarshal(S256(), s)
    26  	return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
    27  }
    28  
    29  func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
    30  	if len(hash) != 32 {
    31  		return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
    32  	}
    33  	seckey := math.PaddedBigBytes(prv.D, prv.Params().BitSize/8)
    34  	defer zeroBytes(seckey)
    35  	return secp256k1.Sign(hash, seckey)
    36  }
    37  
    38  func VerifySignature(pubkey, hash, signature []byte) bool {
    39  	return secp256k1.VerifySignature(pubkey, hash, signature)
    40  }
    41  
    42  func DecompressPubkey(pubkey []byte) (*ecdsa.PublicKey, error) {
    43  	x, y := secp256k1.DecompressPubkey(pubkey)
    44  	if x == nil {
    45  		return nil, fmt.Errorf("invalid public key")
    46  	}
    47  	return &ecdsa.PublicKey{X: x, Y: y, Curve: S256()}, nil
    48  }
    49  
    50  func CompressPubkey(pubkey *ecdsa.PublicKey) []byte {
    51  	return secp256k1.CompressPubkey(pubkey.X, pubkey.Y)
    52  }
    53  
    54  func S256() elliptic.Curve {
    55  	return secp256k1.S256()
    56  }