score.go 18.8 KB
Newer Older
vyzo's avatar
vyzo committed
1 2 3
package pubsub

import (
vyzo's avatar
vyzo committed
4
	"context"
vyzo's avatar
vyzo committed
5
	"fmt"
6
	"net"
vyzo's avatar
vyzo committed
7
	"sync"
vyzo's avatar
vyzo committed
8 9
	"time"

vyzo's avatar
vyzo committed
10
	"github.com/libp2p/go-libp2p-core/host"
vyzo's avatar
vyzo committed
11 12
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/protocol"
vyzo's avatar
vyzo committed
13

14
	manet "github.com/multiformats/go-multiaddr-net"
vyzo's avatar
vyzo committed
15 16
)

vyzo's avatar
vyzo committed
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
type peerStats struct {
	// true if the peer is currently connected
	connected bool

	// expiration time of the score stats for disconnected peers
	expire time.Time

	// per topc stats
	topics map[string]*topicStats

	// IP tracking; store as string for easy processing
	ips []string
}

type topicStats struct {
	// true if the peer is in the mesh
	inMesh bool

	// time when the peer was (last) GRAFTed; valid only when in mesh
	graftTime time.Time

	// time in mesh (updated during refresh/decay to avoid calling gettimeofday on
	// every score invocation)
	meshTime time.Duration

	// first message deliveries
	firstMessageDeliveries float64

	// mesh message deliveries
	meshMessageDeliveries float64

	// true if the peer has been enough time in the mesh to activate mess message deliveries
	meshMessageDeliveriesActive bool

vyzo's avatar
vyzo committed
51 52 53
	// sticky mesh rate failure penalty counter
	meshFailurePenalty float64

vyzo's avatar
vyzo committed
54 55 56 57
	// invalid message counter
	invalidMessageDeliveries float64
}

vyzo's avatar
vyzo committed
58
type peerScore struct {
vyzo's avatar
vyzo committed
59 60 61 62 63 64 65 66 67
	sync.Mutex

	// the score parameters
	params *PeerScoreParams

	// per peer stats for score calculation
	peerStats map[peer.ID]*peerStats

	// IP colocation tracking
vyzo's avatar
vyzo committed
68
	peerIPs map[string]map[peer.ID]struct{}
vyzo's avatar
vyzo committed
69 70 71 72 73

	// message delivery tracking
	deliveries *messageDeliveries

	msgID MsgIdFunction
vyzo's avatar
vyzo committed
74
	host  host.Host
75 76 77 78

	// debugging inspection
	inspect       PeerScoreInspectFn
	inspectPeriod time.Duration
vyzo's avatar
vyzo committed
79 80 81
}

type messageDeliveries struct {
82 83 84 85 86
	records map[string]*deliveryRecord

	// queue for cleaning up old delivery records
	head *deliveryEntry
	tail *deliveryEntry
vyzo's avatar
vyzo committed
87 88 89 90
}

type deliveryRecord struct {
	status    int
91
	validated time.Time
92
	peers     map[peer.ID]struct{}
vyzo's avatar
vyzo committed
93 94
}

95 96 97 98 99 100
type deliveryEntry struct {
	id     string
	expire time.Time
	next   *deliveryEntry
}

vyzo's avatar
vyzo committed
101 102
// delivery record status
const (
vyzo's avatar
vyzo committed
103 104 105 106
	delivery_unknown   = iota // we don't know (yet) if the message is valid
	delivery_valid            // we know the message is valid
	delivery_invalid          // we know the message is invalid
	delivery_throttled        // we can't tell if it is valid because validation throttled
vyzo's avatar
vyzo committed
107 108
)

109 110
type PeerScoreInspectFn func(map[peer.ID]float64)

111
// WithPeerScoreInspect is a gossipsub router option that enables peer score debugging.
112 113 114
// When this option is enabled, the supplied function will be invoked periodically to allow
// the application to inspec or dump the scores for connected peers.
// This option must be passed _after_ the WithPeerScore option.
115
func WithPeerScoreInspect(inspect PeerScoreInspectFn, period time.Duration) Option {
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	return func(ps *PubSub) error {
		gs, ok := ps.rt.(*GossipSubRouter)
		if !ok {
			return fmt.Errorf("pubsub router is not gossipsub")
		}

		if gs.score == nil {
			return fmt.Errorf("peer scoring is not enabled")
		}

		gs.score.inspect = inspect
		gs.score.inspectPeriod = period

		return nil
	}
}

