pubsub.go 33.3 KB
Newer Older
Steven Allen's avatar
Steven Allen committed
1
package pubsub
2 3 4 5

import (
	"context"
	"encoding/binary"
6
	"errors"
7
	"fmt"
vyzo's avatar
vyzo committed
8
	"math/rand"
9
	"sync"
10 11 12
	"sync/atomic"
	"time"

Steven Allen's avatar
Steven Allen committed
13
	pb "github.com/libp2p/go-libp2p-pubsub/pb"
14

15
	"github.com/libp2p/go-libp2p-core/crypto"
16
	"github.com/libp2p/go-libp2p-core/discovery"
17 18 19 20 21
	"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"

Kevin Atkinson's avatar
Kevin Atkinson committed
22 23
	logging "github.com/ipfs/go-log"
	timecache "github.com/whyrusleeping/timecache"
24 25
)

26 27 28
// DefaultMaximumMessageSize is 1mb.
const DefaultMaxMessageSize = 1 << 20

vyzo's avatar
vyzo committed
29 30
var (
	TimeCacheDuration = 120 * time.Second
31 32 33

	// ErrSubscriptionCancelled may be returned when a subscription Next() is called after the
	// subscription has been cancelled.
Preston Van Loon's avatar
Preston Van Loon committed
34
	ErrSubscriptionCancelled = errors.New("subscription cancelled")
vyzo's avatar
vyzo committed
35 36
)

37 38
var log = logging.Logger("pubsub")

vyzo's avatar
vyzo committed
39
// PubSub is the implementation of the pubsub system.
40
type PubSub struct {
41 42 43 44 45 46 47
	// atomic counter for seqnos
	// NOTE: Must be declared at the top of the struct as we perform atomic
	// operations on this field.
	//
	// See: https://golang.org/pkg/sync/atomic/#pkg-note-BUG
	counter uint64

48 49 50 51
	host host.Host

	rt PubSubRouter

vyzo's avatar
vyzo committed
52 53
	val *validation

54 55
	disc *discover

vyzo's avatar
vyzo committed
56 57
	tracer *pubsubTracer

58 59 60 61
	// maxMessageSize is the maximum message size; it applies globally to all
	// topics.
	maxMessageSize int

62 63 64
	// size of the outbound message channel that we maintain for each peer
	peerOutboundQueueSize int

65 66 67 68 69 70
	// incoming messages from other peers
	incoming chan *RPC

	// addSub is a control channel for us to add and remove subscriptions
	addSub chan *addSubReq

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
71 72 73
	// addRelay is a control channel for us to add and remove relays
	addRelay chan *addRelayReq

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
74 75 76
	// rmRelay is a relay cancellation channel
	rmRelay chan string

77 78 79 80 81 82 83 84 85
	// get list of topics we are subscribed to
	getTopics chan *topicReq

	// get chan of peers we are connected to
	getPeers chan *listPeerReq

	// send subscription here to cancel it
	cancelCh chan *Subscription

86 87 88 89 90 91
	// addSub is a channel for us to add a topic
	addTopic chan *addTopicReq

	// removeTopic is a topic cancellation channel
	rmTopic chan *rmTopicReq

92 93 94 95
	// a notification channel for new peer connections
	newPeers chan peer.ID

	// a notification channel for new outoging peer streams
96
	newPeerStream chan network.Stream
97 98 99

	// a notification channel for errors opening new peer streams
	newPeerError chan peer.ID
100 101 102 103 104

	// a notification channel for when our peers die
	peerDead chan peer.ID

	// The set of topics we are subscribed to
105 106
	mySubs map[string]map[*Subscription]struct{}

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
107 108 109
	// The set of topics we are relaying for
	myRelays map[string]int

110 111
	// The set of topics we are interested in
	myTopics map[string]*Topic
112 113 114 115 116

	// topics tracks which topics each of our peers are subscribed to
	topics map[string]map[peer.ID]struct{}

	// sendMsg handles messages that have been validated
117
	sendMsg chan *Message
118 119 120 121

	// addVal handles validator registration requests
	addVal chan *addValReq

122 123 124
	// rmVal handles validator unregistration requests
	rmVal chan *rmValReq

vyzo's avatar
vyzo committed
125 126 127
	// eval thunk in event loop
	eval chan func()

vyzo's avatar
vyzo committed
128
	// peer blacklist
vyzo's avatar
vyzo committed
129
	blacklist     Blacklist
vyzo's avatar
vyzo committed
130 131
	blacklistPeer chan peer.ID

132 133
	peers map[peer.ID]chan *RPC

vyzo's avatar
vyzo committed
134 135 136
	inboundStreamsMx sync.Mutex
	inboundStreams   map[peer.ID]network.Stream

137 138
	seenMessagesMx sync.Mutex
	seenMessages   *timecache.TimeCache
139

140 141 142
	// function used to compute the ID for a message
	msgID MsgIdFunction

143
	// key for signing messages; nil when signing is disabled
144
	signKey crypto.PrivKey
145 146
	// source ID for signed messages; corresponds to signKey, empty when signing is disabled.
	// If empty, the author and seq-nr are completely omitted from the messages.
147
	signID peer.ID
vyzo's avatar
vyzo committed
148
	// strict mode rejects all unsigned messages prior to validation
149
	signPolicy MessageSignaturePolicy
150

vyzo's avatar
vyzo committed
151 152 153
	// filter for tracking subscriptions in topics of interest; if nil, then we track all subscriptions
	subFilter SubscriptionFilter

154 155 156
	ctx context.Context
}

