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.

89 lines
2.3 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 []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 := new([32]byte)
  38. copy(pubKeyBytes[:], pubKey)
  39. sigBytes := new([64]byte)
  40. copy(sigBytes[:], sig)
  41. return ed25519.Verify(pubKeyBytes, msg, sigBytes)
  42. }
  43. // For use with golang/crypto/nacl/box
  44. // If error, returns nil.
  45. func (pubKey PubKeyEd25519) ToCurve25519() *[32]byte {
  46. keyEd25519, keyCurve25519 := new([32]byte), new([32]byte)
  47. copy(keyEd25519[:], pubKey)
  48. ok := extra25519.PublicKeyToCurve25519(keyCurve25519, keyEd25519)
  49. if !ok {
  50. return nil
  51. }
  52. return keyCurve25519
  53. }
  54. func (pubKey PubKeyEd25519) ValidateBasic() error {
  55. if len(pubKey) != ed25519.PublicKeySize {
  56. return errors.New("Invalid PubKeyEd25519 key size")
  57. }
  58. return nil
  59. }
  60. func (pubKey PubKeyEd25519) String() string {
  61. return Fmt("PubKeyEd25519{%X}", []byte(pubKey))
  62. }
  63. // Must return the full bytes in hex.
  64. // Used for map keying, etc.
  65. func (pubKey PubKeyEd25519) KeyString() string {
  66. return Fmt("%X", []byte(pubKey))
  67. }
  68. func (pubKey PubKeyEd25519) Equals(other PubKey) bool {
  69. if _, ok := other.(PubKeyEd25519); ok {
  70. return bytes.Equal(pubKey, other.(PubKeyEd25519))
  71. } else {
  72. return false
  73. }
  74. }