nodekey.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package guardiand
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. p2pcrypto "github.com/libp2p/go-libp2p-core/crypto"
  7. "go.uber.org/zap"
  8. )
  9. func getOrCreateNodeKey(logger *zap.Logger, path string) (p2pcrypto.PrivKey, error) {
  10. b, err := ioutil.ReadFile(path)
  11. if err != nil {
  12. if os.IsNotExist(err) {
  13. logger.Info("No node key found, generating a new one...", zap.String("path", path))
  14. priv, _, err := p2pcrypto.GenerateKeyPair(p2pcrypto.Ed25519, -1)
  15. if err != nil {
  16. panic(err)
  17. }
  18. s, err := p2pcrypto.MarshalPrivateKey(priv)
  19. if err != nil {
  20. panic(err)
  21. }
  22. err = ioutil.WriteFile(path, s, 0600)
  23. if err != nil {
  24. return nil, fmt.Errorf("failed to write node key: %w", err)
  25. }
  26. return priv, nil
  27. } else {
  28. return nil, fmt.Errorf("failed to read node key: %w", err)
  29. }
  30. }
  31. priv, err := p2pcrypto.UnmarshalPrivateKey(b)
  32. if err != nil {
  33. return nil, fmt.Errorf("failed to unmarshal node key: %w", err)
  34. }
  35. logger.Info("Found existing node key", zap.String("path", path))
  36. return priv, nil
  37. }