vyzo's avatar
vyzo committed
157
// PubSubRouter is the message router component of PubSub.
158
type PubSubRouter interface {
vyzo's avatar
vyzo committed
159
	// Protocols returns the list of protocols supported by the router.
160
	Protocols() []protocol.ID
vyzo's avatar
vyzo committed
161 162
	// Attach is invoked by the PubSub constructor to attach the router to a
	// freshly initialized PubSub instance.
163
	Attach(*PubSub)
vyzo's avatar
vyzo committed
164
	// AddPeer notifies the router that a new peer has been connected.
165
	AddPeer(peer.ID, protocol.ID)
vyzo's avatar
vyzo committed
166
	// RemovePeer notifies the router that a peer has been disconnected.
167
	RemovePeer(peer.ID)
168 169 170
	// EnoughPeers returns whether the router needs more peers before it's ready to publish new records.
	// Suggested (if greater than 0) is a suggested number of peers that the router should need.
	EnoughPeers(topic string, suggested int) bool
171 172
	// AcceptFrom is invoked on any incoming message before pushing it to the validation pipeline
	// or processing control information.
Yusef Napora's avatar
Yusef Napora committed
173
	// Allows routers with internal scoring to vet peers before committing any processing resources
vyzo's avatar
vyzo committed
174 175
	// to the message and implement an effective graylist and react to validation queue overload.
	AcceptFrom(peer.ID) AcceptStatus
vyzo's avatar
vyzo committed
176 177
	// HandleRPC is invoked to process control messages in the RPC envelope.
	// It is invoked after subscriptions and payload messages have been processed.
vyzo's avatar
vyzo committed
178
	HandleRPC(*RPC)
vyzo's avatar
vyzo committed
179
	// Publish is invoked to forward a new message that has been validated.
180
	Publish(*Message)
vyzo's avatar
vyzo committed
181 182
	// Join notifies the router that we want to receive and forward messages in a topic.
	// It is invoked after the subscription announcement.
183
	Join(topic string)
vyzo's avatar
vyzo committed
184 185
	// Leave notifies the router that we are no longer interested in a topic.
	// It is invoked after the unsubscription announcement.
186
	Leave(topic string)
187 188
}

vyzo's avatar
vyzo committed
189 190 191 192 193
type AcceptStatus int

const (
	// AcceptAll signals to accept the incoming RPC for full processing
	AcceptNone AcceptStatus = iota
vyzo's avatar
vyzo committed
194 195
	// AcceptControl signals to accept the incoming RPC only for control message processing by
	// the router. Included payload messages will _not_ be pushed to the validation queue.
vyzo's avatar
vyzo committed
196 197 198 199 200
	AcceptControl
	// AcceptNone signals to drop the incoming RPC
	AcceptAll
)

201 202
type Message struct {
	*pb.Message
Piotr Dyraga's avatar
Piotr Dyraga committed
203
	ReceivedFrom  peer.ID
204
	ValidatorData interface{}
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
}

func (m *Message) GetFrom() peer.ID {
	return peer.ID(m.Message.GetFrom())
}

type RPC struct {
	pb.RPC

	// unexported on purpose, not sending this over the wire
	from peer.ID
}

type Option func(*PubSub) error

vyzo's avatar
vyzo committed
220
// NewPubSub returns a new PubSub management object.
221 222
func NewPubSub(ctx context.Context, h host.Host, rt PubSubRouter, opts ...Option) (*PubSub, error) {
	ps := &PubSub{
223 224 225 226 227
		host:                  h,
		ctx:                   ctx,
		rt:                    rt,
		val:                   newValidation(),
		disc:                  &discover{},
228
		maxMessageSize:        DefaultMaxMessageSize,
229 230
		peerOutboundQueueSize: 32,
		signID:                h.ID(),
231 232
		signKey:               nil,
		signPolicy:            StrictSign,
233 234 235 236 237 238 239 240
		incoming:              make(chan *RPC, 32),
		newPeers:              make(chan peer.ID),
		newPeerStream:         make(chan network.Stream),
		newPeerError:          make(chan peer.ID),
		peerDead:              make(chan peer.ID),
		cancelCh:              make(chan *Subscription),
		getPeers:              make(chan *listPeerReq),
		addSub:                make(chan *addSubReq),
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
241
		addRelay:              make(chan *addRelayReq),
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
242
		rmRelay:               make(chan string),
243 244 245 246 247 248 249 250 251
		addTopic:              make(chan *addTopicReq),
		rmTopic:               make(chan *rmTopicReq),
		getTopics:             make(chan *topicReq),
		sendMsg:               make(chan *Message, 32),
		addVal:                make(chan *addValReq),
		rmVal:                 make(chan *rmValReq),
		eval:                  make(chan func()),
		myTopics:              make(map[string]*Topic),
		mySubs:                make(map[string]map[*Subscription]struct{}),
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
252
		myRelays:              make(map[string]int),
253 254
		topics:                make(map[string]map[peer.ID]struct{}),
		peers:                 make(map[peer.ID]chan *RPC),
vyzo's avatar
vyzo committed
255
		inboundStreams:        make(map[peer.ID]network.Stream),
256 257 258
		blacklist:             NewMapBlacklist(),
		blacklistPeer:         make(chan peer.ID),
		seenMessages:          timecache.NewTimeCache(TimeCacheDuration),
259
		msgID:                 DefaultMsgIdFn,
260
		counter:               uint64(time.Now().UnixNano()),
261 262 263 264 265 266 267 268 269
	}

	for _, opt := range opts {
		err := opt(ps)
		if err != nil {
			return nil, err
		}
	}

270 271 272 273 274 275 276 277
	if ps.signPolicy.mustSign() {
		if ps.signID == "" {
			return nil, fmt.Errorf("strict signature usage enabled but message author was disabled")
		}
		ps.signKey = ps.host.Peerstore().PrivKey(ps.signID)
		if ps.signKey == nil {
			return nil, fmt.Errorf("can't sign for peer %s: no private key", ps.signID)
		}
278 279
	}

280 281 282 283
	if err := ps.disc.Start(ps); err != nil {
		return nil, err
	}

284 285 286 287 288 289 290
	rt.Attach(ps)

	for _, id := range rt.Protocols() {
		h.SetStreamHandler(id, ps.handleNewStream)
	}
	h.Network().Notify((*PubSubNotif)(ps))

vyzo's avatar
vyzo committed
291
	ps.val.Start(ps)
292

vyzo's avatar
vyzo committed
293
	go ps.processLoop(ctx)
294

295 296
	(*PubSubNotif)(ps).Initialize()

297 298 299
	return ps, nil
}

