forked from berty/berty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
261 lines (219 loc) · 6.49 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
package main
import (
"context"
crand "crypto/rand"
"encoding/base64"
"flag"
"fmt"
"log"
mrand "math/rand"
"net"
"os"
"strings"
"berty.tech/berty/v2/go/pkg/errcode"
ipfs_log "github.com/ipfs/go-log"
libp2p "github.com/libp2p/go-libp2p"
libp2p_cicuit "github.com/libp2p/go-libp2p-circuit"
libp2p_ci "github.com/libp2p/go-libp2p-core/crypto" // nolint:staticcheck
libp2p_host "github.com/libp2p/go-libp2p-core/host"
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"
ma "github.com/multiformats/go-multiaddr"
"github.com/oklog/run"
"github.com/peterbourgon/ff"
"github.com/peterbourgon/ff/ffcli"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"moul.io/srand"
)
func main() {
log.SetFlags(0)
var (
process run.Group
logger *zap.Logger
globalFlags = flag.NewFlagSet("berty", flag.ExitOnError)
globalDebug = globalFlags.Bool("debug", false, "berty debug mode")
globalLibp2pDebug = globalFlags.Bool("debug-p2p", false, "libp2p debug mode")
globalOrbitDebug = globalFlags.Bool("debug-odb", false, "orbitdb debug mode")
globalLogToFile = globalFlags.String("logfile", "", "if specified, will log everything in JSON into a file and nothing on stderr")
serveFlags = flag.NewFlagSet("serve", flag.ExitOnError)
serveFlagsURN = serveFlags.String("db", ":memory:", "rdvp sqlite URN")
serveFlagsListeners = serveFlags.String("l", "/ip4/0.0.0.0/tcp/4040,/ip4/0.0.0.0/udp/4141/quic", "lists of listeners of (m)addrs separate by a comma")
serveFlagsPK = serveFlags.String("pk", "", "private key (generated by `rdvp genkey`)")
)
globalPreRun := func() error {
mrand.Seed(srand.Secure())
isDebugEnabled := *globalDebug || *globalOrbitDebug || *globalLibp2pDebug
// setup zap config
var config zap.Config
if *globalLogToFile != "" {
config = zap.NewProductionConfig()
config.OutputPaths = []string{*globalLogToFile}
} else {
config = zap.NewDevelopmentConfig()
config.DisableStacktrace = true
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
if isDebugEnabled {
config.Level.SetLevel(zap.DebugLevel)
} else {
config.Level.SetLevel(zap.InfoLevel)
}
var err error
if logger, err = config.Build(); err != nil {
return errcode.TODO.Wrap(err)
}
if *globalLibp2pDebug {
ipfs_log.SetDebugLogging()
}
if *globalOrbitDebug {
zap.ReplaceGlobals(logger)
}
return nil
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// handle close signal
execute, interrupt := run.SignalHandler(ctx, os.Interrupt)
process.Add(execute, interrupt)
serve := &ffcli.Command{
Name: "serve",
Usage: "serve -l <maddrs> -pk <private_key> -db <file>",
FlagSet: serveFlags,
Options: []ff.Option{ff.WithEnvVarPrefix("RDVP")},
Exec: func(args []string) error {
if err := globalPreRun(); err != nil {
return errcode.TODO.Wrap(err)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
laddrs := strings.Split(*serveFlagsListeners, ",")
listeners, err := parseAddrs(laddrs...)
if err != nil {
return errcode.TODO.Wrap(err)
}
// load existing or generate new identity
var priv libp2p_ci.PrivKey
if *serveFlagsPK != "" {
kBytes, err := base64.StdEncoding.DecodeString(*serveFlagsPK)
if err != nil {
return errcode.TODO.Wrap(err)
}
priv, err = libp2p_ci.UnmarshalPrivateKey(kBytes)
if err != nil {
return errcode.TODO.Wrap(err)
}
} else {
priv, _, err = libp2p_ci.GenerateKeyPairWithReader(libp2p_ci.RSA, 2048, crand.Reader) // nolint:staticcheck
if err != nil {
return errcode.TODO.Wrap(err)
}
}
// 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),
)
if err != nil {
return errcode.TODO.Wrap(err)
}
defer host.Close()
logHostInfo(logger, host)
db, err := libp2p_rpdb.OpenDB(ctx, *serveFlagsURN)
if err != nil {
return errcode.TODO.Wrap(err)
}
defer db.Close()
// start service
_ = libp2p_rp.NewRendezvousService(host, db)
<-ctx.Done()
if err = ctx.Err(); err != nil {
return errcode.TODO.Wrap(err)
}
return nil
},
}
genkey := &ffcli.Command{
Name: "genkey",
Exec: func(args []string) error {
priv, _, err := libp2p_ci.GenerateKeyPairWithReader(libp2p_ci.RSA, 2048, 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{
Usage: "rdvp [global flags] <subcommand> [flags] [args...]",
FlagSet: globalFlags,
Options: []ff.Option{ff.WithEnvVarPrefix("RDVP")},
Subcommands: []*ffcli.Command{serve, genkey},
Exec: func([]string) error {
globalFlags.Usage()
return flag.ErrHelp
},
}
// add root command to process
process.Add(func() error {
return root.Run(os.Args[1:])
}, func(error) {
cancel()
})
// run process
if err := process.Run(); err != nil && err != context.Canceled {
log.Fatal(err)
}
}
// 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...)
}
func parseAddrs(addrs ...string) (maddrs []ma.Multiaddr, err error) {
maddrs = make([]ma.Multiaddr, len(addrs))
for i, addr := range addrs {
maddrs[i], err = ma.NewMultiaddr(addr)
if err != nil {
// try to get a tcp multiaddr from host:port
host, port, serr := net.SplitHostPort(addr)
if serr != nil {
return
}
if host == "" {
host = "127.0.0.1"
}
addr = fmt.Sprintf("/ip4/%s/tcp/%s/", host, port)
maddrs[i], err = ma.NewMultiaddr(addr)
}
}
return
}