github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/cmd/bootnode/main.go (about)

     1  // Copyright 2015 The go-simplechain Authors
     2  // This file is part of go-simplechain.
     3  //
     4  // go-simplechain 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-simplechain 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-simplechain. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // bootnode runs a bootstrap node for the Ethereum Discovery Protocol.
    18  package main
    19  
    20  import (
    21  	"crypto/ecdsa"
    22  	"flag"
    23  	"fmt"
    24  	"io/ioutil"
    25  	"net"
    26  	"os"
    27  	"path/filepath"
    28  
    29  	"github.com/bigzoro/my_simplechain/cmd/utils"
    30  	"github.com/bigzoro/my_simplechain/crypto"
    31  	"github.com/bigzoro/my_simplechain/log"
    32  	"github.com/bigzoro/my_simplechain/p2p/discover"
    33  	"github.com/bigzoro/my_simplechain/p2p/discv5"
    34  	"github.com/bigzoro/my_simplechain/p2p/enode"
    35  	"github.com/bigzoro/my_simplechain/p2p/nat"
    36  	"github.com/bigzoro/my_simplechain/p2p/netutil"
    37  )
    38  
    39  func main() {
    40  	var (
    41  		listenAddr  = flag.String("addr", ":30301", "listen address")
    42  		genKey      = flag.String("genkey", "", "generate a node key")
    43  		commonName  = flag.String("commonname", "", "commonname")
    44  		keydir      = flag.String("keydir", "", "key dir")
    45  		writeAddr   = flag.Bool("writeaddress", false, "write out the node's public key and quit")
    46  		nodeKeyFile = flag.String("nodekey", "", "private key filename")
    47  		nodeKeyHex  = flag.String("nodekeyhex", "", "private key as hex (for testing)")
    48  		natdesc     = flag.String("nat", "none", "port mapping mechanism (any|none|upnp|pmp|extip:<IP>)")
    49  		netrestrict = flag.String("netrestrict", "", "restrict network communication to the given IP networks (CIDR masks)")
    50  		runv5       = flag.Bool("v5", false, "run a v5 topic discovery bootnode")
    51  		verbosity   = flag.Int("verbosity", int(log.LvlInfo), "log verbosity (0-9)")
    52  		vmodule     = flag.String("vmodule", "", "log verbosity pattern")
    53  
    54  		nodeKey *ecdsa.PrivateKey
    55  		err     error
    56  	)
    57  	flag.Parse()
    58  
    59  	glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
    60  	glogger.Verbosity(log.Lvl(*verbosity))
    61  	glogger.Vmodule(*vmodule)
    62  	log.Root().SetHandler(glogger)
    63  
    64  	natm, err := nat.Parse(*natdesc)
    65  	if err != nil {
    66  		utils.Fatalf("-nat: %v", err)
    67  	}
    68  	switch {
    69  	case *genKey != "":
    70  		nodeKey, err = crypto.GenerateKey()
    71  		if err != nil {
    72  			utils.Fatalf("could not generate key: %v", err)
    73  		}
    74  		if err = crypto.SaveECDSA(*genKey, nodeKey); err != nil {
    75  			utils.Fatalf("%v", err)
    76  		}
    77  		if *keydir == "" {
    78  			if !*writeAddr {
    79  				return
    80  			}
    81  		} else {
    82  			encodeId := fmt.Sprintf("%x", crypto.FromECDSAPub(&nodeKey.PublicKey)[1:])
    83  			encode := fmt.Sprintf("[\"enode://%s@%s:30303?discport=0&raftport=8548\"]", encodeId, *commonName)
    84  			err = ioutil.WriteFile(filepath.Join(*keydir, "static-nodes.json"), []byte(encode), os.ModePerm)
    85  			if err != nil {
    86  				utils.Fatalf("-nat: %v", err)
    87  			}
    88  			return
    89  		}
    90  
    91  	case *nodeKeyFile == "" && *nodeKeyHex == "":
    92  		utils.Fatalf("Use -nodekey or -nodekeyhex to specify a private key")
    93  	case *nodeKeyFile != "" && *nodeKeyHex != "":
    94  		utils.Fatalf("Options -nodekey and -nodekeyhex are mutually exclusive")
    95  	case *nodeKeyFile != "":
    96  		if nodeKey, err = crypto.LoadECDSA(*nodeKeyFile); err != nil {
    97  			utils.Fatalf("-nodekey: %v", err)
    98  		}
    99  	case *nodeKeyHex != "":
   100  		if nodeKey, err = crypto.HexToECDSA(*nodeKeyHex); err != nil {
   101  			utils.Fatalf("-nodekeyhex: %v", err)
   102  		}
   103  	}
   104  
   105  	if *writeAddr {
   106  		fmt.Printf("%x\n", crypto.FromECDSAPub(&nodeKey.PublicKey)[1:])
   107  		os.Exit(0)
   108  	}
   109  
   110  	var restrictList *netutil.Netlist
   111  	if *netrestrict != "" {
   112  		restrictList, err = netutil.ParseNetlist(*netrestrict)
   113  		if err != nil {
   114  			utils.Fatalf("-netrestrict: %v", err)
   115  		}
   116  	}
   117  
   118  	addr, err := net.ResolveUDPAddr("udp", *listenAddr)
   119  	if err != nil {
   120  		utils.Fatalf("-ResolveUDPAddr: %v", err)
   121  	}
   122  	conn, err := net.ListenUDP("udp", addr)
   123  	if err != nil {
   124  		utils.Fatalf("-ListenUDP: %v", err)
   125  	}
   126  
   127  	realaddr := conn.LocalAddr().(*net.UDPAddr)
   128  	if natm != nil {
   129  		if !realaddr.IP.IsLoopback() {
   130  			go nat.Map(natm, nil, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
   131  		}
   132  		if ext, err := natm.ExternalIP(); err == nil {
   133  			realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port}
   134  		}
   135  	}
   136  
   137  	printNotice(&nodeKey.PublicKey, *realaddr)
   138  
   139  	if *runv5 {
   140  		if _, err := discv5.ListenUDP(nodeKey, conn, "", restrictList); err != nil {
   141  			utils.Fatalf("%v", err)
   142  		}
   143  	} else {
   144  		db, _ := enode.OpenDB("")
   145  		ln := enode.NewLocalNode(db, nodeKey)
   146  		cfg := discover.Config{
   147  			PrivateKey:  nodeKey,
   148  			NetRestrict: restrictList,
   149  		}
   150  		if _, err := discover.ListenUDP(conn, ln, cfg); err != nil {
   151  			utils.Fatalf("%v", err)
   152  		}
   153  	}
   154  
   155  	select {}
   156  }
   157  
   158  func printNotice(nodeKey *ecdsa.PublicKey, addr net.UDPAddr) {
   159  	if addr.IP.IsUnspecified() {
   160  		addr.IP = net.IP{127, 0, 0, 1}
   161  	}
   162  	n := enode.NewV4(nodeKey, addr.IP, 0, addr.Port)
   163  	fmt.Println(n.URLv4())
   164  	fmt.Println("Note: you're using cmd/bootnode, a developer tool.")
   165  	fmt.Println("We recommend using a regular node as bootstrap node for production deployments.")
   166  }