300 301 302 303 304 305 306 307 308 309
// MsgIdFunction returns a unique ID for the passed Message, and PubSub can be customized to use any
// implementation of this function by configuring it with the Option from WithMessageIdFn.
type MsgIdFunction func(pmsg *pb.Message) string

// WithMessageIdFn is an option to customize the way a message ID is computed for a pubsub message.
// The default ID function is DefaultMsgIdFn (concatenate source and seq nr.),
// but it can be customized to e.g. the hash of the message.
func WithMessageIdFn(fn MsgIdFunction) Option {
	return func(p *PubSub) error {
		p.msgID = fn
310 311 312 313
		// the tracer Option may already be set. Update its message ID function to make options order-independent.
		if p.tracer != nil {
			p.tracer.msgID = fn
		}
314 315 316 317
		return nil
	}
}

318 319 320 321
// WithPeerOutboundQueueSize is an option to set the buffer size for outbound messages to a peer
// We start dropping messages to a peer if the outbound queue if full
func WithPeerOutboundQueueSize(size int) Option {
	return func(p *PubSub) error {
322 323
		if size <= 0 {
			return errors.New("outbound queue size must always be positive")
324 325 326 327 328 329
		}
		p.peerOutboundQueueSize = size
		return nil
	}
}

330 331 332 333 334 335 336 337
// WithMessageSignaturePolicy sets the mode of operation for producing and verifying message signatures.
func WithMessageSignaturePolicy(policy MessageSignaturePolicy) Option {
	return func(p *PubSub) error {
		p.signPolicy = policy
		return nil
	}
}

Steven Allen's avatar
Steven Allen committed
338
// WithMessageSigning enables or disables message signing (enabled by default).
339 340
// Deprecated: signature verification without message signing,
// or message signing without verification, are not recommended.
Steven Allen's avatar
Steven Allen committed
341
func WithMessageSigning(enabled bool) Option {
vyzo's avatar
vyzo committed
342
	return func(p *PubSub) error {
Steven Allen's avatar
Steven Allen committed
343
		if enabled {
344
			p.signPolicy |= msgSigning
Steven Allen's avatar
Steven Allen committed
345
		} else {
346
			p.signPolicy &^= msgSigning
Steven Allen's avatar
Steven Allen committed
347 348 349 350 351 352 353 354 355 356
		}
		return nil
	}
}

// WithMessageAuthor sets the author for outbound messages to the given peer ID
// (defaults to the host's ID). If message signing is enabled, the private key
// must be available in the host's peerstore.
func WithMessageAuthor(author peer.ID) Option {
	return func(p *PubSub) error {
vyzo's avatar
vyzo committed
357
		author := author
Steven Allen's avatar
Steven Allen committed
358 359 360 361 362 363 364 365
		if author == "" {
			author = p.host.ID()
		}
		p.signID = author
		return nil
	}
}

366 367 368 369 370 371 372 373 374 375
// WithNoAuthor omits the author and seq-number data of messages, and disables the use of signatures.
// Not recommended to use with the default message ID function, see WithMessageIdFn.
func WithNoAuthor() Option {
	return func(p *PubSub) error {
		p.signID = ""
		p.signPolicy &^= msgSigning
		return nil
	}
}

vyzo's avatar
vyzo committed
376 377
// WithStrictSignatureVerification is an option to enable or disable strict message signing.
// When enabled (which is the default), unsigned messages will be discarded.
378 379
// Deprecated: signature verification without message signing,
// or message signing without verification, are not recommended.
Steven Allen's avatar
Steven Allen committed
380 381
func WithStrictSignatureVerification(required bool) Option {
	return func(p *PubSub) error {
382 383 384 385 386
		if required {
			p.signPolicy |= msgVerification
		} else {
			p.signPolicy &^= msgVerification
		}
vyzo's avatar
vyzo committed
387 388 389 390
		return nil
	}
}

vyzo's avatar
vyzo committed
391 392 393 394 395 396 397 398 399
// WithBlacklist provides an implementation of the blacklist; the default is a
// MapBlacklist
func WithBlacklist(b Blacklist) Option {
	return func(p *PubSub) error {
		p.blacklist = b
		return nil
	}
}

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
// WithDiscovery provides a discovery mechanism used to bootstrap and provide peers into PubSub
func WithDiscovery(d discovery.Discovery, opts ...DiscoverOpt) Option {
	return func(p *PubSub) error {
		discoverOpts := defaultDiscoverOptions()
		for _, opt := range opts {
			err := opt(discoverOpts)
			if err != nil {
				return err
			}
		}

		p.disc.discovery = &pubSubDiscovery{Discovery: d, opts: discoverOpts.opts}
		p.disc.options = discoverOpts
		return nil
	}
}

vyzo's avatar
vyzo committed
417 418 419
// WithEventTracer provides a tracer for the pubsub system
func WithEventTracer(tracer EventTracer) Option {
	return func(p *PubSub) error {
vyzo's avatar
vyzo committed
420
		if p.tracer != nil {
vyzo's avatar
vyzo committed
421 422 423 424
			p.tracer.tracer = tracer
		} else {
			p.tracer = &pubsubTracer{tracer: tracer, pid: p.host.ID(), msgID: p.msgID}
		}
vyzo's avatar
vyzo committed
425 426 427 428
		return nil
	}
}