// implementation
134
func newPeerScore(params *PeerScoreParams) *peerScore {
vyzo's avatar
vyzo committed
135 136 137 138 139 140 141
	return &peerScore{
		params:     params,
		peerStats:  make(map[peer.ID]*peerStats),
		peerIPs:    make(map[string]map[peer.ID]struct{}),
		deliveries: &messageDeliveries{records: make(map[string]*deliveryRecord)},
		msgID:      DefaultMsgIdFn,
	}
vyzo's avatar
vyzo committed
142 143 144
}

// router interface
145
func (ps *peerScore) Start(gs *GossipSubRouter) {
146 147 148 149
	if ps == nil {
		return
	}

vyzo's avatar
vyzo committed
150 151 152
	ps.msgID = gs.p.msgID
	ps.host = gs.p.host
	go ps.background(gs.p.ctx)
153 154
}

155
func (ps *peerScore) Score(p peer.ID) float64 {
vyzo's avatar
vyzo committed
156 157 158 159
	if ps == nil {
		return 0
	}

vyzo's avatar
vyzo committed
160 161 162
	ps.Lock()
	defer ps.Unlock()

163 164 165 166
	return ps.score(p)
}

func (ps *peerScore) score(p peer.ID) float64 {
vyzo's avatar
vyzo committed
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
	pstats, ok := ps.peerStats[p]
	if !ok {
		return 0
	}

	var score float64

	// topic scores
	for topic, tstats := range pstats.topics {
		// the topic score
		var topicScore float64

		// the topic parameters
		topicParams, ok := ps.params.Topics[topic]
		if !ok {
			// we are not scoring this topic
			continue
		}

		// P1: time in Mesh
		if tstats.inMesh {
			p1 := float64(tstats.meshTime / topicParams.TimeInMeshQuantum)
vyzo's avatar
vyzo committed
189 190 191
			if p1 > topicParams.TimeInMeshCap {
				p1 = topicParams.TimeInMeshCap
			}
vyzo's avatar
vyzo committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			topicScore += p1 * topicParams.TimeInMeshWeight
		}

		// P2: first message deliveries
		p2 := tstats.firstMessageDeliveries
		topicScore += p2 * topicParams.FirstMessageDeliveriesWeight

		// P3: mesh message deliveries
		if tstats.meshMessageDeliveriesActive {
			if tstats.meshMessageDeliveries < topicParams.MeshMessageDeliveriesThreshold {
				deficit := topicParams.MeshMessageDeliveriesThreshold - tstats.meshMessageDeliveries
				p3 := deficit * deficit
				topicScore += p3 * topicParams.MeshMessageDeliveriesWeight
			}
		}

vyzo's avatar
vyzo committed
208 209 210 211
		// P3b:
		p3b := tstats.meshFailurePenalty
		topicScore += p3b * topicParams.MeshFailurePenaltyWeight

vyzo's avatar
vyzo committed
212 213 214 215 216 217 218 219
		// P4: invalid messages
		p4 := tstats.invalidMessageDeliveries
		topicScore += p4 * topicParams.InvalidMessageDeliveriesWeight

		// update score, mixing with topic weight
		score += topicScore * topicParams.TopicWeight
	}

vyzo's avatar
vyzo committed
220 221 222 223 224
	// apply the topic score cap, if any
	if ps.params.TopicScoreCap > 0 && score > ps.params.TopicScoreCap {
		score = ps.params.TopicScoreCap
	}

vyzo's avatar
vyzo committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
	// P5: application-specific score
	p5 := ps.params.AppSpecificScore(p)
	score += p5 * ps.params.AppSpecificWeight

	// P6: IP collocation factor
	for _, ip := range pstats.ips {
		peersInIP := len(ps.peerIPs[ip])
		if peersInIP > ps.params.IPColocationFactorThreshold {
			surpluss := float64(peersInIP - ps.params.IPColocationFactorThreshold)
			p6 := surpluss * surpluss
			score += p6 * ps.params.IPColocationFactorWeight
		}
	}

	return score
vyzo's avatar
vyzo committed
240 241
}

