-
Notifications
You must be signed in to change notification settings - Fork 156
/
p2p.go
355 lines (303 loc) · 9.07 KB
/
p2p.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
package p2p
import (
"context"
"encoding/hex"
"errors"
"fmt"
"math/rand"
"strings"
"sync"
"time"
"github.com/NethermindEth/juno/blockchain"
"github.com/NethermindEth/juno/p2p/starknet"
junoSync "github.com/NethermindEth/juno/sync"
"github.com/NethermindEth/juno/utils"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/libp2p/go-libp2p/core/crypto/pb"
"github.com/libp2p/go-libp2p/core/event"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/protocol"
"github.com/multiformats/go-multiaddr"
"google.golang.org/protobuf/proto"
)
const (
keyLength = 2048
routingTableRefreshPeriod = 1 * time.Second
)
type Service struct {
host host.Host
network *utils.Network
handler *starknet.Handler
log utils.SimpleLogger
dht *dht.IpfsDHT
pubsub *pubsub.PubSub
topics map[string]*pubsub.Topic
topicsLock sync.RWMutex
synchroniser *syncService
feederNode bool
}
func New(addr, userAgent, peers, privKeyStr string, feederNode bool, bc *blockchain.Blockchain, snNetwork *utils.Network,
log utils.SimpleLogger,
) (*Service, error) {
if addr == "" {
// 0.0.0.0/tcp/0 will listen on any interface device and assing a free port.
addr = "/ip4/0.0.0.0/tcp/0"
}
sourceMultiAddr, err := multiaddr.NewMultiaddr(addr)
if err != nil {
return nil, err
}
prvKey, err := privateKey(privKeyStr)
if err != nil {
return nil, err
}
p2pHost, err := libp2p.New(libp2p.ListenAddrs(sourceMultiAddr), libp2p.Identity(prvKey), libp2p.UserAgent(userAgent))
if err != nil {
return nil, err
}
// Todo: try to understand what will happen if user passes a multiaddr with p2p public and a private key which doesn't match.
// For example, a user passes the following multiaddr: --p2p-addr=/ip4/0.0.0.0/tcp/7778/p2p/(SomePublicKey) and also passes a
// --p2p-private-key="SomePrivateKey". However, the private public key pair don't match, in this case what will happen?
return NewWithHost(p2pHost, peers, feederNode, bc, snNetwork, log)
}
func NewWithHost(p2phost host.Host, peers string, feederNode bool, bc *blockchain.Blockchain, snNetwork *utils.Network,
log utils.SimpleLogger,
) (*Service, error) {
peersAddrInfoS := []peer.AddrInfo{}
if peers != "" {
splitted := strings.Split(peers, ",")
for _, peerStr := range splitted {
peerAddr, err := peer.AddrInfoFromString(peerStr)
if err != nil {
return nil, fmt.Errorf("addr info from %q: %w", peerStr, err)
}
peersAddrInfoS = append(peersAddrInfoS, *peerAddr)
}
}
p2pdht, err := makeDHT(p2phost, snNetwork, peersAddrInfoS)
if err != nil {
return nil, err
}
// todo: reconsider initialising synchroniser here because if node is a feedernode we shouldn't not create an instance of it.
synchroniser := newSyncService(bc, p2phost, snNetwork, log)
s := &Service{
synchroniser: synchroniser,
log: log,
host: p2phost,
network: snNetwork,
dht: p2pdht,
feederNode: feederNode,
topics: make(map[string]*pubsub.Topic),
handler: starknet.NewHandler(bc, log),
}
return s, nil
}
func makeDHT(p2phost host.Host, snNetwork *utils.Network, addrInfos []peer.AddrInfo) (*dht.IpfsDHT, error) {
return dht.New(context.Background(), p2phost,
dht.ProtocolPrefix(snNetwork.ProtocolID()),
dht.BootstrapPeers(addrInfos...),
dht.RoutingTableRefreshPeriod(routingTableRefreshPeriod),
dht.Mode(dht.ModeServer),
)
}
func privateKey(privKeyStr string) (crypto.PrivKey, error) {
if privKeyStr == "" {
// Creates a new key pair for this host.
prvKey, _, _, err := GenKeyPair()
if err != nil {
return nil, err
}
return prvKey, nil
}
privKeyBytes, err := hex.DecodeString(privKeyStr)
if err != nil {
return nil, err
}
privKeyBytesPB, err := proto.Marshal(&pb.PrivateKey{
Type: utils.Ptr(pb.KeyType_Ed25519),
Data: privKeyBytes,
})
if err != nil {
return nil, err
}
prvKey, err := crypto.UnmarshalPrivateKey(privKeyBytesPB)
if err != nil {
return nil, fmt.Errorf("failed to unmarslah private key: %w", err)
}
return prvKey, nil
}
func (s *Service) SubscribePeerConnectednessChanged(ctx context.Context) (<-chan event.EvtPeerConnectednessChanged, error) {
ch := make(chan event.EvtPeerConnectednessChanged)
sub, err := s.host.EventBus().Subscribe(&event.EvtPeerConnectednessChanged{})
if err != nil {
return nil, err
}
go func() {
for {
select {
case <-ctx.Done():
if err = sub.Close(); err != nil {
s.log.Warnw("Failed to close subscription", "err", err)
}
close(ch)
return
case evnt := <-sub.Out():
typedEvnt := evnt.(event.EvtPeerConnectednessChanged)
if typedEvnt.Connectedness == network.Connected {
ch <- typedEvnt
}
}
}
}()
return ch, nil
}
// Run starts the p2p service. Calling any other function before run is undefined behaviour
func (s *Service) Run(ctx context.Context) error {
defer s.host.Close()
err := s.dht.Bootstrap(ctx)
if err != nil {
return err
}
s.pubsub, err = pubsub.NewGossipSub(ctx, s.host)
if err != nil {
return err
}
defer s.callAndLogErr(s.dht.Close, "Failed stopping DHT")
listenAddrs, err := s.ListenAddrs()
if err != nil {
return err
}
for _, addr := range listenAddrs {
s.log.Infow("Listening on", "addr", addr)
}
s.setProtocolHandlers()
if !s.feederNode {
s.synchroniser.start(ctx)
}
<-ctx.Done()
if err := s.dht.Close(); err != nil {
s.log.Warnw("Failed stopping DHT", "err", err.Error())
}
return s.host.Close()
}
func (s *Service) setProtocolHandlers() {
s.SetProtocolHandler(starknet.BlockHeadersPID(s.network), s.handler.BlockHeadersHandler)
s.SetProtocolHandler(starknet.CurrentBlockHeaderPID(s.network), s.handler.CurrentBlockHeaderHandler)
s.SetProtocolHandler(starknet.ReceiptsPID(s.network), s.handler.ReceiptsHandler)
// todo discuss protocol id (should it be included in BlockHeadersPID)
s.SetProtocolHandler(starknet.BlockBodiesPID(s.network), s.handler.BlockBodiesHandler)
s.SetProtocolHandler(starknet.EventsPID(s.network), s.handler.EventsHandler)
s.SetProtocolHandler(starknet.TransactionsPID(s.network), s.handler.TransactionsHandler)
}
func (s *Service) callAndLogErr(f func() error, msg string) {
err := f()
if err != nil {
s.log.Warnw(msg, "err", err.Error())
}
}
func (s *Service) ListenAddrs() ([]multiaddr.Multiaddr, error) {
pidmhash, err := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", s.host.ID()))
if err != nil {
return nil, err
}
var listenAddrs []multiaddr.Multiaddr
for _, addr := range s.host.Addrs() {
listenAddrs = append(listenAddrs, addr.Encapsulate(pidmhash))
}
return listenAddrs, nil
}
// NewStream creates a bidirectional connection to a random peer that implements a set of protocol ids
func (s *Service) NewStream(ctx context.Context, pids ...protocol.ID) (network.Stream, error) {
peers := s.host.Peerstore().Peers()
peersCount := peers.Len()
if peersCount <= 0 {
return nil, errors.New("no peers")
}
randomPeerIdx := rand.Intn(peersCount) //nolint: gosec
for peerIdx := (randomPeerIdx + 1) % peersCount; ; peerIdx = (peerIdx + 1) % peersCount {
peerID := peers[peerIdx]
if peerID != s.host.ID() {
stream, err := s.host.NewStream(ctx, peerID, pids...)
if err == nil {
return stream, nil
} else if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
}
if peerIdx == randomPeerIdx {
return nil, fmt.Errorf("no reachable peers supporting %s", protocol.ConvertToStrings(pids))
}
}
}
func (s *Service) joinTopic(topic string) (*pubsub.Topic, error) {
existingTopic := func() *pubsub.Topic {
s.topicsLock.RLock()
defer s.topicsLock.RUnlock()
if t, found := s.topics[topic]; found {
return t
}
return nil
}()
if existingTopic != nil {
return existingTopic, nil
}
newTopic, err := s.pubsub.Join(topic)
if err != nil {
return nil, err
}
s.topicsLock.Lock()
defer s.topicsLock.Unlock()
s.topics[topic] = newTopic
return newTopic, nil
}
func (s *Service) SubscribeToTopic(topic string) (chan []byte, func(), error) {
t, joinErr := s.joinTopic(topic)
if joinErr != nil {
return nil, nil, joinErr
}
sub, subErr := t.Subscribe()
if subErr != nil {
return nil, nil, subErr
}
const bufferSize = 16
ch := make(chan []byte, bufferSize)
// go func() {
// for {
// msg, err := sub.Next(s.runCtx)
// if err != nil {
// close(ch)
// return
// }
// only forward messages delivered by others
// if msg.ReceivedFrom == s.host.ID() {
// continue
// }
//
// select {
// case ch <- msg.GetData():
// case <-s.runCtx.Done():
// }
// }
// }()
return ch, sub.Cancel, nil
}
func (s *Service) PublishOnTopic(topic string) error {
t, joinErr := s.joinTopic(topic)
if joinErr != nil {
return joinErr
}
_ = t
return nil
}
func (s *Service) SetProtocolHandler(pid protocol.ID, handler func(network.Stream)) {
s.host.SetStreamHandler(pid, handler)
}
func (s *Service) WithListener(l junoSync.EventListener) {
runMetrics(s.host.Peerstore())
s.synchroniser.WithListener(l)
}