-
Notifications
You must be signed in to change notification settings - Fork 212
/
relay.go
78 lines (67 loc) · 1.88 KB
/
relay.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
package node
import (
"context"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/config"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/metrics"
"github.com/spacemeshos/go-spacemesh/p2p"
"github.com/spacemeshos/go-spacemesh/p2p/handshake"
)
var relayAddrInfoCh chan peer.AddrInfo // used for testing
func runRelay(ctx context.Context, cfg *config.Config) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()
p2pCfg := cfg.P2P
p2pCfg.DataDir = filepath.Join(cfg.DataDir(), "p2p")
p2pCfg.DisablePubSub = true
p2pCfg.Relay = true
p2pCfg.RelayServer.Enable = true
lvl, err := decodeLoggerLevel(cfg, P2PLogger)
if err != nil {
return fmt.Errorf("failed to decode loggers: %w", err)
}
p2pCfg.LogLevel = lvl.Level()
p2pLog := log.NewWithLevel("node", lvl).WithName(P2PLogger)
if cfg.CollectMetrics {
metrics.StartMetricsServer(cfg.MetricsPort)
}
types.SetLayersPerEpoch(cfg.LayersPerEpoch)
prologue := fmt.Sprintf("%x-%v",
cfg.Genesis.GenesisID(),
types.GetEffectiveGenesis(),
)
// Prevent testnet nodes from working on the mainnet, but
// don't use the network cookie on mainnet as this technique
// may be replaced later
nc := handshake.NoNetworkCookie
if !onMainNet(cfg) {
nc = handshake.NetworkCookie(prologue)
}
host, err := p2p.New(ctx, p2pLog, p2pCfg, []byte(prologue), nc)
if err != nil {
return fmt.Errorf("initialize p2p host: %w", err)
}
if err := host.Start(); err != nil {
return fmt.Errorf("error starting P2P host: %w", err)
}
if relayAddrInfoCh != nil {
select {
case relayAddrInfoCh <- peer.AddrInfo{
ID: host.ID(),
Addrs: host.Addrs(),
}:
case <-ctx.Done():
return ctx.Err()
}
}
defer host.Stop()
<-ctx.Done()
return nil
}