242
// periodic maintenance
vyzo's avatar
vyzo committed
243 244 245 246 247 248 249 250 251 252
func (ps *peerScore) background(ctx context.Context) {
	refreshScores := time.NewTicker(ps.params.DecayInterval)
	defer refreshScores.Stop()

	refreshIPs := time.NewTicker(time.Minute)
	defer refreshIPs.Stop()

	gcDeliveryRecords := time.NewTicker(time.Minute)
	defer gcDeliveryRecords.Stop()

253 254 255 256
	var inspectScores <-chan time.Time
	if ps.inspect != nil {
		ticker := time.NewTicker(ps.inspectPeriod)
		defer ticker.Stop()
257 258
		// also dump at exit for one final sample
		defer ps.inspectScores()
259 260 261
		inspectScores = ticker.C
	}

vyzo's avatar
vyzo committed
262 263 264 265 266 267 268 269 270 271 272
	for {
		select {
		case <-refreshScores.C:
			ps.refreshScores()

		case <-refreshIPs.C:
			ps.refreshIPs()

		case <-gcDeliveryRecords.C:
			ps.gcDeliveryRecords()

273 274 275
		case <-inspectScores:
			ps.inspectScores()

vyzo's avatar
vyzo committed
276 277 278 279 280 281
		case <-ctx.Done():
			return
		}
	}
}

282 283 284 285 286 287 288 289 290 291 292
func (ps *peerScore) inspectScores() {
	ps.Lock()
	scores := make(map[peer.ID]float64, len(ps.peerStats))
	for p := range ps.peerStats {
		scores[p] = ps.score(p)
	}
	ps.Unlock()

	ps.inspect(scores)
}

293 294 295 296 297 298 299 300 301
func (ps *peerScore) refreshScores() {
	ps.Lock()
	defer ps.Unlock()

	now := time.Now()
	for p, pstats := range ps.peerStats {
		if !pstats.connected {
			// has the retention period expired?
			if now.After(pstats.expire) {
vyzo's avatar
vyzo committed
302 303
				// yes, throw it away (but clean up the IP tracking first)
				ps.removeIPs(p, pstats.ips)
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
				delete(ps.peerStats, p)
			}

			// we don't decay retained scores, as the peer is not active.
			// this way the peer cannot reset a negative score by simply disconnecting and reconnecting,
			// unless the retention period has ellapsed.
			// similarly, a well behaved peer does not lose its score by getting disconnected.
			continue
		}

		for topic, tstats := range pstats.topics {
			// the topic parameters
			topicParams, ok := ps.params.Topics[topic]
			if !ok {
				// we are not scoring this topic
				continue
			}

			// decay counters
			tstats.firstMessageDeliveries *= topicParams.FirstMessageDeliveriesDecay
324 325 326
			if tstats.firstMessageDeliveries < ps.params.DecayToZero {
				tstats.firstMessageDeliveries = 0
			}
327
			tstats.meshMessageDeliveries *= topicParams.MeshMessageDeliveriesDecay
328 329 330
			if tstats.meshMessageDeliveries < ps.params.DecayToZero {
				tstats.meshMessageDeliveries = 0
			}
vyzo's avatar
vyzo committed
331 332 333 334
			tstats.meshFailurePenalty *= topicParams.MeshFailurePenaltyDecay
			if tstats.meshFailurePenalty < ps.params.DecayToZero {
				tstats.meshFailurePenalty = 0
			}
335
			tstats.invalidMessageDeliveries *= topicParams.InvalidMessageDeliveriesDecay
336 337 338
			if tstats.invalidMessageDeliveries < ps.params.DecayToZero {
				tstats.invalidMessageDeliveries = 0
			}
339 340 341 342 343 344 345 346 347 348 349
			// update mesh time and activate mesh message delivery parameter if need be
			if tstats.inMesh {
				tstats.meshTime = now.Sub(tstats.graftTime)
				if tstats.meshTime > topicParams.MeshMessageDeliveriesActivation {
					tstats.meshMessageDeliveriesActive = true
				}
			}
		}
	}
}

vyzo's avatar
vyzo committed
350 351 352 353
func (ps *peerScore) refreshIPs() {
	ps.Lock()
	defer ps.Unlock()

354
	// peer IPs may change, so we periodically refresh them
vyzo's avatar
vyzo committed
355 356 357 358 359 360 361
	for p, pstats := range ps.peerStats {
		if pstats.connected {
			ips := ps.getIPs(p)
			ps.setIPs(p, ips, pstats.ips)
			pstats.ips = ips
		}
	}
362 363
}

