Polkadot.js Golang服务端验签

点击数:29

package service

import (
	"crypto/ed25519"

	sr25519 "github.com/ChainSafe/go-schnorrkel"
	"github.com/subscan-explorer/subscan-common/core/log"
)

var SigningContext = []byte("substrate")

func (s *Service) verifyWeb3(pub, nounce, sig, encryption string) bool {
	switch encryption {
	case "ed25519":
		return ed25519.Verify([]byte(pub), []byte(nounce), []byte(sig))
	case "sr25519":
		return verifiySigsSr25519(sig, pub, nounce)
	}
	return false
}

//only for pokadot web3.js
func verifiySigsSr25519(sigs, pubkey, message string) bool {
	var err error
	pub, err := sr25519.NewPublicKeyFromHex(pubkey)
	if err != nil {
		log.Errorf("NewPublicKeyFromHex error %v", err)
		return false
	}
	sig, err := sr25519.NewSignatureFromHex(sigs)
	if err != nil {
		log.Errorf("NewSignatureFromHex error %v", err)
		return false
	}
	msgStr := "<Bytes>" + message + "</Bytes>"
	msg := []byte(msgStr)
	transcript := sr25519.NewSigningContext(SigningContext, msg)
	ok, err := pub.Verify(sig, transcript)
	if err != nil {
		log.Errorf("verifiySigsSr25519 Verify error %v", err)
		return false
	}
	if !ok {
		log.Error("failed to verify signature")
		return false
	}
	return true
}
Share
%d 博主赞过: