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.

75 lines
2.0 KiB

  1. package encoding
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/tendermint/tendermint/crypto"
  6. "github.com/tendermint/tendermint/crypto/ed25519"
  7. pc "github.com/tendermint/tendermint/proto/crypto/keys"
  8. )
  9. // PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey
  10. func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) {
  11. var kp pc.PublicKey
  12. switch k := k.(type) {
  13. case ed25519.PubKey:
  14. kp = pc.PublicKey{
  15. Sum: &pc.PublicKey_Ed25519{
  16. Ed25519: k[:],
  17. },
  18. }
  19. default:
  20. return kp, fmt.Errorf("toproto: key type %v is not supported", k)
  21. }
  22. return kp, nil
  23. }
  24. // PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey
  25. func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) {
  26. switch k := k.Sum.(type) {
  27. case *pc.PublicKey_Ed25519:
  28. if len(k.Ed25519) != ed25519.PubKeySize {
  29. return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
  30. len(k.Ed25519), ed25519.PubKeySize)
  31. }
  32. var pk ed25519.PubKey
  33. copy(pk[:], k.Ed25519)
  34. return pk, nil
  35. default:
  36. return nil, fmt.Errorf("fromproto: key type %v is not supported", k)
  37. }
  38. }
  39. // PrivKeyToProto takes crypto.PrivKey and transforms it to a protobuf PrivKey
  40. func PrivKeyToProto(k crypto.PrivKey) (pc.PrivateKey, error) {
  41. var kp pc.PrivateKey
  42. switch k := k.(type) {
  43. case ed25519.PrivKey:
  44. kp = pc.PrivateKey{
  45. Sum: &pc.PrivateKey_Ed25519{
  46. Ed25519: k[:],
  47. },
  48. }
  49. default:
  50. return kp, errors.New("toproto: key type is not supported")
  51. }
  52. return kp, nil
  53. }
  54. // PrivKeyFromProto takes a protobuf PrivateKey and transforms it to a crypto.PrivKey
  55. func PrivKeyFromProto(k pc.PrivateKey) (crypto.PrivKey, error) {
  56. switch k := k.Sum.(type) {
  57. case *pc.PrivateKey_Ed25519:
  58. if len(k.Ed25519) != ed25519.PubKeySize {
  59. return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
  60. len(k.Ed25519), ed25519.PubKeySize)
  61. }
  62. var pk ed25519.PrivKey
  63. copy(pk[:], k.Ed25519)
  64. return pk, nil
  65. default:
  66. return nil, errors.New("fromproto: key type not supported")
  67. }
  68. }