vyzo's avatar
vyzo committed
364 365 366 367 368 369 370
func (ps *peerScore) gcDeliveryRecords() {
	ps.Lock()
	defer ps.Unlock()

	ps.deliveries.gc()
}

vyzo's avatar
vyzo committed
371 372
// tracer interface
func (ps *peerScore) AddPeer(p peer.ID, proto protocol.ID) {
vyzo's avatar
vyzo committed
373 374 375 376 377 378 379 380 381 382 383
	ps.Lock()
	defer ps.Unlock()

	pstats, ok := ps.peerStats[p]
	if !ok {
		pstats = &peerStats{topics: make(map[string]*topicStats)}
		ps.peerStats[p] = pstats
	}

	pstats.connected = true
	ips := ps.getIPs(p)
vyzo's avatar
vyzo committed
384
	ps.setIPs(p, ips, pstats.ips)
vyzo's avatar
vyzo committed
385
	pstats.ips = ips
vyzo's avatar
vyzo committed
386 387 388
}

func (ps *peerScore) RemovePeer(p peer.ID) {
vyzo's avatar
vyzo committed
389 390 391 392 393 394 395 396
	ps.Lock()
	defer ps.Unlock()

	pstats, ok := ps.peerStats[p]
	if !ok {
		return
	}

vyzo's avatar
vyzo committed
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
	// decide whether to retain the score; this currently only retains non-positive scores
	// to dissuade attacks on the score function.
	if ps.score(p) > 0 {
		ps.removeIPs(p, pstats.ips)
		delete(ps.peerStats, p)
		return
	}

	// furthermore, when we decide to retain the score, the firstMessageDelivery counters are
	// reset to 0 and mesh delivery penalties applied.
	for topic, tstats := range pstats.topics {
		tstats.firstMessageDeliveries = 0

		threshold := ps.params.Topics[topic].MeshMessageDeliveriesThreshold
		if tstats.inMesh && tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold {
			deficit := threshold - tstats.meshMessageDeliveries
			tstats.meshFailurePenalty += deficit * deficit
		}

		tstats.inMesh = false
	}

vyzo's avatar
vyzo committed
419 420
	pstats.connected = false
	pstats.expire = time.Now().Add(ps.params.RetainScore)
vyzo's avatar
vyzo committed
421
}
vyzo's avatar
vyzo committed
422

vyzo's avatar
vyzo committed
423 424 425 426
func (ps *peerScore) Join(topic string)  {}
func (ps *peerScore) Leave(topic string) {}

func (ps *peerScore) Graft(p peer.ID, topic string) {
vyzo's avatar
vyzo committed
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	ps.Lock()
	defer ps.Unlock()

	pstats, ok := ps.peerStats[p]
	if !ok {
		return
	}

	tstats, ok := pstats.getTopicStats(topic, ps.params)
	if !ok {
		return
	}

	tstats.inMesh = true
	tstats.graftTime = time.Now()
	tstats.meshTime = 0
vyzo's avatar
vyzo committed
443
	tstats.meshMessageDeliveriesActive = false
vyzo's avatar
vyzo committed
444 445
}

vyzo's avatar
vyzo committed
446
func (ps *peerScore) Prune(p peer.ID, topic string) {
vyzo's avatar
vyzo committed
447 448 449 450 451 452 453 454 455 456 457 458 459
	ps.Lock()
	defer ps.Unlock()

	pstats, ok := ps.peerStats[p]
	if !ok {
		return
	}

	tstats, ok := pstats.getTopicStats(topic, ps.params)
	if !ok {
		return
	}

460 461 462 463 464
	// sticky mesh delivery rate failure penalty
	threshold := ps.params.Topics[topic].MeshMessageDeliveriesThreshold
	if tstats.meshMessageDeliveriesActive && tstats.meshMessageDeliveries < threshold {
		deficit := threshold - tstats.meshMessageDeliveries
		tstats.meshFailurePenalty += deficit * deficit
vyzo's avatar
vyzo committed
465 466
	}

vyzo's avatar
vyzo committed
467
	tstats.inMesh = false
vyzo's avatar
vyzo committed
468
}
vyzo's avatar
vyzo committed
469