vyzo's avatar
vyzo committed
429 430 431
// WithRawTracer adds a raw tracer to the pubsub system.
// Multiple tracers can be added using multiple invocations of the option.
func WithRawTracer(tracer RawTracer) Option {
432 433
	return func(p *PubSub) error {
		if p.tracer != nil {
vyzo's avatar
vyzo committed
434
			p.tracer.raw = append(p.tracer.raw, tracer)
435
		} else {
vyzo's avatar
vyzo committed
436
			p.tracer = &pubsubTracer{raw: []RawTracer{tracer}, pid: p.host.ID(), msgID: p.msgID}
437 438 439 440 441
		}
		return nil
	}
}

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
// WithMaxMessageSize sets the global maximum message size for pubsub wire
// messages. The default value is 1MiB (DefaultMaxMessageSize).
//
// Observe the following warnings when setting this option.
//
// WARNING #1: Make sure to change the default protocol prefixes for floodsub
// (FloodSubID) and gossipsub (GossipSubID). This avoids accidentally joining
// the public default network, which uses the default max message size, and
// therefore will cause messages to be dropped.
//
// WARNING #2: Reducing the default max message limit is fine, if you are
// certain that your application messages will not exceed the new limit.
// However, be wary of increasing the limit, as pubsub networks are naturally
// write-amplifying, i.e. for every message we receive, we send D copies of the
// message to our peers. If those messages are large, the bandwidth requirements
// will grow linearly. Note that propagation is sent on the uplink, which
// traditionally is more constrained than the downlink. Instead, consider
// out-of-band retrieval for large messages, by sending a CID (Content-ID) or
// another type of locator, such that messages can be fetched on-demand, rather
// than being pushed proactively. Under this design, you'd use the pubsub layer
// as a signalling system, rather than a data delivery system.
func WithMaxMessageSize(maxMessageSize int) Option {
	return func(ps *PubSub) error {
		ps.maxMessageSize = maxMessageSize
		return nil
	}
}

470 471 472 473 474 475 476 477 478 479
// processLoop handles all inputs arriving on the channels
func (p *PubSub) processLoop(ctx context.Context) {
	defer func() {
		// Clean up go routines.
		for _, ch := range p.peers {
			close(ch)
		}
		p.peers = nil
		p.topics = nil
	}()
480

481 482
	for {
		select {
483
		case pid := <-p.newPeers:
vyzo's avatar
vyzo committed
484
			if _, ok := p.peers[pid]; ok {
Steven Allen's avatar
Steven Allen committed
485
				log.Debug("already have connection to peer: ", pid)
486
				continue
487 488
			}

vyzo's avatar
vyzo committed
489
			if p.blacklist.Contains(pid) {
vyzo's avatar
vyzo committed
490
				log.Warn("ignoring connection from blacklisted peer: ", pid)
491 492 493
				continue
			}

494
			messages := make(chan *RPC, p.peerOutboundQueueSize)
495
			messages <- p.getHelloPacket()
496
			go p.handleNewPeer(ctx, pid, messages)
497 498
			p.peers[pid] = messages

499 500 501
		case s := <-p.newPeerStream:
			pid := s.Conn().RemotePeer()

502
			ch, ok := p.peers[pid]
503
			if !ok {
vyzo's avatar
vyzo committed
504
				log.Warn("new stream for unknown peer: ", pid)
505 506 507 508
				s.Reset()
				continue
			}

vyzo's avatar
vyzo committed
509
			if p.blacklist.Contains(pid) {
vyzo's avatar
vyzo committed
510
				log.Warn("closing stream for blacklisted peer: ", pid)
511 512 513 514 515
				close(ch)
				s.Reset()
				continue
			}

516 517
			p.rt.AddPeer(pid, s.Protocol())

518 519 520
		case pid := <-p.newPeerError:
			delete(p.peers, pid)

521 522
		case pid := <-p.peerDead:
			ch, ok := p.peers[pid]
523 524 525 526
			if !ok {
				continue
			}

527 528
			close(ch)

529
			if p.host.Network().Connectedness(pid) == network.Connected {
530
				// still connected, must be a duplicate connection being closed.
531
				// we respawn the writer as we need to ensure there is a stream active
vyzo's avatar
vyzo committed
532
				log.Debugf("peer declared dead but still connected; respawning writer: %s", pid)
533
				messages := make(chan *RPC, p.peerOutboundQueueSize)
534
				messages <- p.getHelloPacket()
535 536
				go p.handleNewPeer(ctx, pid, messages)
				p.peers[pid] = messages
537
				continue
538 539 540
			}

			delete(p.peers, pid)
541
			for t, tmap := range p.topics {
542 543 544 545
				if _, ok := tmap[pid]; ok {
					delete(tmap, pid)
					p.notifyLeave(t, pid)
				}
546 547 548 549 550 551
			}

			p.rt.RemovePeer(pid)

		case treq := <-p.getTopics:
			var out []string
552
			for t := range p.mySubs {
553 554 555
				out = append(out, t)
			}
			treq.resp <- out
556 557 558 559
		case topic := <-p.addTopic:
			p.handleAddTopic(topic)
		case topic := <-p.rmTopic:
			p.handleRemoveTopic(topic)
560 561 562 563
		case sub := <-p.cancelCh:
			p.handleRemoveSubscription(sub)
		case sub := <-p.addSub:
			p.handleAddSubscription(sub)
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
564 565
		case relay := <-p.addRelay:
			p.handleAddRelay(relay)
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
566 567
		case topic := <-p.rmRelay:
			p.handleRemoveRelay(topic)
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
		case preq := <-p.getPeers:
			tmap, ok := p.topics[preq.topic]
			if preq.topic != "" && !ok {
				preq.resp <- nil
				continue
			}
			var peers []peer.ID
			for p := range p.peers {
				if preq.topic != "" {
					_, ok := tmap[p]
					if !ok {
						continue
					}
				}
				peers = append(peers, p)
			}
			preq.resp <- peers
		case rpc := <-p.incoming:
vyzo's avatar
vyzo committed
586 587
			p.handleIncomingRPC(rpc)

588 589
		case msg := <-p.sendMsg:
			p.publishMessage(msg)
590 591

		case req := <-p.addVal:
vyzo's avatar
vyzo committed
592
			p.val.AddValidator(req)
593

594
		case req := <-p.rmVal:
vyzo's avatar
vyzo committed
595
			p.val.RemoveValidator(req)
596

vyzo's avatar
vyzo committed
597 598 599
		case thunk := <-p.eval:
			thunk()

vyzo's avatar
vyzo committed
600 601
		case pid := <-p.blacklistPeer:
			log.Infof("Blacklisting peer %s", pid)
vyzo's avatar
vyzo committed
602
			p.blacklist.Add(pid)
vyzo's avatar
vyzo committed
603

604 605 606 607
			ch, ok := p.peers[pid]
			if ok {
				close(ch)
				delete(p.peers, pid)
608
				for t, tmap := range p.topics {
609 610 611 612
					if _, ok := tmap[pid]; ok {
						delete(tmap, pid)
						p.notifyLeave(t, pid)
					}
613 614 615 616
				}
				p.rt.RemovePeer(pid)
			}

617 618 619 620 621 622 623
		case <-ctx.Done():
			log.Info("pubsub processloop shutting down")
			return
		}
	}
}

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
// handleAddTopic adds a tracker for a particular topic.
// Only called from processLoop.
func (p *PubSub) handleAddTopic(req *addTopicReq) {
	topic := req.topic
	topicID := topic.topic

	t, ok := p.myTopics[topicID]
	if ok {
		req.resp <- t
		return
	}

	p.myTopics[topicID] = topic
	req.resp <- topic
}

