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.

47 lines
1.3 KiB

  1. package encoding
  2. import (
  3. "fmt"
  4. "github.com/tendermint/tendermint/crypto"
  5. "github.com/tendermint/tendermint/crypto/ed25519"
  6. "github.com/tendermint/tendermint/libs/json"
  7. pc "github.com/tendermint/tendermint/proto/tendermint/crypto"
  8. )
  9. func init() {
  10. json.RegisterType((*pc.PublicKey)(nil), "tendermint.crypto.PublicKey")
  11. json.RegisterType((*pc.PublicKey_Ed25519)(nil), "tendermint.crypto.PublicKey_Ed25519")
  12. }
  13. // PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey
  14. func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) {
  15. var kp pc.PublicKey
  16. switch k := k.(type) {
  17. case ed25519.PubKey:
  18. kp = pc.PublicKey{
  19. Sum: &pc.PublicKey_Ed25519{
  20. Ed25519: k,
  21. },
  22. }
  23. default:
  24. return kp, fmt.Errorf("toproto: key type %v is not supported", k)
  25. }
  26. return kp, nil
  27. }
  28. // PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey
  29. func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) {
  30. switch k := k.Sum.(type) {
  31. case *pc.PublicKey_Ed25519:
  32. if len(k.Ed25519) != ed25519.PubKeySize {
  33. return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
  34. len(k.Ed25519), ed25519.PubKeySize)
  35. }
  36. pk := make(ed25519.PubKey, ed25519.PubKeySize)
  37. copy(pk, k.Ed25519)
  38. return pk, nil
  39. default:
  40. return nil, fmt.Errorf("fromproto: key type %v is not supported", k)
  41. }
  42. }