crypto, crypto/secp256k1: add CompressPubkey (#15626)
This adds the inverse to DecompressPubkey and improves a few minor details in crypto/secp256k1.
This commit is contained in:
@ -115,7 +115,7 @@ func RecoverPubkey(msg []byte, sig []byte) ([]byte, error) {
|
||||
sigdata = (*C.uchar)(unsafe.Pointer(&sig[0]))
|
||||
msgdata = (*C.uchar)(unsafe.Pointer(&msg[0]))
|
||||
)
|
||||
if C.secp256k1_ecdsa_recover_pubkey(context, (*C.uchar)(unsafe.Pointer(&pubkey[0])), sigdata, msgdata) == 0 {
|
||||
if C.secp256k1_ext_ecdsa_recover(context, (*C.uchar)(unsafe.Pointer(&pubkey[0])), sigdata, msgdata) == 0 {
|
||||
return nil, ErrRecoverFailed
|
||||
}
|
||||
return pubkey, nil
|
||||
@ -130,22 +130,42 @@ func VerifySignature(pubkey, msg, signature []byte) bool {
|
||||
sigdata := (*C.uchar)(unsafe.Pointer(&signature[0]))
|
||||
msgdata := (*C.uchar)(unsafe.Pointer(&msg[0]))
|
||||
keydata := (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
return C.secp256k1_ecdsa_verify_enc(context, sigdata, msgdata, keydata, C.size_t(len(pubkey))) != 0
|
||||
return C.secp256k1_ext_ecdsa_verify(context, sigdata, msgdata, keydata, C.size_t(len(pubkey))) != 0
|
||||
}
|
||||
|
||||
// DecompressPubkey parses a public key in the 33-byte compressed format.
|
||||
// It returns non-nil coordinates if the public key is valid.
|
||||
func DecompressPubkey(pubkey []byte) (X, Y *big.Int) {
|
||||
func DecompressPubkey(pubkey []byte) (x, y *big.Int) {
|
||||
if len(pubkey) != 33 {
|
||||
return nil, nil
|
||||
}
|
||||
buf := make([]byte, 65)
|
||||
bufdata := (*C.uchar)(unsafe.Pointer(&buf[0]))
|
||||
pubkeydata := (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
if C.secp256k1_decompress_pubkey(context, bufdata, pubkeydata) == 0 {
|
||||
var (
|
||||
pubkeydata = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
pubkeylen = C.size_t(len(pubkey))
|
||||
out = make([]byte, 65)
|
||||
outdata = (*C.uchar)(unsafe.Pointer(&out[0]))
|
||||
outlen = C.size_t(len(out))
|
||||
)
|
||||
if C.secp256k1_ext_reencode_pubkey(context, outdata, outlen, pubkeydata, pubkeylen) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return new(big.Int).SetBytes(buf[1:33]), new(big.Int).SetBytes(buf[33:])
|
||||
return new(big.Int).SetBytes(out[1:33]), new(big.Int).SetBytes(out[33:])
|
||||
}
|
||||
|
||||
// CompressPubkey encodes a public key to 33-byte compressed format.
|
||||
func CompressPubkey(x, y *big.Int) []byte {
|
||||
var (
|
||||
pubkey = S256().Marshal(x, y)
|
||||
pubkeydata = (*C.uchar)(unsafe.Pointer(&pubkey[0]))
|
||||
pubkeylen = C.size_t(len(pubkey))
|
||||
out = make([]byte, 33)
|
||||
outdata = (*C.uchar)(unsafe.Pointer(&out[0]))
|
||||
outlen = C.size_t(len(out))
|
||||
)
|
||||
if C.secp256k1_ext_reencode_pubkey(context, outdata, outlen, pubkeydata, pubkeylen) == 0 {
|
||||
panic("libsecp256k1 error")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func checkSignature(sig []byte) error {
|
||||
|
Reference in New Issue
Block a user