-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathlibp2p.go
103 lines (89 loc) · 2.57 KB
/
libp2p.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
package libp2p
import (
"fmt"
"sort"
"time"
version "github.com/ipfs/kubo"
config "github.com/ipfs/kubo/config"
logging "github.com/ipfs/go-log"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/peerstore"
"github.com/libp2p/go-libp2p/p2p/net/connmgr"
"go.uber.org/fx"
)
var log = logging.Logger("p2pnode")
type Libp2pOpts struct {
fx.Out
Opts []libp2p.Option `group:"libp2p"`
}
func ConnectionManager(low, high int, grace time.Duration) func() (opts Libp2pOpts, err error) {
return func() (opts Libp2pOpts, err error) {
cm, err := connmgr.NewConnManager(low, high, connmgr.WithGracePeriod(grace))
if err != nil {
return opts, err
}
opts.Opts = append(opts.Opts, libp2p.ConnectionManager(cm))
return
}
}
func PstoreAddSelfKeys(id peer.ID, sk crypto.PrivKey, ps peerstore.Peerstore) error {
if err := ps.AddPubKey(id, sk.GetPublic()); err != nil {
return err
}
return ps.AddPrivKey(id, sk)
}
func UserAgent() func() (opts Libp2pOpts, err error) {
return simpleOpt(libp2p.UserAgent(version.GetUserAgentVersion()))
}
func simpleOpt(opt libp2p.Option) func() (opts Libp2pOpts, err error) {
return func() (opts Libp2pOpts, err error) {
opts.Opts = append(opts.Opts, opt)
return
}
}
type priorityOption struct {
priority, defaultPriority config.Priority
opt libp2p.Option
}
func prioritizeOptions(opts []priorityOption) libp2p.Option {
type popt struct {
priority int64 // lower priority values mean higher priority
opt libp2p.Option
}
enabledOptions := make([]popt, 0, len(opts))
for _, o := range opts {
if prio, ok := o.priority.WithDefault(o.defaultPriority); ok {
enabledOptions = append(enabledOptions, popt{
priority: prio,
opt: o.opt,
})
}
}
sort.Slice(enabledOptions, func(i, j int) bool {
return enabledOptions[i].priority < enabledOptions[j].priority
})
p2pOpts := make([]libp2p.Option, len(enabledOptions))
for i, opt := range enabledOptions {
p2pOpts[i] = opt.opt
}
return libp2p.ChainOptions(p2pOpts...)
}
func ForceReachability(val *config.OptionalString) func() (opts Libp2pOpts, err error) {
return func() (opts Libp2pOpts, err error) {
if val.IsDefault() {
return
}
v := val.WithDefault("unrecognized")
switch v {
case "public":
opts.Opts = append(opts.Opts, libp2p.ForceReachabilityPublic())
case "private":
opts.Opts = append(opts.Opts, libp2p.ForceReachabilityPrivate())
default:
return opts, fmt.Errorf("unrecognized reachability option: %s", v)
}
return
}
}