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.

81 lines
2.0 KiB

  1. package types
  2. import (
  3. "io/ioutil"
  4. "github.com/tendermint/tendermint/crypto"
  5. "github.com/tendermint/tendermint/crypto/ed25519"
  6. tmjson "github.com/tendermint/tendermint/libs/json"
  7. tmos "github.com/tendermint/tendermint/libs/os"
  8. )
  9. //------------------------------------------------------------------------------
  10. // Persistent peer ID
  11. // TODO: encrypt on disk
  12. // NodeKey is the persistent peer key.
  13. // It contains the nodes private key for authentication.
  14. type NodeKey struct {
  15. // Canonical ID - hex-encoded pubkey's address (IDByteLength bytes)
  16. ID NodeID `json:"id"`
  17. // Private key
  18. PrivKey crypto.PrivKey `json:"priv_key"`
  19. }
  20. // PubKey returns the peer's PubKey
  21. func (nodeKey NodeKey) PubKey() crypto.PubKey {
  22. return nodeKey.PrivKey.PubKey()
  23. }
  24. // SaveAs persists the NodeKey to filePath.
  25. func (nodeKey NodeKey) SaveAs(filePath string) error {
  26. jsonBytes, err := tmjson.Marshal(nodeKey)
  27. if err != nil {
  28. return err
  29. }
  30. return ioutil.WriteFile(filePath, jsonBytes, 0600)
  31. }
  32. // LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If
  33. // the file does not exist, it generates and saves a new NodeKey.
  34. func LoadOrGenNodeKey(filePath string) (NodeKey, error) {
  35. if tmos.FileExists(filePath) {
  36. nodeKey, err := LoadNodeKey(filePath)
  37. if err != nil {
  38. return NodeKey{}, err
  39. }
  40. return nodeKey, nil
  41. }
  42. nodeKey := GenNodeKey()
  43. if err := nodeKey.SaveAs(filePath); err != nil {
  44. return NodeKey{}, err
  45. }
  46. return nodeKey, nil
  47. }
  48. // GenNodeKey generates a new node key.
  49. func GenNodeKey() NodeKey {
  50. privKey := ed25519.GenPrivKey()
  51. return NodeKey{
  52. ID: NodeIDFromPubKey(privKey.PubKey()),
  53. PrivKey: privKey,
  54. }
  55. }
  56. // LoadNodeKey loads NodeKey located in filePath.
  57. func LoadNodeKey(filePath string) (NodeKey, error) {
  58. jsonBytes, err := ioutil.ReadFile(filePath)
  59. if err != nil {
  60. return NodeKey{}, err
  61. }
  62. nodeKey := NodeKey{}
  63. err = tmjson.Unmarshal(jsonBytes, &nodeKey)
  64. if err != nil {
  65. return NodeKey{}, err
  66. }
  67. nodeKey.ID = NodeIDFromPubKey(nodeKey.PubKey())
  68. return nodeKey, nil
  69. }