github.com/devwanda/aphelion-staking@v0.33.9/crypto/sr25519/pubkey.go (about)

     1  package sr25519
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  
     7  	"github.com/devwanda/aphelion-staking/crypto"
     8  	"github.com/devwanda/aphelion-staking/crypto/tmhash"
     9  
    10  	schnorrkel "github.com/devwanda/go-schnorrkel"
    11  )
    12  
    13  var _ crypto.PubKey = PubKeySr25519{}
    14  
    15  // PubKeySr25519Size is the number of bytes in an Sr25519 public key.
    16  const PubKeySr25519Size = 32
    17  
    18  // PubKeySr25519 implements crypto.PubKey for the Sr25519 signature scheme.
    19  type PubKeySr25519 [PubKeySr25519Size]byte
    20  
    21  // Address is the SHA256-20 of the raw pubkey bytes.
    22  func (pubKey PubKeySr25519) Address() crypto.Address {
    23  	return crypto.Address(tmhash.SumTruncated(pubKey[:]))
    24  }
    25  
    26  // Bytes marshals the PubKey using amino encoding.
    27  func (pubKey PubKeySr25519) Bytes() []byte {
    28  	bz, err := cdc.MarshalBinaryBare(pubKey)
    29  	if err != nil {
    30  		panic(err)
    31  	}
    32  	return bz
    33  }
    34  
    35  func (pubKey PubKeySr25519) VerifyBytes(msg []byte, sig []byte) bool {
    36  	// make sure we use the same algorithm to sign
    37  	if len(sig) != SignatureSize {
    38  		return false
    39  	}
    40  	var sig64 [SignatureSize]byte
    41  	copy(sig64[:], sig)
    42  
    43  	publicKey := &(schnorrkel.PublicKey{})
    44  	err := publicKey.Decode(pubKey)
    45  	if err != nil {
    46  		return false
    47  	}
    48  
    49  	signingContext := schnorrkel.NewSigningContext([]byte{}, msg)
    50  
    51  	signature := &(schnorrkel.Signature{})
    52  	err = signature.Decode(sig64)
    53  	if err != nil {
    54  		return false
    55  	}
    56  
    57  	return publicKey.Verify(signature, signingContext)
    58  }
    59  
    60  func (pubKey PubKeySr25519) String() string {
    61  	return fmt.Sprintf("PubKeySr25519{%X}", pubKey[:])
    62  }
    63  
    64  // Equals - checks that two public keys are the same time
    65  // Runs in constant time based on length of the keys.
    66  func (pubKey PubKeySr25519) Equals(other crypto.PubKey) bool {
    67  	if otherEd, ok := other.(PubKeySr25519); ok {
    68  		return bytes.Equal(pubKey[:], otherEd[:])
    69  	}
    70  	return false
    71  }