// handleRemoveTopic removes Topic tracker from bookkeeping.
// Only called from processLoop.
func (p *PubSub) handleRemoveTopic(req *rmTopicReq) {
	topic := p.myTopics[req.topic.topic]

	if topic == nil {
		req.resp <- nil
		return
	}

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
650 651 652
	if len(topic.evtHandlers) == 0 &&
		len(p.mySubs[req.topic.topic]) == 0 &&
		p.myRelays[req.topic.topic] == 0 {
653 654 655 656 657 658 659 660
		delete(p.myTopics, topic.topic)
		req.resp <- nil
		return
	}

	req.resp <- fmt.Errorf("cannot close topic: outstanding event handlers or subscriptions")
}

661
// handleRemoveSubscription removes Subscription sub from bookeeping.
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
662 663
// If this was the last subscription and no more relays exist for a given topic,
// it will also announce that this node is not subscribing to this topic anymore.
664 665
// Only called from processLoop.
func (p *PubSub) handleRemoveSubscription(sub *Subscription) {
666
	subs := p.mySubs[sub.topic]
667 668 669 670 671

	if subs == nil {
		return
	}

672
	sub.err = ErrSubscriptionCancelled
673
	sub.close()
674 675 676
	delete(subs, sub)

	if len(subs) == 0 {
677
		delete(p.mySubs, sub.topic)
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
678

679 680 681 682 683 684
		// stop announcing only if there are no more subs and relays
		if p.myRelays[sub.topic] == 0 {
			p.disc.StopAdvertise(sub.topic)
			p.announce(sub.topic, false)
			p.rt.Leave(sub.topic)
		}
685 686 687 688
	}
}

// handleAddSubscription adds a Subscription for a particular topic. If it is
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
689 690
// the first subscription and no relays exist so far for the topic, it will
// announce that this node subscribes to the topic.
691 692 693
// Only called from processLoop.
func (p *PubSub) handleAddSubscription(req *addSubReq) {
	sub := req.sub
694
	subs := p.mySubs[sub.topic]
695

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
696 697
	// announce we want this topic if neither subs nor relays exist so far
	if len(subs) == 0 && p.myRelays[sub.topic] == 0 {
698
		p.disc.Advertise(sub.topic)
699
		p.announce(sub.topic, true)
700
		p.rt.Join(sub.topic)
701 702 703 704
	}

	// make new if not there
	if subs == nil {
705
		p.mySubs[sub.topic] = make(map[*Subscription]struct{})
706 707
	}

708
	sub.cancelCh = p.cancelCh
709

710
	p.mySubs[sub.topic][sub] = struct{}{}
711 712 713 714

	req.resp <- sub
}

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
715
// handleAddRelay adds a relay for a particular topic. If it is
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
716 717
// the first relay and no subscriptions exist so far for the topic , it will
// announce that this node relays for the topic.
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
718 719
// Only called from processLoop.
func (p *PubSub) handleAddRelay(req *addRelayReq) {
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
720
	topic := req.topic
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
721

722 723
	p.myRelays[topic]++

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
724
	// announce we want this topic if neither relays nor subs exist so far
725
	if p.myRelays[topic] == 1 && len(p.mySubs[topic]) == 0 {
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
726 727 728
		p.disc.Advertise(topic)
		p.announce(topic, true)
		p.rt.Join(topic)
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
729 730
	}

731 732 733 734 735 736 737 738
	// flag used to prevent calling cancel function multiple times
	isCancelled := false

	relayCancelFunc := func() {
		if isCancelled {
			return
		}

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
739
		select {
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
740
		case p.rmRelay <- topic:
741
			isCancelled = true
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
742 743 744
		case <-p.ctx.Done():
		}
	}
745 746

	req.resp <- relayCancelFunc
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
747 748 749
}

// handleRemoveRelay removes one relay reference from bookkeeping.
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
750 751 752
// If this was the last relay reference and no more subscriptions exist
// for a given topic, it will also announce that this node is not relaying
// for this topic anymore.
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
753 754 755 756 757 758 759 760 761 762
// Only called from processLoop.
func (p *PubSub) handleRemoveRelay(topic string) {
	if p.myRelays[topic] == 0 {
		return
	}

	p.myRelays[topic]--

	if p.myRelays[topic] == 0 {
		delete(p.myRelays, topic)
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
763

764 765 766 767 768 769
		// stop announcing only if there are no more relays and subs
		if len(p.mySubs[topic]) == 0 {
			p.disc.StopAdvertise(topic)
			p.announce(topic, false)
			p.rt.Leave(topic)
		}
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
770
	}
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
771 772
}

773 774 775 776 777 778 779 780 781 782 783 784
// announce announces whether or not this node is interested in a given topic
// Only called from processLoop.
func (p *PubSub) announce(topic string, sub bool) {
	subopt := &pb.RPC_SubOpts{
		Topicid:   &topic,
		Subscribe: &sub,
	}

	out := rpcWithSubs(subopt)
	for pid, peer := range p.peers {
		select {
		case peer <- out:
785
			p.tracer.SendRPC(out, pid)
786
		default:
vyzo's avatar
vyzo committed
787
			log.Infof("Can't send announce message to peer %s: queue full; scheduling retry", pid)
788
			p.tracer.DropRPC(out, pid)
vyzo's avatar
vyzo committed
789
			go p.announceRetry(pid, topic, sub)
vyzo's avatar
vyzo committed
790 791 792 793
		}
	}
}

