-
Notifications
You must be signed in to change notification settings - Fork 19
/
node.go
90 lines (78 loc) · 2.34 KB
/
node.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
package main
import (
"context"
host "github.com/libp2p/go-libp2p-host"
kaddht "github.com/libp2p/go-libp2p-kad-dht"
peer "github.com/libp2p/go-libp2p-peer"
pstore "github.com/libp2p/go-libp2p-peerstore"
pubsub "github.com/libp2p/go-libp2p-pubsub"
)
type Node struct {
host.Host // lib-p2p host
discovery Discovery
*RequestProtocol // for peers to request data
*ShardManager
ctx context.Context
dht *kaddht.IpfsDHT
doBootstrapping bool
cancelBootstrapping context.CancelFunc
}
// NewNode creates a new node with its implemented protocols
func NewNode(ctx context.Context, h host.Host, dht *kaddht.IpfsDHT, eventNotifier EventNotifier) *Node {
shardPrefTable := NewShardPrefTable()
pubsubService, err := pubsub.NewGossipSub(ctx, h)
if err != nil {
logger.Fatalf("Failed to create new pubsub service, err: %v", err)
}
node := &Node{
Host: h,
discovery: NewGlobalTable(ctx, h, pubsubService, shardPrefTable),
ctx: ctx,
dht: dht,
doBootstrapping: false,
}
node.RequestProtocol = NewRequestProtocol(node)
node.ShardManager = NewShardManager(ctx, node, pubsubService, eventNotifier, node.discovery, shardPrefTable)
return node
}
// TODO: should be changed to `Knows` and `HasConnections`
func (n *Node) IsPeer(peerID peer.ID) bool {
for _, value := range n.Peerstore().Peers() {
if value == peerID {
return true
}
}
return false
}
//StartBootstrapping starts the bootstrapping process in dht, with the contact peers
// `bootstrapPeers`.
func (n *Node) StartBootstrapping(ctx context.Context, bootstrapPeers []pstore.PeerInfo) error {
if n.doBootstrapping {
return nil
}
// try to connect to the chosen nodes
bootstrapConnect(ctx, n, bootstrapPeers)
bootstrapCtx, cancel := context.WithCancel(ctx)
err := n.dht.Bootstrap(bootstrapCtx)
if err != nil {
return err
}
n.doBootstrapping = true
n.cancelBootstrapping = cancel
return nil
}
//IsBootstrapping indicates if the node is bootstrapping
func (n *Node) IsBootstrapping() bool {
return n.doBootstrapping
}
//StopBootstrapping stops the bootstrapping process, using the cancel function results from
// `StartBootstrapping`
func (n *Node) StopBootstrapping() error {
if !n.doBootstrapping {
return nil
}
n.cancelBootstrapping()
n.doBootstrapping = false
n.cancelBootstrapping = nil
return nil
}