/
peer.go
305 lines (251 loc) · 8.04 KB
/
peer.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
package peer
import (
"bytes"
"context"
"errors"
"fmt"
"math/rand"
"os"
"time"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p-kad-dht/dual"
pubsub "github.com/libp2p/go-libp2p-pubsub"
crypto "github.com/libp2p/go-libp2p/core/crypto"
peer "github.com/libp2p/go-libp2p/core/peer"
ipfslite "github.com/hsanjuan/ipfs-lite"
dirutils "github.com/taubyte/utils/fs/dir"
"github.com/libp2p/go-libp2p/core/pnet"
helpers "github.com/taubyte/p2p/helpers"
discoveryBackoff "github.com/libp2p/go-libp2p/p2p/discovery/backoff"
discovery "github.com/libp2p/go-libp2p/p2p/discovery/routing"
)
func StandAlone() BootstrapParams {
return BootstrapParams{Enable: false}
}
func Bootstrap(peers ...peer.AddrInfo) BootstrapParams {
return BootstrapParams{Enable: true, Peers: peers}
}
func init() {
// Bootstrappers are using 1024 keys. See:
// https://github.com/ipfs/infra/issues/378
crypto.MinRsaKeyBits = 1024
}
func (p *node) Close() {
err := p.cleanup()
if err != nil {
panic(err)
}
p.closed = true
}
func (p *node) cleanup() error {
p.topicsMutex.Lock()
defer p.topicsMutex.Unlock()
p.topics = nil
if err := p.Peer().Close(); err != nil {
return err
}
if p.peering != nil {
if err := p.peering.Stop(); err != nil {
return err
}
}
if p.dht != nil {
// Need to determine the type of DHT then close it
switch p.dht.(type) {
case *dht.IpfsDHT:
if err := p.dht.(*dht.IpfsDHT).Close(); err != nil {
return err
}
case *dual.DHT:
if err := p.dht.(*dual.DHT).Close(); err != nil {
return err
}
}
}
if p.store != nil {
if err := p.store.Close(); err != nil {
return err
}
}
if p.ephemeral_repo_path {
os.RemoveAll(p.repo_path)
}
p.ctx_cancel()
return nil
}
func (p *node) Done() <-chan struct{} {
return p.ctx.Done()
}
// Create a folder inside node root folder
func (p *node) NewFolder(name string) (dirutils.Directory, error) {
return dirutils.New(fmt.Sprintf("%s/local/%s", p.repo_path, name))
}
func (p *node) WaitForSwarm(timeout time.Duration) error {
wctx, wctx_c := context.WithTimeout(p.ctx, timeout)
defer wctx_c()
for {
select {
case <-time.After(100 * time.Millisecond):
if len(p.host.Peerstore().Peers()) > 0 {
return nil
}
case <-wctx.Done():
return errors.New("not able to connect to other peers")
}
}
}
func New(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, notPublic bool, bootstrap bool) (Node, error) {
opts := make([]libp2p.Option, len(helpers.Libp2pSimpleNodeOptions))
copy(opts, helpers.Libp2pSimpleNodeOptions)
if notPublic {
opts = append(opts, libp2p.ForceReachabilityPrivate())
}
return new(ctx, repoPath, privateKey, swarmKey, swarmListen, swarmAnnounce, BootstrapParams{Enable: bootstrap}, false, opts...)
}
func NewClientNode(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, notPublic bool, bootstrapers []peer.AddrInfo) (Node, error) {
opts := make([]libp2p.Option, len(helpers.Libp2pLitePrivateNodeOptions))
copy(opts, helpers.Libp2pLitePrivateNodeOptions)
if notPublic {
opts = append(opts, libp2p.ForceReachabilityPrivate())
}
return new(ctx, repoPath, privateKey, swarmKey, swarmListen, swarmAnnounce, BootstrapParams{Enable: true, Peers: bootstrapers}, false, opts...)
}
func NewWithBootstrapList(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, notPublic bool, bootstrapers []peer.AddrInfo) (Node, error) {
opts := make([]libp2p.Option, len(helpers.Libp2pSimpleNodeOptions))
copy(opts, helpers.Libp2pSimpleNodeOptions)
if notPublic {
opts = append(opts, libp2p.ForceReachabilityPrivate())
}
return new(ctx, repoPath, privateKey, swarmKey, swarmListen, swarmAnnounce, BootstrapParams{Enable: true, Peers: bootstrapers}, false, opts...)
}
func NewFull(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, isPublic bool, bootstrap BootstrapParams) (Node, error) {
opts := make([]libp2p.Option, len(helpers.Libp2pOptionsFullNode))
copy(opts, helpers.Libp2pOptionsFullNode)
if isPublic {
opts = append(opts, libp2p.ForceReachabilityPublic())
}
return new(ctx, repoPath, privateKey, swarmKey, swarmListen, swarmAnnounce, bootstrap, true, opts...)
}
func NewPublic(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, bootstrap BootstrapParams) (Node, error) {
opts := make([]libp2p.Option, len(helpers.Libp2pOptionsPublicNode))
copy(opts, helpers.Libp2pOptionsPublicNode)
return new(ctx, repoPath, privateKey, swarmKey, swarmListen, swarmAnnounce, bootstrap, true, opts...)
}
func NewLitePublic(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, bootstrap BootstrapParams) (Node, error) {
opts := make([]libp2p.Option, len(helpers.Libp2pOptionsLitePublicNode))
copy(opts, helpers.Libp2pOptionsLitePublicNode)
return new(ctx, repoPath, privateKey, swarmKey, swarmListen, swarmAnnounce, bootstrap, true, opts...)
}
func new(ctx context.Context, repoPath interface{}, privateKey []byte, swarmKey []byte, swarmListen []string, swarmAnnounce []string, bootstrap BootstrapParams, server bool, opts ...libp2p.Option) (Node, error) {
var p node
var err error
p.ctx, p.ctx_cancel = context.WithCancel(ctx)
p.ephemeral_repo_path = false
if repoPath == nil {
repoPath, err = os.MkdirTemp("", "tb-node-*")
if err != nil {
return nil, err
}
p.ephemeral_repo_path = true
}
p.repo_path = fmt.Sprint(repoPath)
p.store, err = helpers.NewDatastore(p.repo_path)
if err != nil {
return nil, err
}
// Read key
p.key, err = crypto.UnmarshalPrivateKey(privateKey)
if err != nil {
return nil, err
}
// Generate ID
p.id, err = peer.IDFromPublicKey(p.key.GetPublic())
if err != nil {
return nil, err
}
// Read swarm key
if swarmKey != nil {
p.secret, err = pnet.DecodeV1PSK(bytes.NewReader(swarmKey))
if err != nil {
return nil, err
}
}
// https://github.com/libp2p/go-libp2p/blob/d4d6adff6e3260792cb4514c27368059f2558530/options.go
if opts == nil {
opts = make([]libp2p.Option, 0)
}
opts = append(helpers.Libp2pOptionsBase, opts...)
opts = append(opts, libp2p.UserAgent(UserAgent))
if server && swarmAnnounce != nil {
opts = append(opts, p.SimpleAddrsFactory(swarmAnnounce, server))
}
bootstrapHandler := func() []peer.AddrInfo {
return bootstrap.Peers
}
p.host, p.dht, err = helpers.SetupLibp2p(
p.ctx,
p.key,
p.secret,
swarmListen,
p.store,
bootstrapHandler,
opts...,
)
if err != nil {
return nil, err
}
// Create ipfs node
p.ipfs, err = ipfslite.New(p.ctx, p.store, nil, p.host, p.dht, nil)
if err != nil {
return nil, err
}
p.peering = NewPeeringService(&p)
err = p.peering.Start()
if err != nil {
return nil, err
}
if bootstrap.Enable {
// Bootstrap
bnodes, err := helpers.Bootstrap(p.ctx, p.host, p.dht, bootstrap.Peers)
if err != nil {
return nil, err
}
// TODO: get the peering service out of bootsrap
for _, n := range bnodes {
p.peering.AddPeer(n)
}
} else {
err := p.dht.Bootstrap(p.ctx)
if err != nil {
p.ctx_cancel()
return nil, err
}
}
// Prep Discoverer
p.drouter = discovery.NewRoutingDiscovery(p.dht)
minBackoff, maxBackoff := time.Second*60, time.Hour
rng := rand.New(rand.NewSource(rand.Int63()))
_drouter, err := discoveryBackoff.NewBackoffDiscovery(
p.drouter,
discoveryBackoff.NewExponentialBackoff(minBackoff, maxBackoff, discoveryBackoff.FullJitter, time.Second, 5.0, 0, rng),
)
if err != nil {
return nil, err
}
p.drouter = _drouter
// Prep messaging PUBSUB
p.messaging, err = pubsub.NewGossipSub(
p.ctx,
p.host,
pubsub.WithDiscovery(_drouter),
pubsub.WithFloodPublish(true),
pubsub.WithMessageSigning(true),
pubsub.WithStrictSignatureVerification(true),
)
if err != nil {
return nil, err
}
p.topics = make(map[string]*pubsub.Topic)
return &p, nil
}