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.

87 lines
2.2 KiB

9 years ago
10 years ago
  1. package account
  2. import (
  3. "bytes"
  4. "errors"
  5. "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519"
  6. "github.com/tendermint/tendermint/Godeps/_workspace/src/github.com/tendermint/ed25519/extra25519"
  7. "github.com/tendermint/tendermint/binary"
  8. . "github.com/tendermint/tendermint/common"
  9. )
  10. // PubKey is part of Account and Validator.
  11. type PubKey interface {
  12. IsNil() bool
  13. Address() []byte
  14. VerifyBytes(msg []byte, sig Signature) bool
  15. }
  16. // Types of PubKey implementations
  17. const (
  18. PubKeyTypeEd25519 = byte(0x01)
  19. )
  20. // for binary.readReflect
  21. var _ = binary.RegisterInterface(
  22. struct{ PubKey }{},
  23. binary.ConcreteType{PubKeyEd25519{}, PubKeyTypeEd25519},
  24. )
  25. //-------------------------------------
  26. // Implements PubKey
  27. type PubKeyEd25519 [32]byte
  28. func (pubKey PubKeyEd25519) IsNil() bool { return false }
  29. // TODO: Or should this just be BinaryRipemd160(key)? (The difference is the TypeByte.)
  30. func (pubKey PubKeyEd25519) Address() []byte { return binary.BinaryRipemd160(pubKey[:]) }
  31. // TODO: Consider returning a reason for failure, or logging a runtime type mismatch.
  32. func (pubKey PubKeyEd25519) VerifyBytes(msg []byte, sig_ Signature) bool {
  33. sig, ok := sig_.(SignatureEd25519)
  34. if !ok {
  35. return false
  36. }
  37. pubKeyBytes := [32]byte(pubKey)
  38. sigBytes := [64]byte(sig)
  39. return ed25519.Verify(&pubKeyBytes, msg, &sigBytes)
  40. }
  41. // For use with golang/crypto/nacl/box
  42. // If error, returns nil.
  43. func (pubKey PubKeyEd25519) ToCurve25519() *[32]byte {
  44. keyCurve25519, pubKeyBytes := new([32]byte), [32]byte(pubKey)
  45. ok := extra25519.PublicKeyToCurve25519(keyCurve25519, &pubKeyBytes)
  46. if !ok {
  47. return nil
  48. }
  49. return keyCurve25519
  50. }
  51. // redundant: compiler does it for us
  52. func (pubKey PubKeyEd25519) ValidateBasic() error {
  53. if len(pubKey) != ed25519.PublicKeySize {
  54. return errors.New("Invalid PubKeyEd25519 key size")
  55. }
  56. return nil
  57. }
  58. func (pubKey PubKeyEd25519) String() string {
  59. return Fmt("PubKeyEd25519{%X}", pubKey[:])
  60. }
  61. // Must return the full bytes in hex.
  62. // Used for map keying, etc.
  63. func (pubKey PubKeyEd25519) KeyString() string {
  64. return Fmt("%X", pubKey[:])
  65. }
  66. func (pubKey PubKeyEd25519) Equals(other PubKey) bool {
  67. if otherEd, ok := other.(PubKeyEd25519); ok {
  68. return bytes.Equal(pubKey[:], otherEd[:])
  69. } else {
  70. return false
  71. }
  72. }