vyzo's avatar
vyzo committed
794
func (p *PubSub) announceRetry(pid peer.ID, topic string, sub bool) {
vyzo's avatar
vyzo committed
795
	time.Sleep(time.Duration(1+rand.Intn(1000)) * time.Millisecond)
796 797

	retry := func() {
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
798 799 800 801 802
		_, okSubs := p.mySubs[topic]
		_, okRelays := p.myRelays[topic]

		ok := okSubs || okRelays

vyzo's avatar
vyzo committed
803
		if (ok && sub) || (!ok && !sub) {
vyzo's avatar
vyzo committed
804
			p.doAnnounceRetry(pid, topic, sub)
805 806
		}
	}
807 808 809 810 811

	select {
	case p.eval <- retry:
	case <-p.ctx.Done():
	}
812 813
}

vyzo's avatar
vyzo committed
814 815 816 817 818 819 820
func (p *PubSub) doAnnounceRetry(pid peer.ID, topic string, sub bool) {
	peer, ok := p.peers[pid]
	if !ok {
		return
	}

	subopt := &pb.RPC_SubOpts{
821 822
		Topicid:   &topic,
		Subscribe: &sub,
vyzo's avatar
vyzo committed
823 824 825 826 827
	}

	out := rpcWithSubs(subopt)
	select {
	case peer <- out:
828
		p.tracer.SendRPC(out, pid)
vyzo's avatar
vyzo committed
829 830
	default:
		log.Infof("Can't send announce message to peer %s: queue full; scheduling retry", pid)
831
		p.tracer.DropRPC(out, pid)
vyzo's avatar
vyzo committed
832 833 834 835
		go p.announceRetry(pid, topic, sub)
	}
}

836 837
// notifySubs sends a given message to all corresponding subscribers.
// Only called from processLoop.
838
func (p *PubSub) notifySubs(msg *Message) {
vyzo's avatar
vyzo committed
839 840 841 842 843 844 845
	topic := msg.GetTopic()
	subs := p.mySubs[topic]
	for f := range subs {
		select {
		case f.ch <- msg:
		default:
			log.Infof("Can't deliver message to subscription for topic %s; subscriber too slow", topic)
846 847 848 849 850 851
		}
	}
}

// seenMessage returns whether we already saw this message before
func (p *PubSub) seenMessage(id string) bool {
852 853
	p.seenMessagesMx.Lock()
	defer p.seenMessagesMx.Unlock()
854 855 856 857
	return p.seenMessages.Has(id)
}

// markSeen marks a message as seen such that seenMessage returns `true' for the given id
858 859 860 861 862 863 864 865
// returns true if the message was freshly marked
func (p *PubSub) markSeen(id string) bool {
	p.seenMessagesMx.Lock()
	defer p.seenMessagesMx.Unlock()
	if p.seenMessages.Has(id) {
		return false
	}

866
	p.seenMessages.Add(id)
867
	return true
868 869 870 871 872
}

// subscribedToMessage returns whether we are subscribed to one of the topics
// of a given message
func (p *PubSub) subscribedToMsg(msg *pb.Message) bool {
873
	if len(p.mySubs) == 0 {
874 875 876
		return false
	}

vyzo's avatar
vyzo committed
877 878 879 880
	topic := msg.GetTopic()
	_, ok := p.mySubs[topic]

	return ok
881 882
}

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
883 884 885 886 887 888 889
// canRelayMsg returns whether we are able to relay for one of the topics
// of a given message
func (p *PubSub) canRelayMsg(msg *pb.Message) bool {
	if len(p.myRelays) == 0 {
		return false
	}

vyzo's avatar
vyzo committed
890 891 892 893
	topic := msg.GetTopic()
	relays := p.myRelays[topic]

	return relays > 0
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
894 895
}

896
func (p *PubSub) notifyLeave(topic string, pid peer.ID) {
897 898
	if t, ok := p.myTopics[topic]; ok {
		t.sendNotification(PeerEvent{PeerLeave, pid})
899 900 901
	}
}

vyzo's avatar
vyzo committed
902
func (p *PubSub) handleIncomingRPC(rpc *RPC) {
vyzo's avatar
vyzo committed
903 904
	p.tracer.RecvRPC(rpc)

vyzo's avatar
vyzo committed
905 906 907 908 909 910 911 912 913 914 915
	subs := rpc.GetSubscriptions()
	if len(subs) != 0 && p.subFilter != nil {
		var err error
		subs, err = p.subFilter.FilterIncomingSubscriptions(rpc.from, subs)
		if err != nil {
			log.Debugf("subscription filter error: %s; ignoring RPC", err)
			return
		}
	}

	for _, subopt := range subs {
916
		t := subopt.GetTopicid()
vyzo's avatar
vyzo committed
917

918 919 920 921 922 923 924
		if subopt.GetSubscribe() {
			tmap, ok := p.topics[t]
			if !ok {
				tmap = make(map[peer.ID]struct{})
				p.topics[t] = tmap
			}

925 926
			if _, ok = tmap[rpc.from]; !ok {
				tmap[rpc.from] = struct{}{}
927
				if topic, ok := p.myTopics[t]; ok {
928
					peer := rpc.from
929
					topic.sendNotification(PeerEvent{PeerJoin, peer})
930 931
				}
			}
932 933 934 935 936
		} else {
			tmap, ok := p.topics[t]
			if !ok {
				continue
			}
937 938 939 940 941

			if _, ok := tmap[rpc.from]; ok {
				delete(tmap, rpc.from)
				p.notifyLeave(t, rpc.from)
			}
942 943 944
		}
	}

945
	// ask the router to vet the peer before commiting any processing resources
vyzo's avatar
vyzo committed
946 947
	switch p.rt.AcceptFrom(rpc.from) {
	case AcceptNone:
vyzo's avatar
vyzo committed
948
		log.Debugf("received RPC from router graylisted peer %s; dropping RPC", rpc.from)
949 950
		return

vyzo's avatar
vyzo committed
951 952
	case AcceptControl:
		if len(rpc.GetPublish()) > 0 {
vyzo's avatar
vyzo committed
953
			log.Debugf("peer %s was throttled by router; ignoring %d payload messages", rpc.from, len(rpc.GetPublish()))
954
		}
955
		p.tracer.ThrottlePeer(rpc.from)
956

vyzo's avatar
vyzo committed
957 958 959
	case AcceptAll:
		for _, pmsg := range rpc.GetPublish() {
			if !(p.subscribedToMsg(pmsg) || p.canRelayMsg(pmsg)) {
vyzo's avatar
vyzo committed
960
				log.Debug("received message in topic we didn't subscribe to; ignoring message")
vyzo's avatar
vyzo committed
961 962 963 964 965 966
				continue
			}

			msg := &Message{pmsg, rpc.from, nil}
			p.pushMsg(msg)
		}
967 968
	}

vyzo's avatar
vyzo committed
969
	p.rt.HandleRPC(rpc)
970 971
}

