+// NodeKey retrieves the currently configured private key of the node, checking
+// first any manually set key, falling back to the one found in the configured
+// data folder. If no key can be found, a new one is generated.
+func (cfg *Config) NodeKey() (string, error) {
+ // Use any specifically configured key.
+ if cfg.P2P.PrivateKey != "" {
+ return cfg.P2P.PrivateKey, nil
+ }
+
+ keyFile := rootify(cfg.P2P.NodeKeyFile, cfg.BaseConfig.RootDir)
+ buf := make([]byte, ed25519.PrivateKeySize*2)
+ fd, err := os.Open(keyFile)
+ defer fd.Close()
+ if err == nil {
+ if _, err = io.ReadFull(fd, buf); err == nil {
+ return string(buf), nil
+ }
+ }
+
+ log.WithField("err", err).Warning("key file access failed")
+ _, privKey, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ return "", err
+ }
+
+ if err = ioutil.WriteFile(keyFile, []byte(privKey.String()), 0600); err != nil {
+ return "", err
+ }
+ return privKey.String(), nil
+}
+