You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.6 KiB

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