972 973
// DefaultMsgIdFn returns a unique ID of the passed Message
func DefaultMsgIdFn(pmsg *pb.Message) string {
974 975 976 977
	return string(pmsg.GetFrom()) + string(pmsg.GetSeqno())
}

// pushMsg pushes a message performing validation as necessary
978 979
func (p *PubSub) pushMsg(msg *Message) {
	src := msg.ReceivedFrom
vyzo's avatar
vyzo committed
980
	// reject messages from blacklisted peers
vyzo's avatar
vyzo committed
981
	if p.blacklist.Contains(src) {
vyzo's avatar
vyzo committed
982
		log.Debugf("dropping message from blacklisted peer %s", src)
vyzo's avatar
vyzo committed
983
		p.tracer.RejectMessage(msg, RejectBlacklstedPeer)
vyzo's avatar
vyzo committed
984 985 986
		return
	}

vyzo's avatar
vyzo committed
987
	// even if they are forwarded by good peers
vyzo's avatar
vyzo committed
988
	if p.blacklist.Contains(msg.GetFrom()) {
vyzo's avatar
vyzo committed
989
		log.Debugf("dropping message from blacklisted source %s", src)
vyzo's avatar
vyzo committed
990
		p.tracer.RejectMessage(msg, RejectBlacklistedSource)
vyzo's avatar
vyzo committed
991 992 993
		return
	}

994
	err := p.checkSigningPolicy(msg)
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	if err != nil {
		log.Debugf("dropping message from %s: %s", src, err)
		return
	}

	// reject messages claiming to be from ourselves but not locally published
	self := p.host.ID()
	if peer.ID(msg.GetFrom()) == self && src != self {
		log.Debugf("dropping message claiming to be from self but forwarded from %s", src)
		p.tracer.RejectMessage(msg, RejectSelfOrigin)
		return
	}

	// have we already seen and validated this message?
	id := p.msgID(msg.Message)
	if p.seenMessage(id) {
		p.tracer.DuplicateMessage(msg)
		return
	}

	if !p.val.Push(src, msg) {
		return
	}

	if p.markSeen(id) {
		p.publishMessage(msg)
	}
}

1024
func (p *PubSub) checkSigningPolicy(msg *Message) error {
vyzo's avatar
vyzo committed
1025
	// reject unsigned messages when strict before we even process the id
1026 1027 1028
	if p.signPolicy.mustVerify() {
		if p.signPolicy.mustSign() {
			if msg.Signature == nil {
vyzo's avatar
vyzo committed
1029
				p.tracer.RejectMessage(msg, RejectMissingSignature)
1030
				return ValidationError{Reason: RejectMissingSignature}
1031 1032 1033 1034 1035 1036
			}
			// Actual signature verification happens in the validation pipeline,
			// after checking if the message was already seen or not,
			// to avoid unnecessary signature verification processing-cost.
		} else {
			if msg.Signature != nil {
vyzo's avatar
vyzo committed
1037
				p.tracer.RejectMessage(msg, RejectUnexpectedSignature)
1038
				return ValidationError{Reason: RejectUnexpectedSignature}
1039 1040 1041 1042 1043 1044 1045
			}
			// If we are expecting signed messages, and not authoring messages,
			// then do no accept seq numbers, from data, or key data.
			// The default msgID function still relies on Seqno and From,
			// but is not used if we are not authoring messages ourselves.
			if p.signID == "" {
				if msg.Seqno != nil || msg.From != nil || msg.Key != nil {
vyzo's avatar
vyzo committed
1046
					p.tracer.RejectMessage(msg, RejectUnexpectedAuthInfo)
1047
					return ValidationError{Reason: RejectUnexpectedAuthInfo}
1048 1049 1050
				}
			}
		}
vyzo's avatar
vyzo committed
1051 1052
	}

1053
	return nil
1054 1055
}

1056
func (p *PubSub) publishMessage(msg *Message) {
vyzo's avatar
vyzo committed
1057
	p.tracer.DeliverMessage(msg)
1058
	p.notifySubs(msg)
1059
	p.rt.Publish(msg)
1060 1061
}

1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
type addTopicReq struct {
	topic *Topic
	resp  chan *Topic
}

type rmTopicReq struct {
	topic *Topic
	resp  chan error
}

type TopicOptions struct{}

type TopicOpt func(t *Topic) error

// Join joins the topic and returns a Topic handle. Only one Topic handle should exist per topic, and Join will error if
// the Topic handle already exists.
func (p *PubSub) Join(topic string, opts ...TopicOpt) (*Topic, error) {
	t, ok, err := p.tryJoin(topic, opts...)
	if err != nil {
		return nil, err
	}

	if !ok {
		return nil, fmt.Errorf("topic already exists")
	}

	return t, nil
}

