-
Notifications
You must be signed in to change notification settings - Fork 6
/
p2p.go
560 lines (520 loc) · 15.1 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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package p2p
import (
"context"
"crypto/sha1"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"math/rand"
"time"
"github.com/pkg/errors"
"golang.org/x/time/rate"
lru "github.com/hashicorp/golang-lru"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p"
relay "github.com/libp2p/go-libp2p-circuit"
connmgr "github.com/libp2p/go-libp2p-connmgr"
crypto "github.com/libp2p/go-libp2p-crypto"
discovery "github.com/libp2p/go-libp2p-discovery"
host "github.com/libp2p/go-libp2p-host"
dht "github.com/libp2p/go-libp2p-kad-dht"
net "github.com/libp2p/go-libp2p-net"
peer "github.com/libp2p/go-libp2p-peer"
peerstore "github.com/libp2p/go-libp2p-peerstore"
protocol "github.com/libp2p/go-libp2p-protocol"
pubsub "github.com/libp2p/go-libp2p-pubsub"
stream "github.com/libp2p/go-libp2p-transport-upgrader"
"github.com/libp2p/go-tcp-transport"
"github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multihash"
sm_yamux "github.com/whyrusleeping/go-smux-yamux"
"go.uber.org/zap"
)
// HandleBroadcast defines the callback function triggered when a broadcast message reaches a host
type HandleBroadcast func(ctx context.Context, data []byte) error
// HandleUnicast defines the callback function triggered when a unicast message reaches a host
type HandleUnicast func(ctx context.Context, w io.Writer, data []byte) error
// Config enumerates the configs required by a host
type Config struct {
HostName string
Port int
ExternalHostName string
ExternalPort int
SecureIO bool
Gossip bool
ConnectTimeout time.Duration
MasterKey string
Relay string // could be `active`, `nat`, `disable`
ConnLowWater int
ConnHighWater int
RateLimiterLRUSize int
BlackListLRUSize int
BlackListCleanupInterval time.Duration
AvgNumMsgsPerSec int
BurstNumMsgsPerSec int
ConnGracePeriod time.Duration
RateLimit bool
}
// DefaultConfig is a set of default configs
var DefaultConfig = Config{
HostName: "127.0.0.1",
Port: 30001,
ExternalHostName: "",
ExternalPort: 30001,
SecureIO: false,
Gossip: false,
ConnectTimeout: time.Minute,
MasterKey: "",
Relay: "disable",
ConnLowWater: 200,
ConnHighWater: 500,
RateLimiterLRUSize: 1000,
BlackListLRUSize: 1000,
BlackListCleanupInterval: 600 * time.Second,
AvgNumMsgsPerSec: 300,
BurstNumMsgsPerSec: 500,
ConnGracePeriod: 0,
RateLimit: false,
}
// Option defines the option function to modify the config for a host
type Option func(cfg *Config) error
// HostName is the option to override the host name or IP address
func HostName(hostName string) Option {
return func(cfg *Config) error {
cfg.HostName = hostName
return nil
}
}
// Port is the option to override the port number
func Port(port int) Option {
return func(cfg *Config) error {
cfg.Port = port
return nil
}
}
// ExternalHostName is the option to set the host name or IP address seen from external
func ExternalHostName(externalHostName string) Option {
return func(cfg *Config) error {
cfg.ExternalHostName = externalHostName
return nil
}
}
// ExternalPort is the option to set the port number seen from external
func ExternalPort(externalPort int) Option {
return func(cfg *Config) error {
cfg.ExternalPort = externalPort
return nil
}
}
// SecureIO is to indicate using secured I/O
func SecureIO() Option {
return func(cfg *Config) error {
cfg.SecureIO = true
return nil
}
}
// Gossip is to indicate using gossip protocol
func Gossip() Option {
return func(cfg *Config) error {
cfg.Gossip = true
return nil
}
}
// ConnectTimeout is the option to override the connect timeout
func ConnectTimeout(timout time.Duration) Option {
return func(cfg *Config) error {
cfg.ConnectTimeout = timout
return nil
}
}
// MasterKey is to determine network identifier
func MasterKey(masterKey string) Option {
return func(cfg *Config) error {
cfg.MasterKey = masterKey
return nil
}
}
// RateLimit is to indicate limiting msg rate from peers
func RateLimit() Option {
return func(cfg *Config) error {
cfg.RateLimit = true
return nil
}
}
// WithRelay config relay option.
func WithRelay(relayType string) Option {
return func(cfg *Config) error {
cfg.Relay = relayType
return nil
}
}
// WithConnectionManagerConfig set configuration for connection manager.
func WithConnectionManagerConfig(lo, hi int, grace time.Duration) Option {
return func(cfg *Config) error {
cfg.ConnLowWater = lo
cfg.ConnHighWater = hi
cfg.ConnGracePeriod = grace
return nil
}
}
// Host is the main struct that represents a host that communicating with the rest of the P2P networks
type Host struct {
host host.Host
cfg Config
topics map[string]interface{}
kad *dht.IpfsDHT
kadKey cid.Cid
newPubSub func(ctx context.Context, h host.Host, opts ...pubsub.Option) (*pubsub.PubSub, error)
pubs map[string]*pubsub.PubSub
blacklists map[string]*LRUBlacklist
subs map[string]*pubsub.Subscription
close chan interface{}
ctx context.Context
limiters *lru.Cache
}
// NewHost constructs a host struct
func NewHost(ctx context.Context, options ...Option) (*Host, error) {
cfg := DefaultConfig
for _, option := range options {
if err := option(&cfg); err != nil {
return nil, err
}
}
ip, err := EnsureIPv4(cfg.HostName)
if err != nil {
return nil, err
}
masterKey := cfg.MasterKey
// If ID is not given use network address instead
if masterKey == "" {
masterKey = fmt.Sprintf("%s:%d", ip, cfg.Port)
}
sk, _, err := generateKeyPair(masterKey)
if err != nil {
return nil, err
}
var extMultiAddr multiaddr.Multiaddr
// Set external address and replace private key it external host name is given
if cfg.ExternalHostName != "" {
extIP, err := EnsureIPv4(cfg.ExternalHostName)
if err != nil {
return nil, err
}
masterKey := cfg.MasterKey
// If ID is not given use network address instead
if masterKey == "" {
masterKey = fmt.Sprintf("%s:%d", cfg.ExternalHostName, cfg.ExternalPort)
}
sk, _, err = generateKeyPair(masterKey)
if err != nil {
return nil, err
}
extMultiAddr, err = multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", extIP, cfg.ExternalPort))
if err != nil {
return nil, err
}
}
opts := []libp2p.Option{
libp2p.ListenAddrStrings(fmt.Sprintf("/ip4/%s/tcp/%d", ip, cfg.Port)),
libp2p.AddrsFactory(func(addrs []multiaddr.Multiaddr) []multiaddr.Multiaddr {
if extMultiAddr != nil {
return append(addrs, extMultiAddr)
}
return addrs
}),
libp2p.Identity(sk),
libp2p.Transport(func(upgrader *stream.Upgrader) *tcp.TcpTransport {
return &tcp.TcpTransport{Upgrader: upgrader, ConnectTimeout: cfg.ConnectTimeout}
}),
libp2p.Muxer("/yamux/2.0.0", sm_yamux.DefaultTransport),
libp2p.ConnectionManager(connmgr.NewConnManager(cfg.ConnLowWater, cfg.ConnHighWater, cfg.ConnGracePeriod)),
}
if !cfg.SecureIO {
opts = append(opts, libp2p.NoSecurity)
}
// relay option
if cfg.Relay == "active" {
opts = append(opts, libp2p.EnableRelay(relay.OptActive, relay.OptHop))
} else if cfg.Relay == "nat" {
opts = append(opts, libp2p.EnableRelay(), libp2p.NATPortMap())
} else {
opts = append(opts, libp2p.DisableRelay())
}
host, err := libp2p.New(ctx, opts...)
if err != nil {
return nil, err
}
kad, err := dht.New(ctx, host)
if err != nil {
}
if err := kad.Bootstrap(ctx); err != nil {
return nil, err
}
newPubSub := pubsub.NewFloodSub
if cfg.Gossip {
newPubSub = pubsub.NewGossipSub
}
v1b := cid.V1Builder{Codec: cid.Raw, MhType: multihash.SHA2_256}
cid, err := v1b.Sum([]byte(masterKey))
if err != nil {
return nil, err
}
limiters, err := lru.New(cfg.RateLimiterLRUSize)
if err != nil {
return nil, err
}
myHost := Host{
host: host,
cfg: cfg,
topics: make(map[string]interface{}),
kad: kad,
kadKey: cid,
newPubSub: newPubSub,
pubs: make(map[string]*pubsub.PubSub),
blacklists: make(map[string]*LRUBlacklist),
subs: make(map[string]*pubsub.Subscription),
close: make(chan interface{}),
ctx: ctx,
limiters: limiters,
}
addrs := make([]string, 0)
for _, ma := range myHost.Addresses() {
addrs = append(addrs, ma.String())
}
Logger().Info("P2p host started.",
zap.Strings("address", addrs),
zap.Bool("secureIO", myHost.cfg.SecureIO),
zap.Bool("gossip", myHost.cfg.Gossip))
return &myHost, nil
}
// JoinOverlay triggers the host to join the DHT overlay
func (h *Host) JoinOverlay(ctx context.Context) {
routingDiscovery := discovery.NewRoutingDiscovery(h.kad)
discovery.Advertise(ctx, routingDiscovery, h.kadKey.String())
}
// AddUnicastPubSub adds a unicast topic that the host will pay attention to
func (h *Host) AddUnicastPubSub(topic string, callback HandleUnicast) error {
if _, ok := h.topics[topic]; ok {
return nil
}
h.host.SetStreamHandler(protocol.ID(topic), func(stream net.Stream) {
defer func() {
if err := stream.Close(); err != nil {
Logger().Error("Error when closing a unicast stream.", zap.Error(err))
}
}()
/*
src := stream.Conn().RemotePeer()
allowed, err := h.allowSource(src)
if err != nil {
Logger().Error("Error when checking if the source is allowed.", zap.Error(err))
return
}
if !allowed {
// TODO: blacklist src for unicast too
return
}
*/
data, err := ioutil.ReadAll(stream)
if err != nil {
Logger().Error("Error when subscribing a unicast message.", zap.Error(err))
return
}
ctx := context.WithValue(context.Background(), unicastCtxKey{}, stream)
if err := callback(ctx, stream, data); err != nil {
Logger().Error("Error when processing a unicast message.", zap.Error(err))
}
})
h.topics[topic] = nil
return nil
}
// AddBroadcastPubSub adds a broadcast topic that the host will pay attention to. This need to be called before using
// Connect/JoinOverlay. Otherwise, pubsub may not be aware of the existing overlay topology
func (h *Host) AddBroadcastPubSub(topic string, callback HandleBroadcast) error {
if _, ok := h.pubs[topic]; ok {
return nil
}
blacklist, err := NewLRUBlacklist(h.cfg.BlackListLRUSize)
if err != nil {
return err
}
pub, err := h.newPubSub(
h.ctx,
h.host,
pubsub.WithMessageSigning(true),
pubsub.WithStrictSignatureVerification(true),
pubsub.WithBlacklist(blacklist),
)
if err != nil {
return err
}
sub, err := pub.Subscribe(topic)
if err != nil {
return err
}
h.pubs[topic] = pub
h.blacklists[topic] = blacklist
h.subs[topic] = sub
go func() {
for {
select {
case <-h.close:
return
default:
ctx := context.Background()
msg, err := sub.Next(ctx)
if err != nil {
Logger().Error("Error when subscribing a broadcast message.", zap.Error(err))
continue
}
src := msg.GetFrom()
allowed, err := h.allowSource(src)
if err != nil {
Logger().Error("Error when checking if the source is allowed.", zap.Error(err))
continue
}
if !allowed {
h.blacklists[topic].Add(src)
Logger().Warn("Blacklist a peer", zap.Any("id", src))
continue
}
h.blacklists[topic].Remove(src)
ctx = context.WithValue(ctx, broadcastCtxKey{}, msg)
if err := callback(ctx, msg.Data); err != nil {
Logger().Error("Error when processing a broadcast message.", zap.Error(err))
}
}
}
}()
go func() {
for {
time.Sleep(h.cfg.BlackListCleanupInterval)
h.blacklists[topic].RemoveOldest()
}
}()
return nil
}
// ConnectWithMultiaddr connects a peer given the multi address
func (h *Host) ConnectWithMultiaddr(ctx context.Context, ma multiaddr.Multiaddr) error {
target, err := peerstore.InfoFromP2pAddr(ma)
if err != nil {
return err
}
if err := h.host.Connect(ctx, *target); err != nil {
return err
}
Logger().Debug(
"P2P peer connected.",
zap.String("multiAddress", ma.String()),
)
return nil
}
// Connect connects a peer.
func (h *Host) Connect(ctx context.Context, target peerstore.PeerInfo) error {
if err := h.host.Connect(ctx, target); err != nil {
return err
}
Logger().Debug(
"P2P peer connected.",
zap.String("peer", fmt.Sprintf("%+v", target)),
)
return nil
}
// Broadcast sends a message to the hosts who subscribe the topic
func (h *Host) Broadcast(topic string, data []byte) error {
pub, ok := h.pubs[topic]
if !ok {
return nil
}
return pub.Publish(topic, data)
}
// Unicast sends a message to a peer on the given address
func (h *Host) Unicast(ctx context.Context, target peerstore.PeerInfo, topic string, data []byte) error {
if err := h.Connect(ctx, target); err != nil {
return err
}
stream, err := h.host.NewStream(ctx, target.ID, protocol.ID(topic))
if err != nil {
return err
}
defer func() { err = stream.Close() }()
if _, err = stream.Write(data); err != nil {
return err
}
return nil
}
// HostIdentity returns the host identity string
func (h *Host) HostIdentity() string { return h.host.ID().Pretty() }
// OverlayIdentity returns the overlay identity string
func (h *Host) OverlayIdentity() string { return h.kadKey.String() }
// Addresses returns the multi address
func (h *Host) Addresses() []multiaddr.Multiaddr {
hostID, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ipfs/%s", h.HostIdentity()))
addrs := make([]multiaddr.Multiaddr, 0)
for _, addr := range h.host.Addrs() {
addrs = append(addrs, addr.Encapsulate(hostID))
}
return addrs
}
// Info returns host's perr info.
func (h *Host) Info() peerstore.PeerInfo {
return peerstore.PeerInfo{ID: h.host.ID(), Addrs: h.host.Addrs()}
}
// Neighbors returns the closest peer addresses
func (h *Host) Neighbors(ctx context.Context) ([]peerstore.PeerInfo, error) {
peers := h.host.Peerstore().Peers()
dedupedPeers := make(map[string]peer.ID)
for _, p := range peers {
idStr := p.Pretty()
if idStr == h.host.ID().Pretty() || idStr == "" {
continue
}
dedupedPeers[idStr] = p
}
neighbors := make([]peerstore.PeerInfo, 0)
for _, p := range dedupedPeers {
neighbors = append(neighbors, h.kad.FindLocal(p))
}
return neighbors, nil
}
// Close closes the host
func (h *Host) Close() error {
close(h.close)
for _, sub := range h.subs {
sub.Cancel()
}
if err := h.kad.Close(); err != nil {
return err
}
if err := h.host.Close(); err != nil {
return err
}
return nil
}
func (h *Host) allowSource(src peer.ID) (bool, error) {
if !h.cfg.RateLimit {
return true, nil
}
var limiter *rate.Limiter
val, ok := h.limiters.Get(src)
if ok {
limiter, ok = val.(*rate.Limiter)
if !ok {
return false, errors.New("error when casting to limiter struct")
}
} else {
limiter = rate.NewLimiter(rate.Limit(h.cfg.AvgNumMsgsPerSec), h.cfg.BurstNumMsgsPerSec)
h.limiters.Add(src, limiter)
}
return limiter.Allow(), nil
}
// generateKeyPair generates the public key and private key by network address
func generateKeyPair(masterKey string) (crypto.PrivKey, crypto.PubKey, error) {
hash := sha1.Sum([]byte(masterKey))
seedBytes := hash[12:]
seedBytes[0] = 0
seed := int64(binary.BigEndian.Uint64(seedBytes))
r := rand.New(rand.NewSource(seed))
return crypto.GenerateKeyPairWithReader(crypto.Ed25519, 2048, r)
}