forked from maticnetwork/bor
/
bootnode.go
229 lines (197 loc) · 5.42 KB
/
bootnode.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
package cli
import (
"crypto/ecdsa"
"errors"
"fmt"
"net"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/internal/cli/flagset"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p/discover"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/mitchellh/cli"
)
type BootnodeCommand struct {
UI cli.Ui
listenAddr string
v5 bool
logLevel string
nat string
nodeKey string
saveKey string
dryRun bool
}
// Help implements the cli.Command interface
func (b *BootnodeCommand) Help() string {
return `Usage: bor bootnode`
}
// MarkDown implements cli.MarkDown interface
func (c *BootnodeCommand) MarkDown() string {
items := []string{
"# Bootnode",
c.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
func (b *BootnodeCommand) Flags() *flagset.Flagset {
flags := flagset.NewFlagSet("bootnode")
flags.StringFlag(&flagset.StringFlag{
Name: "listen-addr",
Default: "0.0.0.0:30303",
Usage: "listening address of bootnode (<ip>:<port>)",
Value: &b.listenAddr,
})
flags.BoolFlag(&flagset.BoolFlag{
Name: "v5",
Default: false,
Usage: "Enable UDP v5",
Value: &b.v5,
})
flags.StringFlag(&flagset.StringFlag{
Name: "log-level",
Default: "info",
Usage: "Log level (trace|debug|info|warn|error|crit)",
Value: &b.logLevel,
})
flags.StringFlag(&flagset.StringFlag{
Name: "nat",
Default: "none",
Usage: "port mapping mechanism (any|none|upnp|pmp|extip:<IP>)",
Value: &b.nat,
})
flags.StringFlag(&flagset.StringFlag{
Name: "node-key",
Default: "",
Usage: "file or hex node key",
Value: &b.nodeKey,
})
flags.StringFlag(&flagset.StringFlag{
Name: "save-key",
Default: "",
Usage: "path to save the ecdsa private key",
Value: &b.saveKey,
})
flags.BoolFlag(&flagset.BoolFlag{
Name: "dry-run",
Default: false,
Usage: "validates parameters and prints bootnode configurations, but does not start bootnode",
Value: &b.dryRun,
})
return flags
}
// Synopsis implements the cli.Command interface
func (b *BootnodeCommand) Synopsis() string {
return "Start a bootnode"
}
// Run implements the cli.Command interface
// nolint: gocognit
func (b *BootnodeCommand) Run(args []string) int {
flags := b.Flags()
if err := flags.Parse(args); err != nil {
b.UI.Error(err.Error())
return 1
}
glogger := log.NewGlogHandler(log.StreamHandler(os.Stderr, log.TerminalFormat(false)))
lvl, err := log.LvlFromString(strings.ToLower(b.logLevel))
if err == nil {
glogger.Verbosity(lvl)
} else {
glogger.Verbosity(log.LvlInfo)
}
log.Root().SetHandler(glogger)
natm, err := nat.Parse(b.nat)
if err != nil {
b.UI.Error(fmt.Sprintf("failed to parse nat: %v", err))
return 1
}
// create a one time key
var nodeKey *ecdsa.PrivateKey
// nolint: nestif
if b.nodeKey != "" {
// try to read the key either from file or command line
if _, err := os.Stat(b.nodeKey); errors.Is(err, os.ErrNotExist) {
if nodeKey, err = crypto.HexToECDSA(b.nodeKey); err != nil {
b.UI.Error(fmt.Sprintf("failed to parse hex address: %v", err))
return 1
}
} else {
if nodeKey, err = crypto.LoadECDSA(b.nodeKey); err != nil {
b.UI.Error(fmt.Sprintf("failed to load node key: %v", err))
return 1
}
}
} else {
// generate a new temporal key
if nodeKey, err = crypto.GenerateKey(); err != nil {
b.UI.Error(fmt.Sprintf("could not generate key: %v", err))
return 1
}
if b.saveKey != "" {
path := b.saveKey
// save the private key
if err = crypto.SaveECDSA(filepath.Join(path, "priv.key"), nodeKey); err != nil {
b.UI.Error(fmt.Sprintf("failed to write node priv key: %v", err))
return 1
}
// save the public key
pubRaw := fmt.Sprintf("%x", crypto.FromECDSAPub(&nodeKey.PublicKey)[1:])
if err := os.WriteFile(filepath.Join(path, "pub.key"), []byte(pubRaw), 0600); err != nil {
b.UI.Error(fmt.Sprintf("failed to write node pub key: %v", err))
return 1
}
}
}
addr, err := net.ResolveUDPAddr("udp", b.listenAddr)
if err != nil {
b.UI.Error(fmt.Sprintf("could not resolve udp addr '%s': %v", b.listenAddr, err))
return 1
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
b.UI.Error(fmt.Sprintf("failed to listen udp addr '%s': %v", b.listenAddr, err))
return 1
}
realaddr := conn.LocalAddr().(*net.UDPAddr)
if natm != nil {
if !realaddr.IP.IsLoopback() {
go nat.Map(natm, nil, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
}
if ext, err := natm.ExternalIP(); err == nil {
// nolint: govet
realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port}
}
}
n := enode.NewV4(&nodeKey.PublicKey, addr.IP, addr.Port, addr.Port)
b.UI.Info(n.String())
if b.dryRun {
return 0
}
db, _ := enode.OpenDB("")
ln := enode.NewLocalNode(db, nodeKey)
cfg := discover.Config{
PrivateKey: nodeKey,
Log: log.Root(),
}
if b.v5 {
if _, err := discover.ListenV5(conn, ln, cfg); err != nil {
utils.Fatalf("%v", err)
}
} else {
if _, err := discover.ListenUDP(conn, ln, cfg); err != nil {
utils.Fatalf("%v", err)
}
}
signalCh := make(chan os.Signal, 4)
signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
sig := <-signalCh
b.UI.Output(fmt.Sprintf("Caught signal: %v", sig))
b.UI.Output("Gracefully shutting down agent...")
return 0
}