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.

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