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.

85 lines
2.0 KiB

  1. package p2p
  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. err = ioutil.WriteFile(filePath, jsonBytes, 0600)
  31. if err != nil {
  32. return err
  33. }
  34. return nil
  35. }
  36. // LoadOrGenNodeKey attempts to load the NodeKey from the given filePath. If
  37. // the file does not exist, it generates and saves a new NodeKey.
  38. func LoadOrGenNodeKey(filePath string) (NodeKey, error) {
  39. if tmos.FileExists(filePath) {
  40. nodeKey, err := LoadNodeKey(filePath)
  41. if err != nil {
  42. return NodeKey{}, err
  43. }
  44. return nodeKey, nil
  45. }
  46. nodeKey := GenNodeKey()
  47. if err := nodeKey.SaveAs(filePath); err != nil {
  48. return NodeKey{}, err
  49. }
  50. return nodeKey, nil
  51. }
  52. // GenNodeKey generates a new node key.
  53. func GenNodeKey() NodeKey {
  54. privKey := ed25519.GenPrivKey()
  55. return NodeKey{
  56. ID: NodeIDFromPubKey(privKey.PubKey()),
  57. PrivKey: privKey,
  58. }
  59. }
  60. // LoadNodeKey loads NodeKey located in filePath.
  61. func LoadNodeKey(filePath string) (NodeKey, error) {
  62. jsonBytes, err := ioutil.ReadFile(filePath)
  63. if err != nil {
  64. return NodeKey{}, err
  65. }
  66. nodeKey := NodeKey{}
  67. err = tmjson.Unmarshal(jsonBytes, &nodeKey)
  68. if err != nil {
  69. return NodeKey{}, err
  70. }
  71. nodeKey.ID = NodeIDFromPubKey(nodeKey.PubKey())
  72. return nodeKey, nil
  73. }