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.

91 lines
2.3 KiB

9 years ago
9 years ago
9 years ago
9 years ago
  1. package crypto
  2. import (
  3. "bytes"
  4. "github.com/tendermint/ed25519"
  5. "github.com/tendermint/ed25519/extra25519"
  6. . "github.com/tendermint/go-common"
  7. "github.com/tendermint/go-wire"
  8. "golang.org/x/crypto/ripemd160"
  9. )
  10. // PubKey is part of Account and Validator.
  11. type PubKey interface {
  12. Address() []byte
  13. KeyString() string
  14. VerifyBytes(msg []byte, sig Signature) bool
  15. }
  16. // Types of PubKey implementations
  17. const (
  18. PubKeyTypeEd25519 = byte(0x01)
  19. )
  20. // for wire.readReflect
  21. var _ = wire.RegisterInterface(
  22. struct{ PubKey }{},
  23. wire.ConcreteType{PubKeyEd25519{}, PubKeyTypeEd25519},
  24. )
  25. //-------------------------------------
  26. // Implements PubKey
  27. type PubKeyEd25519 [32]byte
  28. // TODO: Slicing the array gives us length prefixing but loses the type byte.
  29. // Revisit if we add more pubkey types.
  30. // For now, we artificially append the type byte in front to give us backwards
  31. // compatibility for when the pubkey wasn't fixed length array
  32. func (pubKey PubKeyEd25519) Address() []byte {
  33. w, n, err := new(bytes.Buffer), new(int), new(error)
  34. wire.WriteBinary(pubKey[:], w, n, err)
  35. if *err != nil {
  36. PanicCrisis(*err)
  37. }
  38. // append type byte
  39. encodedPubkey := append([]byte{1}, w.Bytes()...)
  40. hasher := ripemd160.New()
  41. hasher.Write(encodedPubkey) // does not error
  42. return hasher.Sum(nil)
  43. }
  44. // TODO: Consider returning a reason for failure, or logging a runtime type mismatch.
  45. func (pubKey PubKeyEd25519) VerifyBytes(msg []byte, sig_ Signature) bool {
  46. sig, ok := sig_.(SignatureEd25519)
  47. if !ok {
  48. return false
  49. }
  50. pubKeyBytes := [32]byte(pubKey)
  51. sigBytes := [64]byte(sig)
  52. return ed25519.Verify(&pubKeyBytes, msg, &sigBytes)
  53. }
  54. // For use with golang/crypto/nacl/box
  55. // If error, returns nil.
  56. func (pubKey PubKeyEd25519) ToCurve25519() *[32]byte {
  57. keyCurve25519, pubKeyBytes := new([32]byte), [32]byte(pubKey)
  58. ok := extra25519.PublicKeyToCurve25519(keyCurve25519, &pubKeyBytes)
  59. if !ok {
  60. return nil
  61. }
  62. return keyCurve25519
  63. }
  64. func (pubKey PubKeyEd25519) String() string {
  65. return Fmt("PubKeyEd25519{%X}", pubKey[:])
  66. }
  67. // Must return the full bytes in hex.
  68. // Used for map keying, etc.
  69. func (pubKey PubKeyEd25519) KeyString() string {
  70. return Fmt("%X", pubKey[:])
  71. }
  72. func (pubKey PubKeyEd25519) Equals(other PubKey) bool {
  73. if otherEd, ok := other.(PubKeyEd25519); ok {
  74. return bytes.Equal(pubKey[:], otherEd[:])
  75. } else {
  76. return false
  77. }
  78. }