// tryJoin is an internal function that tries to join a topic
// Returns the topic if it can be created or found
// Returns true if the topic was newly created, false otherwise
// Can be removed once pubsub.Publish() and pubsub.Subscribe() are removed
func (p *PubSub) tryJoin(topic string, opts ...TopicOpt) (*Topic, bool, error) {
vyzo's avatar
vyzo committed
1096 1097 1098 1099
	if p.subFilter != nil && !p.subFilter.CanSubscribe(topic) {
		return nil, false, fmt.Errorf("topic is not allowed by the subscription filter")
	}

1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
	t := &Topic{
		p:           p,
		topic:       topic,
		evtHandlers: make(map[*TopicEventHandler]struct{}),
	}

	for _, opt := range opts {
		err := opt(t)
		if err != nil {
			return nil, false, err
		}
	}

	resp := make(chan *Topic, 1)
1114 1115
	select {
	case t.p.addTopic <- &addTopicReq{
1116 1117
		topic: t,
		resp:  resp,
1118 1119 1120
	}:
	case <-t.p.ctx.Done():
		return nil, false, t.p.ctx.Err()
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
	}
	returnedTopic := <-resp

	if returnedTopic != t {
		return returnedTopic, false, nil
	}

	return t, true, nil
}

1131 1132 1133 1134 1135 1136 1137
type addSubReq struct {
	sub  *Subscription
	resp chan *Subscription
}

type SubOpt func(sub *Subscription) error

1138 1139 1140
// Subscribe returns a new Subscription for the given topic.
// Note that subscription is not an instanteneous operation. It may take some time
// before the subscription is processed by the pubsub main loop and propagated to our peers.
1141 1142
//
// Deprecated: use pubsub.Join() and topic.Subscribe() instead
1143
func (p *PubSub) Subscribe(topic string, opts ...SubOpt) (*Subscription, error) {
1144
	// ignore whether the topic was newly created or not, since either way we have a valid topic to work with
1145
	topicHandle, _, err := p.tryJoin(topic)
1146 1147
	if err != nil {
		return nil, err
1148 1149
	}

1150
	return topicHandle.Subscribe(opts...)
1151 1152 1153 1154 1155 1156
}

type topicReq struct {
	resp chan []string
}

vyzo's avatar
vyzo committed
1157
// GetTopics returns the topics this node is subscribed to.
1158 1159
func (p *PubSub) GetTopics() []string {
	out := make(chan []string, 1)
1160 1161 1162 1163 1164
	select {
	case p.getTopics <- &topicReq{resp: out}:
	case <-p.ctx.Done():
		return nil
	}
1165 1166 1167
	return <-out
}

vyzo's avatar
vyzo committed
1168
// Publish publishes data to the given topic.
1169 1170 1171 1172 1173 1174 1175
//
// Deprecated: use pubsub.Join() and topic.Publish() instead
func (p *PubSub) Publish(topic string, data []byte, opts ...PubOpt) error {
	// ignore whether the topic was newly created or not, since either way we have a valid topic to work with
	t, _, err := p.tryJoin(topic)
	if err != nil {
		return err
1176
	}
1177 1178

	return t.Publish(context.TODO(), data, opts...)
1179 1180
}

vyzo's avatar
vyzo committed
1181 1182 1183 1184 1185 1186 1187
func (p *PubSub) nextSeqno() []byte {
	seqno := make([]byte, 8)
	counter := atomic.AddUint64(&p.counter, 1)
	binary.BigEndian.PutUint64(seqno, counter)
	return seqno
}

1188 1189 1190 1191 1192
type listPeerReq struct {
	resp  chan []peer.ID
	topic string
}

vyzo's avatar
vyzo committed
1193
// ListPeers returns a list of peers we are connected to in the given topic.
1194 1195
func (p *PubSub) ListPeers(topic string) []peer.ID {
	out := make(chan []peer.ID)
1196 1197
	select {
	case p.getPeers <- &listPeerReq{
1198 1199
		resp:  out,
		topic: topic,
1200 1201 1202
	}:
	case <-p.ctx.Done():
		return nil
1203 1204 1205 1206
	}
	return <-out
}

vyzo's avatar
vyzo committed
1207 1208
// BlacklistPeer blacklists a peer; all messages from this peer will be unconditionally dropped.
func (p *PubSub) BlacklistPeer(pid peer.ID) {
1209 1210 1211 1212
	select {
	case p.blacklistPeer <- pid:
	case <-p.ctx.Done():
	}
vyzo's avatar
vyzo committed
1213 1214
}

vyzo's avatar
vyzo committed
1215
// RegisterTopicValidator registers a validator for topic.
1216 1217 1218
// By default validators are asynchronous, which means they will run in a separate goroutine.
// The number of active goroutines is controlled by global and per topic validator
// throttles; if it exceeds the throttle threshold, messages will be dropped.
vyzo's avatar
vyzo committed
1219
func (p *PubSub) RegisterTopicValidator(topic string, val interface{}, opts ...ValidatorOpt) error {
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
	addVal := &addValReq{
		topic:    topic,
		validate: val,
		resp:     make(chan error, 1),
	}

	for _, opt := range opts {
		err := opt(addVal)
		if err != nil {
			return err
		}
	}

1233 1234 1235 1236 1237
	select {
	case p.addVal <- addVal:
	case <-p.ctx.Done():
		return p.ctx.Err()
	}
1238 1239 1240
	return <-addVal.resp
}

vyzo's avatar
vyzo committed
1241 1242
// UnregisterTopicValidator removes a validator from a topic.
// Returns an error if there was no validator registered with the topic.
1243 1244 1245 1246 1247 1248
func (p *PubSub) UnregisterTopicValidator(topic string) error {
	rmVal := &rmValReq{
		topic: topic,
		resp:  make(chan error, 1),
	}

1249 1250 1251 1252 1253
	select {
	case p.rmVal <- rmVal:
	case <-p.ctx.Done():
		return p.ctx.Err()
	}
1254 1255
	return <-rmVal.resp
}
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
1256

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
1257 1258
type RelayCancelFunc func()

Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
1259 1260
type addRelayReq struct {
	topic string
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
1261
	resp  chan RelayCancelFunc
Lukasz Zimnoch's avatar
Lukasz Zimnoch committed
1262
}