-
Notifications
You must be signed in to change notification settings - Fork 383
/
main.go
349 lines (302 loc) · 9.81 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main
import (
"context"
crand "crypto/rand"
"encoding/base64"
"flag"
"fmt"
"log"
mrand "math/rand"
"net"
"net/http"
"os"
"strings"
// nolint:staticcheck
libp2p "github.com/libp2p/go-libp2p"
libp2p_cicuit "github.com/libp2p/go-libp2p-circuit"
libp2p_ci "github.com/libp2p/go-libp2p-core/crypto"
libp2p_host "github.com/libp2p/go-libp2p-core/host"
metrics "github.com/libp2p/go-libp2p-core/metrics"
libp2p_peer "github.com/libp2p/go-libp2p-core/peer"
libp2p_quic "github.com/libp2p/go-libp2p-quic-transport"
libp2p_rp "github.com/libp2p/go-libp2p-rendezvous"
libp2p_rpdb "github.com/libp2p/go-libp2p-rendezvous/db/sqlite"
"github.com/libp2p/go-libp2p/config"
ma "github.com/multiformats/go-multiaddr"
"github.com/oklog/run"
ff "github.com/peterbourgon/ff/v3"
"github.com/peterbourgon/ff/v3/ffcli"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"moul.io/srand"
"berty.tech/berty/v2/go/internal/ipfsutil"
"berty.tech/berty/v2/go/internal/logutil"
"berty.tech/berty/v2/go/pkg/errcode"
)
func main() {
log.SetFlags(0)
// opts
var (
logFormat = "color" // json, console, color, light-console, light-color
logToFile = "stderr" // can be stdout, stderr or a file path
logFilters = "info+:*" // info and more for everything
serveURN = ":memory:"
serveListeners = "/ip4/0.0.0.0/tcp/4040,/ip4/0.0.0.0/udp/4141/quic"
servePK = ""
sharekeyPK = ""
serveAnnounce = ""
serveMetricsListeners = ""
genkeyType = "Ed25519"
genkeyLength = 2048
)
// parse opts
var (
serveFlags = flag.NewFlagSet("serve", flag.ExitOnError)
sharekeyFlags = flag.NewFlagSet("sharekey", flag.ExitOnError)
genkeyFlags = flag.NewFlagSet("genkey", flag.ExitOnError)
)
setupGlobalFlags := func(fs *flag.FlagSet) {
fs.StringVar(&logFilters, "log.filters", logFilters, "logged namespaces")
fs.StringVar(&logFormat, "log.format", logFormat, "if specified, will override default log format")
fs.StringVar(&logToFile, "log.file", logToFile, "if specified, will log everything in JSON into a file and nothing on stderr")
}
setupGlobalFlags(serveFlags)
setupGlobalFlags(sharekeyFlags)
setupGlobalFlags(genkeyFlags)
genkeyFlags.IntVar(&genkeyLength, "length", genkeyLength, "The length (in bits) of the key generated.")
genkeyFlags.StringVar(&genkeyType, "type", genkeyType, "Type of the private key generated, one of : Ed25519, ECDSA, Secp256k1, RSA")
serveFlags.String("config", "", "config file (optional)")
serveFlags.StringVar(&serveAnnounce, "announce", serveAnnounce, "addrs that will be announce by this server")
serveFlags.StringVar(&serveListeners, "l", serveListeners, "lists of listeners of (m)addrs separate by a comma")
serveFlags.StringVar(&serveMetricsListeners, "metrics", serveMetricsListeners, "metrics listener, if empty will disable metrics")
serveFlags.StringVar(&servePK, "pk", servePK, "private key (generated by `rdvp genkey`)")
serveFlags.StringVar(&serveURN, "db", serveURN, "rdvp sqlite URN")
sharekeyFlags.StringVar(&sharekeyPK, "pk", sharekeyPK, "private key (generated by `rdvp genkey`)")
serve := &ffcli.Command{
Name: "serve",
ShortUsage: "rdvp [global flags] serve [flags]",
LongHelp: "EXAMPLE\n rdvp genkey > rdvp.key\n rdvp serve -pk `cat rdvp.key` -db ./rdvp-store",
FlagSet: serveFlags,
Options: []ff.Option{
ff.WithEnvVarPrefix("RDVP"),
ff.WithConfigFileFlag("config"),
ff.WithConfigFileParser(ff.PlainParser),
},
Exec: func(ctx context.Context, args []string) error {
if len(args) > 0 {
return flag.ErrHelp
}
mrand.Seed(srand.MustSecure())
logger, cleanup, err := logutil.NewLogger(logutil.NewStdStream(logFilters, logFormat, logToFile))
if err != nil {
return errcode.TODO.Wrap(err)
}
defer cleanup()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
var gServe run.Group
gServe.Add(func() error {
<-ctx.Done()
return ctx.Err()
}, func(error) {
cancel()
})
laddrs := strings.Split(serveListeners, ",")
listeners, err := ipfsutil.ParseAddrs(laddrs...)
if err != nil {
return errcode.TODO.Wrap(err)
}
// load existing or generate new identity
var priv libp2p_ci.PrivKey
if servePK != "" {
kBytes, err := base64.StdEncoding.DecodeString(servePK)
if err != nil {
return errcode.TODO.Wrap(err)
}
priv, err = libp2p_ci.UnmarshalPrivateKey(kBytes)
if err != nil {
return errcode.TODO.Wrap(err)
}
} else {
// Don't use key params here, this is a dev tool, a real installation should use a static key.
priv, _, err = libp2p_ci.GenerateKeyPairWithReader(libp2p_ci.Ed25519, -1, crand.Reader) // nolint:staticcheck
if err != nil {
return errcode.TODO.Wrap(err)
}
}
var addrsFactory config.AddrsFactory = func(ms []ma.Multiaddr) []ma.Multiaddr { return ms }
if serveAnnounce != "" {
aaddrs := strings.Split(serveAnnounce, ",")
announces, err := ipfsutil.ParseAddrs(aaddrs...)
if err != nil {
return errcode.TODO.Wrap(err)
}
addrsFactory = func([]ma.Multiaddr) []ma.Multiaddr { return announces }
}
reporter := metrics.NewBandwidthCounter()
// init p2p host
host, err := libp2p.New(ctx,
// default tpt + quic
libp2p.DefaultTransports,
libp2p.Transport(libp2p_quic.NewTransport),
// Nat & Relay service
libp2p.EnableNATService(),
libp2p.DefaultStaticRelays(),
libp2p.EnableRelay(libp2p_cicuit.OptHop),
// swarm listeners
libp2p.ListenAddrs(listeners...),
// identity
libp2p.Identity(priv),
// announce
libp2p.AddrsFactory(addrsFactory),
// metrics
libp2p.BandwidthReporter(reporter),
)
if err != nil {
return errcode.TODO.Wrap(err)
}
defer host.Close()
logHostInfo(logger, host)
db, err := libp2p_rpdb.OpenDB(ctx, serveURN)
if err != nil {
return errcode.TODO.Wrap(err)
}
defer db.Close()
// start service
_ = libp2p_rp.NewRendezvousService(host, db)
if serveMetricsListeners != "" {
ml, err := net.Listen("tcp", serveMetricsListeners)
if err != nil {
return errcode.TODO.Wrap(err)
}
registry := prometheus.NewRegistry()
registry.MustRegister(prometheus.NewBuildInfoCollector())
registry.MustRegister(prometheus.NewGoCollector())
registry.MustRegister(ipfsutil.NewHostCollector(host))
registry.MustRegister(ipfsutil.NewBandwidthCollector(reporter))
// @TODO(gfanton): add rdvp specific collector...
handerfor := promhttp.HandlerFor(
registry,
promhttp.HandlerOpts{Registry: registry},
)
mux := http.NewServeMux()
gServe.Add(func() error {
mux.Handle("/metrics", handerfor)
logger.Info("metrics listener",
zap.String("handler", "/metrics"),
zap.String("listener", ml.Addr().String()))
return http.Serve(ml, mux)
}, func(error) {
ml.Close()
})
}
if err = gServe.Run(); err != nil {
return errcode.TODO.Wrap(err)
}
return nil
},
}
sharekey := &ffcli.Command{
Name: "sharekey",
ShortUsage: "rdvp [global flags] sharekey -pk PK",
FlagSet: sharekeyFlags,
Exec: func(ctx context.Context, args []string) error {
if len(args) > 0 {
return flag.ErrHelp
}
if sharekeyPK == "" {
return flag.ErrHelp
}
kBytes, err := base64.StdEncoding.DecodeString(sharekeyPK)
if err != nil {
return errcode.TODO.Wrap(err)
}
priv, err := libp2p_ci.UnmarshalPrivateKey(kBytes)
if err != nil {
return errcode.TODO.Wrap(err)
}
// init p2p host
host, err := libp2p.New(ctx,
libp2p.Identity(priv),
)
if err != nil {
return errcode.TODO.Wrap(err)
}
defer host.Close()
fmt.Println(host.ID().String())
return nil
},
}
genkey := &ffcli.Command{
Name: "genkey",
FlagSet: genkeyFlags,
Exec: func(context.Context, []string) error {
keyType, ok := keyNameToKeyType[strings.ToLower(genkeyType)]
if !ok {
return fmt.Errorf("unknown key type : '%s'. Only Ed25519, ECDSA, Secp256k1, RSA supported", genkeyType)
}
priv, _, err := libp2p_ci.GenerateKeyPairWithReader(keyType, genkeyLength, crand.Reader) // nolint:staticcheck
if err != nil {
return errcode.TODO.Wrap(err)
}
kBytes, err := libp2p_ci.MarshalPrivateKey(priv)
if err != nil {
return errcode.TODO.Wrap(err)
}
fmt.Println(base64.StdEncoding.EncodeToString(kBytes))
return nil
},
}
root := &ffcli.Command{
ShortUsage: "rdvp [global flags] <subcommand>",
Options: []ff.Option{ff.WithEnvVarPrefix("RDVP")},
Subcommands: []*ffcli.Command{serve, genkey, sharekey},
Exec: func(context.Context, []string) error {
return flag.ErrHelp
},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var process run.Group
// handle close signal
execute, interrupt := run.SignalHandler(ctx, os.Interrupt)
process.Add(execute, interrupt)
// add root command to process
process.Add(func() error {
return root.ParseAndRun(ctx, os.Args[1:])
}, func(error) {
cancel()
})
// run process
if err := process.Run(); err != nil && err != context.Canceled {
log.Println(err)
return
}
}
// Names are in lower case.
var keyNameToKeyType = map[string]int{
"ed25519": libp2p_ci.Ed25519,
"ecdsa": libp2p_ci.ECDSA,
"secp256k1": libp2p_ci.Secp256k1,
"rsa": libp2p_ci.RSA,
}
// helpers
func logHostInfo(l *zap.Logger, host libp2p_host.Host) {
// print peer addrs
fields := []zapcore.Field{
zap.String("host ID (local)", host.ID().String()),
}
addrs := host.Addrs()
pi := libp2p_peer.AddrInfo{
ID: host.ID(),
Addrs: addrs,
}
if maddrs, err := libp2p_peer.AddrInfoToP2pAddrs(&pi); err == nil {
for _, maddr := range maddrs {
fields = append(fields, zap.Stringer("maddr", maddr))
}
}
l.Info("host started", fields...)
}