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.

63 lines
1.9 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/crypto/secp256k1"
  7. "github.com/tendermint/tendermint/libs/json"
  8. pc "github.com/tendermint/tendermint/proto/tendermint/crypto"
  9. )
  10. func init() {
  11. json.RegisterType((*pc.PublicKey)(nil), "tendermint.crypto.PublicKey")
  12. json.RegisterType((*pc.PublicKey_Ed25519)(nil), "tendermint.crypto.PublicKey_Ed25519")
  13. json.RegisterType((*pc.PublicKey_Secp256K1)(nil), "tendermint.crypto.PublicKey_Secp256K1")
  14. }
  15. // PubKeyToProto takes crypto.PubKey and transforms it to a protobuf Pubkey
  16. func PubKeyToProto(k crypto.PubKey) (pc.PublicKey, error) {
  17. var kp pc.PublicKey
  18. switch k := k.(type) {
  19. case ed25519.PubKey:
  20. kp = pc.PublicKey{
  21. Sum: &pc.PublicKey_Ed25519{
  22. Ed25519: k,
  23. },
  24. }
  25. case secp256k1.PubKey:
  26. kp = pc.PublicKey{
  27. Sum: &pc.PublicKey_Secp256K1{
  28. Secp256K1: k,
  29. },
  30. }
  31. default:
  32. return kp, fmt.Errorf("toproto: key type %v is not supported", k)
  33. }
  34. return kp, nil
  35. }
  36. // PubKeyFromProto takes a protobuf Pubkey and transforms it to a crypto.Pubkey
  37. func PubKeyFromProto(k pc.PublicKey) (crypto.PubKey, error) {
  38. switch k := k.Sum.(type) {
  39. case *pc.PublicKey_Ed25519:
  40. if len(k.Ed25519) != ed25519.PubKeySize {
  41. return nil, fmt.Errorf("invalid size for PubKeyEd25519. Got %d, expected %d",
  42. len(k.Ed25519), ed25519.PubKeySize)
  43. }
  44. pk := make(ed25519.PubKey, ed25519.PubKeySize)
  45. copy(pk, k.Ed25519)
  46. return pk, nil
  47. case *pc.PublicKey_Secp256K1:
  48. if len(k.Secp256K1) != secp256k1.PubKeySize {
  49. return nil, fmt.Errorf("invalid size for PubKeySecp256k1. Got %d, expected %d",
  50. len(k.Secp256K1), secp256k1.PubKeySize)
  51. }
  52. pk := make(secp256k1.PubKey, secp256k1.PubKeySize)
  53. copy(pk, k.Secp256K1)
  54. return pk, nil
  55. default:
  56. return nil, fmt.Errorf("fromproto: key type %v is not supported", k)
  57. }
  58. }