forked from klaytn/klaytn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
235 lines (211 loc) · 6.07 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Modifications Copyright 2018 The klaytn Authors
// Copyright 2015 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
//
// This file is derived from cmd/bootnode/main.go (2018/06/04).
// Modified and improved for the klaytn development.
package main
import (
"errors"
"fmt"
"github.com/klaytn/klaytn/api/debug"
"github.com/klaytn/klaytn/cmd/utils"
"github.com/klaytn/klaytn/cmd/utils/nodecmd"
"github.com/klaytn/klaytn/log"
"github.com/klaytn/klaytn/networks/p2p"
"github.com/klaytn/klaytn/networks/p2p/discover"
"github.com/klaytn/klaytn/networks/p2p/nat"
"gopkg.in/urfave/cli.v1"
"net"
"os"
"os/signal"
"syscall"
)
var (
logger = log.NewModuleLogger(log.CMDKBN)
)
const (
generateNodeKeySpecified = iota
noPrivateKeyPathSpecified
nodeKeyDuplicated
writeOutAddress
goodToGo
)
func bootnode(ctx *cli.Context) error {
var (
// Local variables
err error
bcfg = bootnodeConfig{
// Config variables
networkID: ctx.GlobalUint64(utils.NetworkIdFlag.Name),
addr: ctx.GlobalString(utils.BNAddrFlag.Name),
genKeyPath: ctx.GlobalString(utils.GenKeyFlag.Name),
nodeKeyFile: ctx.GlobalString(utils.NodeKeyFileFlag.Name),
nodeKeyHex: ctx.GlobalString(utils.NodeKeyHexFlag.Name),
natFlag: ctx.GlobalString(utils.NATFlag.Name),
netrestrict: ctx.GlobalString(utils.NetrestrictFlag.Name),
writeAddress: ctx.GlobalBool(utils.WriteAddressFlag.Name),
IPCPath: "klay.ipc",
DataDir: ctx.GlobalString(utils.DataDirFlag.Name),
HTTPPort: DefaultHTTPPort,
HTTPModules: []string{"net"},
HTTPVirtualHosts: []string{"localhost"},
WSPort: DefaultWSPort,
WSModules: []string{"net"},
GRPCPort: DefaultGRPCPort,
Logger: log.NewModuleLogger(log.CMDKBN),
}
)
if err = nodecmd.CheckCommands(ctx); err != nil {
return err
}
setIPC(ctx, &bcfg)
// httptype is http or fasthttp
if ctx.GlobalIsSet(utils.SrvTypeFlag.Name) {
bcfg.HTTPServerType = ctx.GlobalString(utils.SrvTypeFlag.Name)
}
setHTTP(ctx, &bcfg)
setWS(ctx, &bcfg)
setgRPC(ctx, &bcfg)
setAuthorizedNodes(ctx, &bcfg)
// Check exit condition
switch bcfg.checkCMDState() {
case generateNodeKeySpecified:
bcfg.generateNodeKey()
case noPrivateKeyPathSpecified:
return errors.New("Use --nodekey or --nodekeyhex to specify a private key")
case nodeKeyDuplicated:
return errors.New("Options --nodekey and --nodekeyhex are mutually exclusive")
case writeOutAddress:
bcfg.doWriteOutAddress()
default:
err = bcfg.readNodeKey()
if err != nil {
return err
}
}
err = bcfg.validateNetworkParameter()
if err != nil {
return err
}
addr, err := net.ResolveUDPAddr("udp", bcfg.listenAddr)
if err != nil {
log.Fatalf("Failed to ResolveUDPAddr: %v", err)
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
log.Fatalf("Failed to ListenUDP: %v", err)
}
realaddr := conn.LocalAddr().(*net.UDPAddr)
if bcfg.natm != nil {
if !realaddr.IP.IsLoopback() {
go nat.Map(bcfg.natm, nil, "udp", realaddr.Port, realaddr.Port, "Klaytn node discovery")
}
// TODO: react to external IP changes over time.
if ext, err := bcfg.natm.ExternalIP(); err == nil {
realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port}
}
}
cfg := discover.Config{
NetworkID: bcfg.networkID,
PrivateKey: bcfg.nodeKey,
AnnounceAddr: realaddr,
NetRestrict: bcfg.restrictList,
Conn: conn,
Addr: realaddr,
Id: discover.PubkeyID(&bcfg.nodeKey.PublicKey),
NodeType: p2p.ConvertNodeType(p2p.BOOTNODE),
AuthorizedNodes: bcfg.AuthorizedNodes,
}
tab, err := discover.ListenUDP(&cfg)
if err != nil {
log.Fatalf("%v", err)
}
node, err := New(&bcfg)
if err != nil {
return err
}
node.appendAPIs(NewBN(tab).APIs())
if err := startNode(node); err != nil {
return err
}
node.Wait()
return nil
}
func startNode(node *Node) error {
if err := node.Start(); err != nil {
return err
}
go func() {
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigc)
<-sigc
logger.Info("Got interrupt, shutting down...")
go node.Stop()
for i := 10; i > 0; i-- {
<-sigc
if i > 1 {
logger.Info("Already shutting down, interrupt more to panic.", "times", i-1)
}
}
}()
return nil
}
func main() {
var (
cliFlags = []cli.Flag{
utils.SrvTypeFlag,
utils.DataDirFlag,
utils.GenKeyFlag,
utils.NodeKeyFileFlag,
utils.NodeKeyHexFlag,
utils.WriteAddressFlag,
utils.BNAddrFlag,
utils.NATFlag,
utils.NetrestrictFlag,
utils.MetricsEnabledFlag,
utils.PrometheusExporterFlag,
utils.PrometheusExporterPortFlag,
utils.AuthorizedNodesFlag,
utils.NetworkIdFlag,
}
)
// TODO-Klaytn: remove `help` command
app := utils.NewApp("", "the Klaytn's bootnode command line interface")
app.Name = "kbn"
app.Copyright = "Copyright 2018 The klaytn Authors"
app.UsageText = app.Name + " [global options] [commands]"
app.Flags = append(app.Flags, cliFlags...)
app.Flags = append(app.Flags, debug.Flags...)
app.Flags = append(app.Flags, nodecmd.CommonRPCFlags...)
app.Commands = []cli.Command{
nodecmd.VersionCommand,
nodecmd.AttachCommand,
}
app.Action = bootnode
app.CommandNotFound = nodecmd.CommandNotExist
app.OnUsageError = nodecmd.OnUsageError
app.Before = nodecmd.BeforeRunBootnode
app.After = func(c *cli.Context) error {
debug.Exit()
return nil
}
if err := app.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}