vyzo's avatar
vyzo committed
470 471 472 473 474 475 476 477 478
func (ps *peerScore) ValidateMessage(msg *Message) {
	ps.Lock()
	defer ps.Unlock()

	// the pubsub subsystem is beginning validation; create a record to track time in
	// the validation pipeline with an accurate firstSeen time.
	_ = ps.deliveries.getRecord(ps.msgID(msg.Message))
}

vyzo's avatar
vyzo committed
479 480 481 482 483 484 485 486
func (ps *peerScore) DeliverMessage(msg *Message) {
	ps.Lock()
	defer ps.Unlock()

	ps.markFirstMessageDelivery(msg.ReceivedFrom, msg)

	drec := ps.deliveries.getRecord(ps.msgID(msg.Message))

487
	// mark the message as valid and reward mesh peers that have already forwarded it to us
vyzo's avatar
vyzo committed
488
	drec.status = delivery_valid
489
	drec.validated = time.Now()
490
	for p := range drec.peers {
491 492 493 494 495
		// this check is to make sure a peer can't send us a message twice and get a double count
		// if it is a first delivery.
		if p != msg.ReceivedFrom {
			ps.markDuplicateMessageDelivery(p, msg, time.Time{})
		}
vyzo's avatar
vyzo committed
496
	}
vyzo's avatar
vyzo committed
497 498
}

vyzo's avatar
vyzo committed
499 500 501 502
func (ps *peerScore) RejectMessage(msg *Message, reason string) {
	ps.Lock()
	defer ps.Unlock()

503 504 505 506 507 508
	// TODO: the reasons should become named strings; good enough for now.
	switch reason {
	// we don't track those messages, but we penalize the peer as they are clearly invalid
	case "missing signature":
		fallthrough
	case "invalid signature":
vyzo's avatar
vyzo committed
509
		ps.markInvalidMessageDelivery(msg.ReceivedFrom, msg)
510 511 512 513 514 515
		return

		// we ignore those messages, so do nothing.
	case "blacklisted peer":
		fallthrough
	case "blacklisted source":
vyzo's avatar
vyzo committed
516
		return
517 518 519 520 521 522

	case "validation queue full":
		// the message was rejected before it entered the validation pipeline;
		// we don't know if this message has a valid signature, and thus we also don't know if
		// it has a valid message ID; all we can do is ignore it.
		return
vyzo's avatar
vyzo committed
523 524 525
	}

	drec := ps.deliveries.getRecord(ps.msgID(msg.Message))
vyzo's avatar
vyzo committed
526

vyzo's avatar
vyzo committed
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
	if reason == "validation throttled" {
		// if we reject with "validation throttled" we don't penalize the peer(s) that forward it
		// because we don't know if it was valid.
		drec.status = delivery_throttled
		// release the delivery time tracking map to free some memory early
		drec.peers = nil
		return
	}

	// mark the message as invalid and penalize peers that have already forwarded it.
	drec.status = delivery_invalid
	for p := range drec.peers {
		ps.markInvalidMessageDelivery(p, msg)
	}

	// release the delivery time tracking map to free some memory early
	drec.peers = nil
vyzo's avatar
vyzo committed
544 545
}

vyzo's avatar
vyzo committed
546 547 548 549 550 551 552 553 554 555 556
func (ps *peerScore) DuplicateMessage(msg *Message) {
	ps.Lock()
	defer ps.Unlock()

	drec := ps.deliveries.getRecord(ps.msgID(msg.Message))

	_, ok := drec.peers[msg.ReceivedFrom]
	if ok {
		// we have already seen this duplicate!
		return
	}
vyzo's avatar
vyzo committed
557

vyzo's avatar
vyzo committed
558 559
	switch drec.status {
	case delivery_unknown:
560
		// the message is being validated; track the peer delivery and wait for
vyzo's avatar
vyzo committed
561
		// the Deliver/Reject notification.
562
		drec.peers[msg.ReceivedFrom] = struct{}{}
vyzo's avatar
vyzo committed
563 564 565

	case delivery_valid:
		// mark the peer delivery time to only count a duplicate delivery once.
566
		drec.peers[msg.ReceivedFrom] = struct{}{}
567
		ps.markDuplicateMessageDelivery(msg.ReceivedFrom, msg, drec.validated)
vyzo's avatar
vyzo committed
568 569 570 571 572 573

	case delivery_invalid:
		// we no longer track delivery time
		ps.markInvalidMessageDelivery(msg.ReceivedFrom, msg)

	case delivery_throttled:
574
		// the message was throttled; do nothing (we don't know if it was valid)
vyzo's avatar
vyzo committed
575
	}
vyzo's avatar
vyzo committed
576 577
}

