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.

77 lines
1.7 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 (
  12. PubKeySize = 32
  13. keyType = "sr25519"
  14. )
  15. // PubKeySr25519 implements crypto.PubKey for the Sr25519 signature scheme.
  16. type PubKey []byte
  17. // Address is the SHA256-20 of the raw pubkey bytes.
  18. func (pubKey PubKey) Address() crypto.Address {
  19. return crypto.Address(tmhash.SumTruncated(pubKey[:]))
  20. }
  21. // Bytes returns the byte representation of the PubKey.
  22. func (pubKey PubKey) Bytes() []byte {
  23. return []byte(pubKey)
  24. }
  25. func (pubKey PubKey) VerifyBytes(msg []byte, sig []byte) bool {
  26. // make sure we use the same algorithm to sign
  27. if len(sig) != SignatureSize {
  28. return false
  29. }
  30. var sig64 [SignatureSize]byte
  31. copy(sig64[:], sig)
  32. publicKey := &(schnorrkel.PublicKey{})
  33. var p [PubKeySize]byte
  34. copy(p[:], pubKey)
  35. err := publicKey.Decode(p)
  36. if err != nil {
  37. return false
  38. }
  39. signingContext := schnorrkel.NewSigningContext([]byte{}, msg)
  40. signature := &(schnorrkel.Signature{})
  41. err = signature.Decode(sig64)
  42. if err != nil {
  43. return false
  44. }
  45. return publicKey.Verify(signature, signingContext)
  46. }
  47. func (pubKey PubKey) String() string {
  48. return fmt.Sprintf("PubKeySr25519{%X}", []byte(pubKey))
  49. }
  50. // Equals - checks that two public keys are the same time
  51. // Runs in constant time based on length of the keys.
  52. func (pubKey PubKey) Equals(other crypto.PubKey) bool {
  53. if otherEd, ok := other.(PubKey); ok {
  54. return bytes.Equal(pubKey[:], otherEd[:])
  55. }
  56. return false
  57. }
  58. func (pubKey PubKey) Type() string {
  59. return keyType
  60. }