github.com/sunriselayer/sunrise-da@v0.13.1-sr3/cmd/cel-shed/p2p.go (about) 1 package main 2 3 import ( 4 "crypto/rand" 5 "encoding/hex" 6 "fmt" 7 8 "github.com/libp2p/go-libp2p/core/crypto" 9 "github.com/libp2p/go-libp2p/core/peer" 10 "github.com/spf13/cobra" 11 ) 12 13 func init() { 14 p2pCmd.AddCommand(p2pNewKeyCmd, p2pPeerIDCmd) 15 } 16 17 var p2pCmd = &cobra.Command{ 18 Use: "p2p [subcommand]", 19 Short: "Collection of p2p related utilities", 20 } 21 22 var p2pNewKeyCmd = &cobra.Command{ 23 Use: "new-key", 24 Short: "Generate and print new Ed25519 private key for p2p networking", 25 RunE: func(cmd *cobra.Command, args []string) error { 26 privkey, _, err := crypto.GenerateEd25519Key(rand.Reader) 27 if err != nil { 28 return err 29 } 30 31 raw, err := privkey.Raw() 32 if err != nil { 33 return err 34 } 35 36 fmt.Println(hex.EncodeToString(raw)) 37 return nil 38 }, 39 Args: cobra.NoArgs, 40 } 41 42 var p2pPeerIDCmd = &cobra.Command{ 43 Use: "peer-id", 44 Short: "Get peer-id out of public or private Ed25519 key", 45 RunE: func(cmd *cobra.Command, args []string) error { 46 decKey, err := hex.DecodeString(args[0]) 47 if err != nil { 48 return err 49 } 50 51 privKey, err := crypto.UnmarshalEd25519PrivateKey(decKey) 52 if err != nil { 53 // try pubkey then 54 pubKey, err := crypto.UnmarshalEd25519PublicKey(decKey) 55 if err != nil { 56 return err 57 } 58 59 id, err := peer.IDFromPublicKey(pubKey) 60 if err != nil { 61 return err 62 } 63 64 fmt.Println(id.String()) 65 return nil 66 } 67 68 id, err := peer.IDFromPrivateKey(privKey) 69 if err != nil { 70 return err 71 } 72 73 fmt.Println(id.String()) 74 return nil 75 }, 76 Args: cobra.ExactArgs(1), 77 }