github.com/core-coin/go-core/v2@v2.1.9/cmd/devp2p/keycmd.go (about) 1 // Copyright 2020 by the Authors 2 // This file is part of go-core. 3 // 4 // go-core is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // go-core 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 General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-core. If not, see <http://www.gnu.org/licenses/>. 16 17 package main 18 19 import ( 20 crand "crypto/rand" 21 "fmt" 22 "net" 23 24 "gopkg.in/urfave/cli.v1" 25 26 "github.com/core-coin/go-core/v2/crypto" 27 "github.com/core-coin/go-core/v2/p2p/enode" 28 ) 29 30 var ( 31 keyCommand = cli.Command{ 32 Name: "key", 33 Usage: "Operations on node keys", 34 Subcommands: []cli.Command{ 35 keyGenerateCommand, 36 keyToNodeCommand, 37 }, 38 } 39 keyGenerateCommand = cli.Command{ 40 Name: "generate", 41 Usage: "Generates node key files", 42 ArgsUsage: "keyfile", 43 Action: genkey, 44 } 45 keyToNodeCommand = cli.Command{ 46 Name: "to-enode", 47 Usage: "Creates an enode URL from a node key file", 48 ArgsUsage: "keyfile", 49 Action: keyToURL, 50 Flags: []cli.Flag{hostFlag, tcpPortFlag, udpPortFlag}, 51 } 52 ) 53 54 var ( 55 hostFlag = cli.StringFlag{ 56 Name: "ip", 57 Usage: "IP address of the node", 58 Value: "127.0.0.1", 59 } 60 tcpPortFlag = cli.IntFlag{ 61 Name: "tcp", 62 Usage: "TCP port of the node", 63 Value: 30300, 64 } 65 udpPortFlag = cli.IntFlag{ 66 Name: "udp", 67 Usage: "UDP port of the node", 68 Value: 30300, 69 } 70 ) 71 72 func genkey(ctx *cli.Context) error { 73 if ctx.NArg() != 1 { 74 return fmt.Errorf("need key file as argument") 75 } 76 file := ctx.Args().Get(0) 77 78 key, err := crypto.GenerateKey(crand.Reader) 79 if err != nil { 80 return fmt.Errorf("could not generate key: %v", err) 81 } 82 return crypto.SaveEDDSA(file, key) 83 } 84 85 func keyToURL(ctx *cli.Context) error { 86 if ctx.NArg() != 1 { 87 return fmt.Errorf("need key file as argument") 88 } 89 90 var ( 91 file = ctx.Args().Get(0) 92 host = ctx.String(hostFlag.Name) 93 tcp = ctx.Int(tcpPortFlag.Name) 94 udp = ctx.Int(udpPortFlag.Name) 95 ) 96 key, err := crypto.LoadEDDSA(file) 97 if err != nil { 98 return err 99 } 100 ip := net.ParseIP(host) 101 if ip == nil { 102 return fmt.Errorf("invalid IP address %q", host) 103 } 104 node := enode.NewV4(key.PublicKey(), ip, tcp, udp) 105 fmt.Println(node.URLv4()) 106 return nil 107 }