vyzo's avatar
vyzo committed
578 579
// message delivery records
func (d *messageDeliveries) getRecord(id string) *deliveryRecord {
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
	rec, ok := d.records[id]
	if ok {
		return rec
	}

	rec = &deliveryRecord{peers: make(map[peer.ID]struct{})}
	d.records[id] = rec

	entry := &deliveryEntry{id: id, expire: time.Now().Add(TimeCacheDuration)}
	if d.tail != nil {
		d.tail.next = entry
		d.tail = entry
	} else {
		d.head = entry
		d.tail = entry
	}

	return rec
}

func (d *messageDeliveries) gc() {
	if d.head == nil {
		return
	}

	now := time.Now()
	for d.head != nil && now.After(d.head.expire) {
		delete(d.records, d.head.id)
		d.head = d.head.next
	}

	if d.head == nil {
		d.tail = nil
	}
vyzo's avatar
vyzo committed
614 615 616 617 618 619 620 621 622 623 624 625 626
}

// utilities
func (pstats *peerStats) getTopicStats(topic string, params *PeerScoreParams) (*topicStats, bool) {
	tstats, ok := pstats.topics[topic]
	if ok {
		return tstats, true
	}

	_, scoredTopic := params.Topics[topic]
	if !scoredTopic {
		return nil, false
	}
vyzo's avatar
vyzo committed
627

vyzo's avatar
vyzo committed
628 629 630 631
	tstats = &topicStats{}
	pstats.topics[topic] = tstats

	return tstats, true
vyzo's avatar
vyzo committed
632 633
}

vyzo's avatar
vyzo committed
634 635 636 637 638 639 640 641 642 643 644
func (ps *peerScore) markInvalidMessageDelivery(p peer.ID, msg *Message) {
	pstats, ok := ps.peerStats[p]
	if !ok {
		return
	}

	for _, topic := range msg.GetTopicIDs() {
		tstats, ok := pstats.getTopicStats(topic, ps.params)
		if !ok {
			continue
		}
vyzo's avatar
vyzo committed
645

vyzo's avatar
vyzo committed
646 647
		tstats.invalidMessageDeliveries += 1
	}
vyzo's avatar
vyzo committed
648 649
}

vyzo's avatar
vyzo committed
650 651 652 653 654 655 656 657 658 659 660 661
func (ps *peerScore) markFirstMessageDelivery(p peer.ID, msg *Message) {
	pstats, ok := ps.peerStats[p]
	if !ok {
		return
	}

	for _, topic := range msg.GetTopicIDs() {
		tstats, ok := pstats.getTopicStats(topic, ps.params)
		if !ok {
			continue
		}

vyzo's avatar
vyzo committed
662
		cap := ps.params.Topics[topic].FirstMessageDeliveriesCap
vyzo's avatar
vyzo committed
663
		tstats.firstMessageDeliveries += 1
vyzo's avatar
vyzo committed
664 665
		if tstats.firstMessageDeliveries > cap {
			tstats.firstMessageDeliveries = cap
vyzo's avatar
vyzo committed
666 667 668 669 670
		}

		if !tstats.inMesh {
			continue
		}
vyzo's avatar
vyzo committed
671

vyzo's avatar
vyzo committed
672
		cap = ps.params.Topics[topic].MeshMessageDeliveriesCap
vyzo's avatar
vyzo committed
673
		tstats.meshMessageDeliveries += 1
vyzo's avatar
vyzo committed
674 675
		if tstats.meshMessageDeliveries > cap {
			tstats.meshMessageDeliveries = cap
vyzo's avatar
vyzo committed
676 677
		}
	}
vyzo's avatar
vyzo committed
678 679
}

