|
| 1 | +// Copyright (C) 2019-2024 Algorand, Inc. |
| 2 | +// This file is part of go-algorand |
| 3 | +// |
| 4 | +// go-algorand is free software: you can redistribute it and/or modify |
| 5 | +// it under the terms of the GNU Affero General Public License as |
| 6 | +// published by the Free Software Foundation, either version 3 of the |
| 7 | +// License, or (at your option) any later version. |
| 8 | +// |
| 9 | +// go-algorand is distributed in the hope that it will be useful, |
| 10 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +// GNU Affero General Public License for more details. |
| 13 | +// |
| 14 | +// You should have received a copy of the GNU Affero General Public License |
| 15 | +// along with go-algorand. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +// generate a new p2p private key and print out peerID to stdout |
| 18 | + |
| 19 | +package main |
| 20 | + |
| 21 | +import ( |
| 22 | + "fmt" |
| 23 | + "os" |
| 24 | + "path" |
| 25 | + |
| 26 | + "github.com/algorand/go-algorand/cmd/util/datadir" |
| 27 | + "github.com/algorand/go-algorand/config" |
| 28 | + "github.com/algorand/go-algorand/network/p2p" |
| 29 | + "github.com/algorand/go-algorand/util" |
| 30 | + "github.com/libp2p/go-libp2p/core/peer" |
| 31 | + "github.com/spf13/cobra" |
| 32 | +) |
| 33 | + |
| 34 | +var p2pID = &cobra.Command{ |
| 35 | + Use: "generate-p2pid", |
| 36 | + Short: "Generate a new p2p private key", |
| 37 | + Long: "Generate a new p2p private key (saved to " + p2p.DefaultPrivKeyPath + ") and print out peerID to stdout", |
| 38 | + Args: validateNoPosArgsFn, |
| 39 | + Run: func(cmd *cobra.Command, args []string) { |
| 40 | + anyError := false |
| 41 | + datadir.OnDataDirs(func(dataDir string) { |
| 42 | + exist := false |
| 43 | + privKeyPath := path.Join(dataDir, p2p.DefaultPrivKeyPath) |
| 44 | + if util.FileExists(privKeyPath) { |
| 45 | + exist = true |
| 46 | + } |
| 47 | + |
| 48 | + peerKey, err := p2p.GetPrivKey(config.Local{P2PPersistPeerID: true}, dataDir) |
| 49 | + if err != nil { |
| 50 | + fmt.Fprintf(os.Stderr, "Error obtaining private key: %v\n", err) |
| 51 | + anyError = true |
| 52 | + return |
| 53 | + } |
| 54 | + peerID, err := peer.IDFromPublicKey(peerKey.GetPublic()) |
| 55 | + if err != nil { |
| 56 | + fmt.Fprintf(os.Stderr, "Error obtaining peerID from a key: %v\n", err) |
| 57 | + anyError = true |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + fmt.Printf("PeerID: %s\n", peerID.String()) |
| 62 | + if !exist { |
| 63 | + fmt.Printf("Private key saved to %s\n", privKeyPath) |
| 64 | + } else { |
| 65 | + fmt.Printf("Used existing key %s\n", privKeyPath) |
| 66 | + } |
| 67 | + }) |
| 68 | + if anyError { |
| 69 | + os.Exit(1) |
| 70 | + } |
| 71 | + }, |
| 72 | +} |
0 commit comments