12 "github.com/RoaringBitmap/roaring"
13 "github.com/anacrolix/chansync"
14 . "github.com/anacrolix/generics"
15 "github.com/anacrolix/log"
16 "github.com/anacrolix/missinggo/iter"
17 "github.com/anacrolix/missinggo/v2/bitmap"
18 "github.com/anacrolix/multiless"
20 "github.com/anacrolix/torrent/internal/alloclim"
21 "github.com/anacrolix/torrent/mse"
22 pp "github.com/anacrolix/torrent/peer_protocol"
23 request_strategy "github.com/anacrolix/torrent/request-strategy"
24 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
29 // First to ensure 64-bit alignment for atomics. See #262.
39 RemoteAddr PeerRemoteAddr
40 // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
42 localPublicAddr peerLocalPublicAddr
43 bannableAddr Option[bannableAddr]
44 // True if the connection is operating over MSE obfuscation.
46 cryptoMethod mse.CryptoMethod
49 closed chansync.SetOnce
50 // Set true after we've added our ConnStats generated during handshake to
51 // other ConnStat instances as determined when the *Torrent became known.
52 reconciledHandshakeStats bool
54 lastMessageReceived time.Time
55 completedHandshake time.Time
56 lastUsefulChunkReceived time.Time
57 lastChunkSent time.Time
59 // Stuff controlled by the local peer.
60 needRequestUpdate string
61 requestState request_strategy.PeerRequestState
62 updateRequestsTimer *time.Timer
63 lastRequestUpdate time.Time
64 peakRequests maxRequests
65 lastBecameInterested time.Time
66 priorInterest time.Duration
68 lastStartedExpectingToReceiveChunks time.Time
69 cumulativeExpectedToReceiveChunks time.Duration
70 _chunksReceivedWhileExpecting int64
73 piecesReceivedSinceLastRequestUpdate maxRequests
74 maxPiecesReceivedBetweenRequestUpdates maxRequests
75 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
76 // and implementation differences, we may receive chunks that are no longer in the set of
77 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
78 validReceiveChunks map[RequestIndex]int
79 // Indexed by metadata piece, set to true if posted and pending a
81 metadataRequests []bool
82 sentHaves bitmap.Bitmap
84 // Stuff controlled by the remote peer.
87 peerRequests map[Request]*peerRequestState
88 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
89 // The highest possible number of pieces the torrent could have based on
90 // communication with the peer. Generally only useful until we have the
92 peerMinPieces pieceIndex
93 // Pieces we've accepted chunks for from the peer.
94 peerTouchedPieces map[pieceIndex]struct{}
95 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
97 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
104 peerRequestState struct {
106 allocReservation *alloclim.Reservation
109 PeerRemoteAddr interface {
113 peerRequests = orderedBitmap[RequestIndex]
117 PeerSourceUtHolepunch = "C"
118 PeerSourceTracker = "Tr"
119 PeerSourceIncoming = "I"
120 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
121 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
123 // The peer was given directly, such as through a magnet link.
124 PeerSourceDirect = "M"
127 // Returns the Torrent a Peer belongs to. Shouldn't change for the lifetime of the Peer. May be nil
128 // if we are the receiving end of a connection and the handshake hasn't been received or accepted
130 func (p *Peer) Torrent() *Torrent {
134 func (p *Peer) initRequestState() {
135 p.requestState.Requests = &peerRequests{}
138 func (cn *Peer) updateExpectingChunks() {
139 if cn.expectingChunks() {
140 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
141 cn.lastStartedExpectingToReceiveChunks = time.Now()
144 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
145 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
146 cn.lastStartedExpectingToReceiveChunks = time.Time{}
151 func (cn *Peer) expectingChunks() bool {
152 if cn.requestState.Requests.IsEmpty() {
155 if !cn.requestState.Interested {
161 haveAllowedFastRequests := false
162 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
163 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
164 cn.requestState.Requests,
165 cn.t.pieceRequestIndexOffset(i),
166 cn.t.pieceRequestIndexOffset(i+1),
168 return !haveAllowedFastRequests
170 return haveAllowedFastRequests
173 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
174 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
177 func (cn *Peer) cumInterest() time.Duration {
178 ret := cn.priorInterest
179 if cn.requestState.Interested {
180 ret += time.Since(cn.lastBecameInterested)
185 func (cn *Peer) locker() *lockWithDeferreds {
186 return cn.t.cl.locker()
189 func (cn *PeerConn) supportsExtension(ext pp.ExtensionName) bool {
190 _, ok := cn.PeerExtensionIDs[ext]
194 // The best guess at number of pieces in the torrent for this peer.
195 func (cn *Peer) bestPeerNumPieces() pieceIndex {
197 return cn.t.numPieces()
199 return cn.peerMinPieces
202 func (cn *Peer) completedString() string {
203 have := pieceIndex(cn.peerPieces().GetCardinality())
204 if all, _ := cn.peerHasAllPieces(); all {
205 have = cn.bestPeerNumPieces()
207 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
210 func eventAgeString(t time.Time) string {
214 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
217 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
218 func (cn *Peer) statusFlags() (ret string) {
220 ret += string([]byte{b})
222 if cn.requestState.Interested {
229 ret += cn.connectionFlags()
231 if cn.peerInterested {
240 func (cn *Peer) downloadRate() float64 {
241 num := cn._stats.BytesReadUsefulData.Int64()
245 return float64(num) / cn.totalExpectingTime().Seconds()
248 func (p *Peer) DownloadRate() float64 {
250 defer p.locker().RUnlock()
252 return p.downloadRate()
255 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
256 var last Option[pieceIndex]
258 next := func(item Option[pieceIndex]) {
269 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
270 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
273 next(None[pieceIndex]())
276 func (cn *Peer) writeStatus(w io.Writer) {
277 // \t isn't preserved in <pre> blocks?
278 if cn.closed.IsSet() {
279 fmt.Fprint(w, "CLOSED: ")
281 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
282 prio, err := cn.peerPriority()
283 prioStr := fmt.Sprintf("%08x", prio)
285 prioStr += ": " + err.Error()
287 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
288 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
289 eventAgeString(cn.lastMessageReceived),
290 eventAgeString(cn.completedHandshake),
291 eventAgeString(cn.lastHelpful()),
293 cn.totalExpectingTime(),
296 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
297 cn.completedString(),
298 len(cn.peerTouchedPieces),
299 &cn._stats.ChunksReadUseful,
300 &cn._stats.ChunksRead,
301 &cn._stats.ChunksWritten,
302 cn.requestState.Requests.GetCardinality(),
303 cn.requestState.Cancelled.GetCardinality(),
304 cn.nominalMaxRequests(),
306 len(cn.peerRequests),
309 cn.downloadRate()/(1<<10),
311 fmt.Fprintf(w, "requested pieces:")
312 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
313 fmt.Fprintf(w, " %v(%v)", piece, count)
318 func (p *Peer) close() {
322 if p.updateRequestsTimer != nil {
323 p.updateRequestsTimer.Stop()
325 for _, prs := range p.peerRequests {
326 prs.allocReservation.Drop()
330 p.t.decPeerPieceAvailability(p)
332 for _, f := range p.callbacks.PeerClosed {
337 func (p *Peer) Close() error {
339 defer p.locker().Unlock()
344 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
345 // they do (known=true).
346 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
347 if all, known := cn.peerHasAllPieces(); all && known {
350 return cn.peerPieces().ContainsInt(piece)
353 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
354 // https://github.com/pion/datachannel/issues/59 is fixed.
356 writeBufferHighWaterLen = 1 << 15
357 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
361 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
362 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
363 // This is the maximum request count that could fit in the write buffer if it's at or below the
364 // low water mark when we run maybeUpdateActualRequestState.
365 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
368 // The actual value to use as the maximum outbound requests.
369 func (cn *Peer) nominalMaxRequests() maxRequests {
370 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
373 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
374 ret = cn.cumulativeExpectedToReceiveChunks
375 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
376 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
381 func (cn *Peer) setInterested(interested bool) bool {
382 if cn.requestState.Interested == interested {
385 cn.requestState.Interested = interested
387 cn.lastBecameInterested = time.Now()
388 } else if !cn.lastBecameInterested.IsZero() {
389 cn.priorInterest += time.Since(cn.lastBecameInterested)
391 cn.updateExpectingChunks()
392 // log.Printf("%p: setting interest: %v", cn, interested)
393 return cn.writeInterested(interested)
396 // The function takes a message to be sent, and returns true if more messages
398 type messageWriter func(pp.Message) bool
400 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
401 // when we want to go fast.
402 func (cn *Peer) shouldRequest(r RequestIndex) error {
403 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
407 pi := cn.t.pieceIndexOfRequestIndex(r)
408 if cn.requestState.Cancelled.Contains(r) {
409 return errors.New("request is cancelled and waiting acknowledgement")
411 if !cn.peerHasPiece(pi) {
412 return errors.New("requesting piece peer doesn't have")
414 if !cn.t.peerIsActive(cn) {
415 panic("requesting but not in active conns")
417 if cn.closed.IsSet() {
418 panic("requesting when connection is closed")
420 if cn.t.hashingPiece(pi) {
421 panic("piece is being hashed")
423 if cn.t.pieceQueuedForHash(pi) {
424 panic("piece is queued for hash")
426 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
427 // This could occur if we made a request with the fast extension, and then got choked and
428 // haven't had the request rejected yet.
429 if !cn.requestState.Requests.Contains(r) {
430 panic("peer choking and piece not allowed fast")
436 func (cn *Peer) mustRequest(r RequestIndex) bool {
437 more, err := cn.request(r)
444 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
445 if err := cn.shouldRequest(r); err != nil {
448 if cn.requestState.Requests.Contains(r) {
451 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
452 return true, errors.New("too many outstanding requests")
454 cn.requestState.Requests.Add(r)
455 if cn.validReceiveChunks == nil {
456 cn.validReceiveChunks = make(map[RequestIndex]int)
458 cn.validReceiveChunks[r]++
459 cn.t.requestState[r] = requestState{
463 cn.updateExpectingChunks()
464 ppReq := cn.t.requestIndexToRequest(r)
465 for _, f := range cn.callbacks.SentRequest {
466 f(PeerRequestEvent{cn, ppReq})
468 return cn.peerImpl._request(ppReq), nil
471 func (me *Peer) cancel(r RequestIndex) {
472 if !me.deleteRequest(r) {
473 panic("request not existing should have been guarded")
476 // Record that we expect to get a cancel ack.
477 if !me.requestState.Cancelled.CheckedAdd(r) {
478 panic("request already cancelled")
482 if me.isLowOnRequests() {
483 me.updateRequests("Peer.cancel")
487 // Sets a reason to update requests, and if there wasn't already one, handle it.
488 func (cn *Peer) updateRequests(reason string) {
489 if cn.needRequestUpdate != "" {
492 cn.needRequestUpdate = reason
493 cn.handleUpdateRequests()
496 // Emits the indices in the Bitmaps bms in order, never repeating any index.
497 // skip is mutated during execution, and its initial values will never be
499 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
500 return func(cb iter.Callback) {
501 for _, bm := range bms {
503 func(_i interface{}) bool {
505 if skip.Contains(bitmap.BitIndex(i)) {
508 skip.Add(bitmap.BitIndex(i))
519 // After handshake, we know what Torrent and Client stats to include for a
521 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
527 // All ConnStats that include this connection. Some objects are not known
528 // until the handshake is complete, after which it's expected to reconcile the
530 func (cn *Peer) allStats(f func(*ConnStats)) {
532 if cn.reconciledHandshakeStats {
533 cn.postHandshakeStats(f)
537 func (cn *Peer) readBytes(n int64) {
538 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
541 func (c *Peer) lastHelpful() (ret time.Time) {
542 ret = c.lastUsefulChunkReceived
543 if c.t.seeding() && c.lastChunkSent.After(ret) {
544 ret = c.lastChunkSent
549 // Returns whether any part of the chunk would lie outside a piece of the given length.
550 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
554 case cs.Begin+cs.Length > pieceLength:
555 // Check for integer overflow
556 case cs.Begin > pp.IntegerMax-cs.Length:
561 func runSafeExtraneous(f func()) {
569 // Returns true if it was valid to reject the request.
570 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
571 if c.deleteRequest(r) {
573 } else if !c.requestState.Cancelled.CheckedRemove(r) {
576 if c.isLowOnRequests() {
577 c.updateRequests("Peer.remoteRejectedRequest")
579 c.decExpectedChunkReceive(r)
583 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
584 count := c.validReceiveChunks[r]
586 delete(c.validReceiveChunks, r)
587 } else if count > 1 {
588 c.validReceiveChunks[r] = count - 1
594 func (c *Peer) doChunkReadStats(size int64) {
595 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
598 // Handle a received chunk from a peer.
599 func (c *Peer) receiveChunk(msg *pp.Message) error {
600 chunksReceived.Add("total", 1)
602 ppReq := newRequestFromMessage(msg)
604 err := t.checkValidReceiveChunk(ppReq)
606 err = log.WithLevel(log.Warning, err)
609 req := c.t.requestIndexFromRequest(ppReq)
611 recordBlockForSmartBan := sync.OnceFunc(func() {
612 c.recordBlockForSmartBan(req, msg.Piece)
614 // This needs to occur before we return, but we try to do it when the client is unlocked. It
615 // can't be done before checking if chunks are valid because they won't be deallocated by piece
616 // hashing if they're out of bounds.
617 defer recordBlockForSmartBan()
620 chunksReceived.Add("while choked", 1)
623 if c.validReceiveChunks[req] <= 0 {
624 chunksReceived.Add("unexpected", 1)
625 return errors.New("received unexpected chunk")
627 c.decExpectedChunkReceive(req)
629 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
630 chunksReceived.Add("due to allowed fast", 1)
633 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
634 // have actually already received the piece, while we have the Client unlocked to write the data
638 if c.requestState.Requests.Contains(req) {
639 for _, f := range c.callbacks.ReceivedRequested {
640 f(PeerMessageEvent{c, msg})
643 // Request has been satisfied.
644 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
647 c._chunksReceivedWhileExpecting++
649 if c.isLowOnRequests() {
650 c.updateRequests("Peer.receiveChunk deleted request")
653 chunksReceived.Add("unintended", 1)
659 // Do we actually want this chunk?
660 if t.haveChunk(ppReq) {
661 // panic(fmt.Sprintf("%+v", ppReq))
662 chunksReceived.Add("redundant", 1)
663 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
667 piece := &t.pieces[ppReq.Index]
669 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
670 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
672 c.piecesReceivedSinceLastRequestUpdate++
673 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
675 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
676 f(ReceivedUsefulDataEvent{c, msg})
678 c.lastUsefulChunkReceived = time.Now()
680 // Need to record that it hasn't been written yet, before we attempt to do
682 piece.incrementPendingWrites()
683 // Record that we have the chunk, so we aren't trying to download it while
684 // waiting for it to be written to storage.
685 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
687 // Cancel pending requests for this chunk from *other* peers.
688 if p := t.requestingPeer(req); p != nil {
690 panic("should not be pending request from conn that just received it")
698 // Opportunistically do this here while we aren't holding the client lock.
699 recordBlockForSmartBan()
700 concurrentChunkWrites.Add(1)
701 defer concurrentChunkWrites.Add(-1)
702 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
703 // number of connections. We write inline with receiving the chunk (with this lock dance),
704 // because we want to handle errors synchronously and I haven't thought of a nice way to
705 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
707 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
710 piece.decrementPendingWrites()
713 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
715 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
716 // request update runs while we're writing the chunk that just failed. Then we never do a
717 // fresh update after pending the failed request.
718 c.updateRequests("Peer.receiveChunk error writing chunk")
719 t.onWriteChunkErr(err)
723 c.onDirtiedPiece(pieceIndex(ppReq.Index))
725 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
726 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
727 t.queuePieceCheck(pieceIndex(ppReq.Index))
728 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
729 // chunk status (such as the haveChunk call above) to have to check all the various other
730 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
731 // that chunk pieces are pended at an appropriate time later however.
735 // We do this because we've written a chunk, and may change PieceState.Partial.
736 t.publishPieceStateChange(pieceIndex(ppReq.Index))
741 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
742 if c.peerTouchedPieces == nil {
743 c.peerTouchedPieces = make(map[pieceIndex]struct{})
745 c.peerTouchedPieces[piece] = struct{}{}
746 ds := &c.t.pieces[piece].dirtiers
748 *ds = make(map[*Peer]struct{})
750 (*ds)[c] = struct{}{}
753 func (cn *Peer) netGoodPiecesDirtied() int64 {
754 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
757 func (c *Peer) peerHasWantedPieces() bool {
758 if all, _ := c.peerHasAllPieces(); all {
759 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
762 return !c.peerPieces().IsEmpty()
764 return c.peerPieces().Intersects(&c.t._pendingPieces)
767 // Returns true if an outstanding request is removed. Cancelled requests should be handled
769 func (c *Peer) deleteRequest(r RequestIndex) bool {
770 if !c.requestState.Requests.CheckedRemove(r) {
773 for _, f := range c.callbacks.DeletedRequest {
774 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
776 c.updateExpectingChunks()
777 if c.t.requestingPeer(r) != c {
778 panic("only one peer should have a given request at a time")
780 delete(c.t.requestState, r)
781 // c.t.iterPeers(func(p *Peer) {
782 // if p.isLowOnRequests() {
783 // p.updateRequests("Peer.deleteRequest")
789 func (c *Peer) deleteAllRequests(reason string) {
790 if c.requestState.Requests.IsEmpty() {
793 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
794 if !c.deleteRequest(x) {
795 panic("request should exist")
800 c.t.iterPeers(func(p *Peer) {
801 if p.isLowOnRequests() {
802 p.updateRequests(reason)
808 func (c *Peer) assertNoRequests() {
809 if !c.requestState.Requests.IsEmpty() {
810 panic(c.requestState.Requests.GetCardinality())
814 func (c *Peer) cancelAllRequests() {
815 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
823 func (c *Peer) peerPriority() (peerPriority, error) {
824 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
827 func (c *Peer) remoteIp() net.IP {
828 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
829 return net.ParseIP(host)
832 func (c *Peer) remoteIpPort() IpPort {
833 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
834 return IpPort{ipa.IP, uint16(ipa.Port)}
837 func (c *Peer) trust() connectionTrust {
838 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
841 type connectionTrust struct {
843 NetGoodPiecesDirted int64
846 func (l connectionTrust) Less(r connectionTrust) bool {
847 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
850 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
851 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
852 // TODO: Can we use copy on write?
853 ret := cn.peerPieces().Clone()
854 if all, _ := cn.peerHasAllPieces(); all {
856 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
858 ret.AddRange(0, bitmap.ToEnd)
864 func (cn *Peer) stats() *ConnStats {
868 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
869 pc, ok := p.peerImpl.(*PeerConn)
873 func (p *Peer) uncancelledRequests() uint64 {
874 return p.requestState.Requests.GetCardinality()
877 type peerLocalPublicAddr = IpPort
879 func (p *Peer) isLowOnRequests() bool {
880 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
883 func (p *Peer) decPeakRequests() {
884 // // This can occur when peak requests are altered by the update request timer to be lower than
885 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
886 // // wonder what happens if maxRequests is not signed.
887 // if p.peakRequests < 1 {
888 // panic(p.peakRequests)
893 func (p *Peer) recordBlockForSmartBan(req RequestIndex, blockData []byte) {
894 if p.bannableAddr.Ok {
895 p.t.smartBanCache.RecordBlock(p.bannableAddr.Value, req, blockData)