680
func (ps *peerScore) markDuplicateMessageDelivery(p peer.ID, msg *Message, validated time.Time) {
681 682
	var now time.Time

vyzo's avatar
vyzo committed
683 684 685 686 687
	pstats, ok := ps.peerStats[p]
	if !ok {
		return
	}

688
	if !validated.IsZero() {
689 690 691
		now = time.Now()
	}

vyzo's avatar
vyzo committed
692 693 694 695 696 697 698 699 700
	for _, topic := range msg.GetTopicIDs() {
		tstats, ok := pstats.getTopicStats(topic, ps.params)
		if !ok {
			continue
		}

		if !tstats.inMesh {
			continue
		}
vyzo's avatar
vyzo committed
701

702 703 704 705
		// check against the mesh delivery window -- if the validated time is passed as 0, then
		// the message was received before we finished validation and thus falls within the mesh
		// delivery window.
		if !validated.IsZero() && now.After(validated.Add(ps.params.Topics[topic].MeshMessageDeliveriesWindow)) {
vyzo's avatar
vyzo committed
706 707 708
			continue
		}

vyzo's avatar
vyzo committed
709
		cap := ps.params.Topics[topic].MeshMessageDeliveriesCap
vyzo's avatar
vyzo committed
710
		tstats.meshMessageDeliveries += 1
vyzo's avatar
vyzo committed
711 712
		if tstats.meshMessageDeliveries > cap {
			tstats.meshMessageDeliveries = cap
vyzo's avatar
vyzo committed
713 714
		}
	}
vyzo's avatar
vyzo committed
715
}
vyzo's avatar
vyzo committed
716 717 718

// gets the current IPs for a peer
func (ps *peerScore) getIPs(p peer.ID) []string {
vyzo's avatar
vyzo committed
719 720 721 722 723 724 725 726 727
	// in unit tests this can be nil
	if ps.host == nil {
		return nil
	}

	conns := ps.host.Network().ConnsToPeer(p)
	res := make([]string, 0, len(conns))
	for _, c := range conns {
		remote := c.RemoteMultiaddr()
728 729 730 731
		ip, err := manet.ToIP(remote)
		if err != nil {
			continue
		}
vyzo's avatar
vyzo committed
732

733 734 735
		if len(ip) == 4 {
			// IPv4 address
			ip4 := ip.String()
vyzo's avatar
vyzo committed
736 737 738 739
			res = append(res, ip4)
			continue
		}

740 741 742
		if len(ip) == 16 {
			// IPv6 address -- we add both the actual address and the /64 subnet
			ip6 := ip.String()
vyzo's avatar
vyzo committed
743
			res = append(res, ip6)
744 745 746

			ip6mask := ip.Mask(net.CIDRMask(64, 128)).String()
			res = append(res, ip6mask)
vyzo's avatar
vyzo committed
747 748 749 750
		}
	}

	return res
vyzo's avatar
vyzo committed
751 752
}

vyzo's avatar
vyzo committed
753 754
//  adds tracking for the new IPs in the list, and removes tracking from the obsolete ips.
func (ps *peerScore) setIPs(p peer.ID, newips, oldips []string) {
vyzo's avatar
vyzo committed
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
addNewIPs:
	// add the new IPs to the tracking
	for _, ip := range newips {
		// check if it is in the old ips list
		for _, xip := range oldips {
			if ip == xip {
				continue addNewIPs
			}
		}
		// no, it's a new one -- add it to the tracker
		peers, ok := ps.peerIPs[ip]
		if !ok {
			peers = make(map[peer.ID]struct{})
			ps.peerIPs[ip] = peers
		}
		peers[p] = struct{}{}
	}

removeOldIPs:
	// remove the obsolete old IPs from the tracking
	for _, ip := range oldips {
		// check if it is in the new ips list
		for _, xip := range newips {
			if ip == xip {
				continue removeOldIPs
			}
			// no, it's obsolete -- remove it from the tracker
			peers, ok := ps.peerIPs[ip]
			if !ok {
				continue
			}
			delete(peers, p)
			if len(peers) == 0 {
				delete(ps.peerIPs, ip)
			}
		}
	}
}

// removes an IP list from the tracking list
func (ps *peerScore) removeIPs(p peer.ID, ips []string) {
	for _, ip := range ips {
		peers, ok := ps.peerIPs[ip]
		if !ok {
			continue
		}

		delete(peers, p)
		if len(peers) == 0 {
			delete(ps.peerIPs, ip)
		}
	}
}