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.
100 protocolLogger log.Logger
105 peerRequestState struct {
107 allocReservation *alloclim.Reservation
110 PeerRemoteAddr interface {
114 peerRequests = orderedBitmap[RequestIndex]
118 PeerSourceUtHolepunch = "C"
119 PeerSourceTracker = "Tr"
120 PeerSourceIncoming = "I"
121 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
122 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
124 // The peer was given directly, such as through a magnet link.
125 PeerSourceDirect = "M"
128 // Returns the Torrent a Peer belongs to. Shouldn't change for the lifetime of the Peer. May be nil
129 // if we are the receiving end of a connection and the handshake hasn't been received or accepted
131 func (p *Peer) Torrent() *Torrent {
135 func (p *Peer) initRequestState() {
136 p.requestState.Requests = &peerRequests{}
139 func (cn *Peer) updateExpectingChunks() {
140 if cn.expectingChunks() {
141 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
142 cn.lastStartedExpectingToReceiveChunks = time.Now()
145 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
146 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
147 cn.lastStartedExpectingToReceiveChunks = time.Time{}
152 func (cn *Peer) expectingChunks() bool {
153 if cn.requestState.Requests.IsEmpty() {
156 if !cn.requestState.Interested {
162 haveAllowedFastRequests := false
163 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
164 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
165 cn.requestState.Requests,
166 cn.t.pieceRequestIndexOffset(i),
167 cn.t.pieceRequestIndexOffset(i+1),
169 return !haveAllowedFastRequests
171 return haveAllowedFastRequests
174 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
175 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
178 func (cn *Peer) cumInterest() time.Duration {
179 ret := cn.priorInterest
180 if cn.requestState.Interested {
181 ret += time.Since(cn.lastBecameInterested)
186 func (cn *Peer) locker() *lockWithDeferreds {
187 return cn.t.cl.locker()
190 func (cn *PeerConn) supportsExtension(ext pp.ExtensionName) bool {
191 _, ok := cn.PeerExtensionIDs[ext]
195 // The best guess at number of pieces in the torrent for this peer.
196 func (cn *Peer) bestPeerNumPieces() pieceIndex {
198 return cn.t.numPieces()
200 return cn.peerMinPieces
203 func (cn *Peer) completedString() string {
204 have := pieceIndex(cn.peerPieces().GetCardinality())
205 if all, _ := cn.peerHasAllPieces(); all {
206 have = cn.bestPeerNumPieces()
208 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
211 func eventAgeString(t time.Time) string {
215 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
218 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
219 func (cn *Peer) statusFlags() (ret string) {
221 ret += string([]byte{b})
223 if cn.requestState.Interested {
230 ret += cn.connectionFlags()
232 if cn.peerInterested {
241 func (cn *Peer) downloadRate() float64 {
242 num := cn._stats.BytesReadUsefulData.Int64()
246 return float64(num) / cn.totalExpectingTime().Seconds()
249 func (p *Peer) DownloadRate() float64 {
251 defer p.locker().RUnlock()
253 return p.downloadRate()
256 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
257 var last Option[pieceIndex]
259 next := func(item Option[pieceIndex]) {
270 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
271 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
274 next(None[pieceIndex]())
277 func (cn *Peer) writeStatus(w io.Writer) {
278 // \t isn't preserved in <pre> blocks?
279 if cn.closed.IsSet() {
280 fmt.Fprint(w, "CLOSED: ")
282 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
283 prio, err := cn.peerPriority()
284 prioStr := fmt.Sprintf("%08x", prio)
286 prioStr += ": " + err.Error()
288 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
289 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
290 eventAgeString(cn.lastMessageReceived),
291 eventAgeString(cn.completedHandshake),
292 eventAgeString(cn.lastHelpful()),
294 cn.totalExpectingTime(),
297 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
298 cn.completedString(),
299 len(cn.peerTouchedPieces),
300 &cn._stats.ChunksReadUseful,
301 &cn._stats.ChunksRead,
302 &cn._stats.ChunksWritten,
303 cn.requestState.Requests.GetCardinality(),
304 cn.requestState.Cancelled.GetCardinality(),
305 cn.nominalMaxRequests(),
307 len(cn.peerRequests),
310 cn.downloadRate()/(1<<10),
312 fmt.Fprintf(w, "requested pieces:")
313 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
314 fmt.Fprintf(w, " %v(%v)", piece, count)
319 func (p *Peer) close() {
323 if p.updateRequestsTimer != nil {
324 p.updateRequestsTimer.Stop()
326 for _, prs := range p.peerRequests {
327 prs.allocReservation.Drop()
331 p.t.decPeerPieceAvailability(p)
333 for _, f := range p.callbacks.PeerClosed {
338 func (p *Peer) Close() error {
340 defer p.locker().Unlock()
345 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
346 // they do (known=true).
347 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
348 if all, known := cn.peerHasAllPieces(); all && known {
351 return cn.peerPieces().ContainsInt(piece)
354 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
355 // https://github.com/pion/datachannel/issues/59 is fixed.
357 writeBufferHighWaterLen = 1 << 15
358 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
362 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
363 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
364 // This is the maximum request count that could fit in the write buffer if it's at or below the
365 // low water mark when we run maybeUpdateActualRequestState.
366 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
369 // The actual value to use as the maximum outbound requests.
370 func (cn *Peer) nominalMaxRequests() maxRequests {
371 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
374 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
375 ret = cn.cumulativeExpectedToReceiveChunks
376 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
377 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
382 func (cn *Peer) setInterested(interested bool) bool {
383 if cn.requestState.Interested == interested {
386 cn.requestState.Interested = interested
388 cn.lastBecameInterested = time.Now()
389 } else if !cn.lastBecameInterested.IsZero() {
390 cn.priorInterest += time.Since(cn.lastBecameInterested)
392 cn.updateExpectingChunks()
393 // log.Printf("%p: setting interest: %v", cn, interested)
394 return cn.writeInterested(interested)
397 // The function takes a message to be sent, and returns true if more messages
399 type messageWriter func(pp.Message) bool
401 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
402 // when we want to go fast.
403 func (cn *Peer) shouldRequest(r RequestIndex) error {
404 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
408 pi := cn.t.pieceIndexOfRequestIndex(r)
409 if cn.requestState.Cancelled.Contains(r) {
410 return errors.New("request is cancelled and waiting acknowledgement")
412 if !cn.peerHasPiece(pi) {
413 return errors.New("requesting piece peer doesn't have")
415 if !cn.t.peerIsActive(cn) {
416 panic("requesting but not in active conns")
418 if cn.closed.IsSet() {
419 panic("requesting when connection is closed")
421 if cn.t.hashingPiece(pi) {
422 panic("piece is being hashed")
424 if cn.t.pieceQueuedForHash(pi) {
425 panic("piece is queued for hash")
427 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
428 // This could occur if we made a request with the fast extension, and then got choked and
429 // haven't had the request rejected yet.
430 if !cn.requestState.Requests.Contains(r) {
431 panic("peer choking and piece not allowed fast")
437 func (cn *Peer) mustRequest(r RequestIndex) bool {
438 more, err := cn.request(r)
445 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
446 if err := cn.shouldRequest(r); err != nil {
449 if cn.requestState.Requests.Contains(r) {
452 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
453 return true, errors.New("too many outstanding requests")
455 cn.requestState.Requests.Add(r)
456 if cn.validReceiveChunks == nil {
457 cn.validReceiveChunks = make(map[RequestIndex]int)
459 cn.validReceiveChunks[r]++
460 cn.t.requestState[r] = requestState{
464 cn.updateExpectingChunks()
465 ppReq := cn.t.requestIndexToRequest(r)
466 for _, f := range cn.callbacks.SentRequest {
467 f(PeerRequestEvent{cn, ppReq})
469 return cn.peerImpl._request(ppReq), nil
472 func (me *Peer) cancel(r RequestIndex) {
473 if !me.deleteRequest(r) {
474 panic("request not existing should have been guarded")
477 // Record that we expect to get a cancel ack.
478 if !me.requestState.Cancelled.CheckedAdd(r) {
479 panic("request already cancelled")
483 if me.isLowOnRequests() {
484 me.updateRequests("Peer.cancel")
488 // Sets a reason to update requests, and if there wasn't already one, handle it.
489 func (cn *Peer) updateRequests(reason string) {
490 if cn.needRequestUpdate != "" {
493 cn.needRequestUpdate = reason
494 cn.handleUpdateRequests()
497 // Emits the indices in the Bitmaps bms in order, never repeating any index.
498 // skip is mutated during execution, and its initial values will never be
500 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
501 return func(cb iter.Callback) {
502 for _, bm := range bms {
504 func(_i interface{}) bool {
506 if skip.Contains(bitmap.BitIndex(i)) {
509 skip.Add(bitmap.BitIndex(i))
520 // After handshake, we know what Torrent and Client stats to include for a
522 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
528 // All ConnStats that include this connection. Some objects are not known
529 // until the handshake is complete, after which it's expected to reconcile the
531 func (cn *Peer) allStats(f func(*ConnStats)) {
533 if cn.reconciledHandshakeStats {
534 cn.postHandshakeStats(f)
538 func (cn *Peer) readBytes(n int64) {
539 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
542 func (c *Peer) lastHelpful() (ret time.Time) {
543 ret = c.lastUsefulChunkReceived
544 if c.t.seeding() && c.lastChunkSent.After(ret) {
545 ret = c.lastChunkSent
550 // Returns whether any part of the chunk would lie outside a piece of the given length.
551 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
555 case cs.Begin+cs.Length > pieceLength:
556 // Check for integer overflow
557 case cs.Begin > pp.IntegerMax-cs.Length:
562 func runSafeExtraneous(f func()) {
570 // Returns true if it was valid to reject the request.
571 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
572 if c.deleteRequest(r) {
574 } else if !c.requestState.Cancelled.CheckedRemove(r) {
577 if c.isLowOnRequests() {
578 c.updateRequests("Peer.remoteRejectedRequest")
580 c.decExpectedChunkReceive(r)
584 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
585 count := c.validReceiveChunks[r]
587 delete(c.validReceiveChunks, r)
588 } else if count > 1 {
589 c.validReceiveChunks[r] = count - 1
595 func (c *Peer) doChunkReadStats(size int64) {
596 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
599 // Handle a received chunk from a peer.
600 func (c *Peer) receiveChunk(msg *pp.Message) error {
601 chunksReceived.Add("total", 1)
603 ppReq := newRequestFromMessage(msg)
605 err := t.checkValidReceiveChunk(ppReq)
607 err = log.WithLevel(log.Warning, err)
610 req := c.t.requestIndexFromRequest(ppReq)
612 recordBlockForSmartBan := sync.OnceFunc(func() {
613 c.recordBlockForSmartBan(req, msg.Piece)
615 // This needs to occur before we return, but we try to do it when the client is unlocked. It
616 // can't be done before checking if chunks are valid because they won't be deallocated by piece
617 // hashing if they're out of bounds.
618 defer recordBlockForSmartBan()
621 chunksReceived.Add("while choked", 1)
624 if c.validReceiveChunks[req] <= 0 {
625 chunksReceived.Add("unexpected", 1)
626 return errors.New("received unexpected chunk")
628 c.decExpectedChunkReceive(req)
630 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
631 chunksReceived.Add("due to allowed fast", 1)
634 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
635 // have actually already received the piece, while we have the Client unlocked to write the data
639 if c.requestState.Requests.Contains(req) {
640 for _, f := range c.callbacks.ReceivedRequested {
641 f(PeerMessageEvent{c, msg})
644 // Request has been satisfied.
645 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
648 c._chunksReceivedWhileExpecting++
650 if c.isLowOnRequests() {
651 c.updateRequests("Peer.receiveChunk deleted request")
654 chunksReceived.Add("unintended", 1)
660 // Do we actually want this chunk?
661 if t.haveChunk(ppReq) {
662 // panic(fmt.Sprintf("%+v", ppReq))
663 chunksReceived.Add("redundant", 1)
664 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
668 piece := &t.pieces[ppReq.Index]
670 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
671 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
673 c.piecesReceivedSinceLastRequestUpdate++
674 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
676 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
677 f(ReceivedUsefulDataEvent{c, msg})
679 c.lastUsefulChunkReceived = time.Now()
681 // Need to record that it hasn't been written yet, before we attempt to do
683 piece.incrementPendingWrites()
684 // Record that we have the chunk, so we aren't trying to download it while
685 // waiting for it to be written to storage.
686 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
688 // Cancel pending requests for this chunk from *other* peers.
689 if p := t.requestingPeer(req); p != nil {
691 panic("should not be pending request from conn that just received it")
699 // Opportunistically do this here while we aren't holding the client lock.
700 recordBlockForSmartBan()
701 concurrentChunkWrites.Add(1)
702 defer concurrentChunkWrites.Add(-1)
703 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
704 // number of connections. We write inline with receiving the chunk (with this lock dance),
705 // because we want to handle errors synchronously and I haven't thought of a nice way to
706 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
708 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
711 piece.decrementPendingWrites()
714 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
716 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
717 // request update runs while we're writing the chunk that just failed. Then we never do a
718 // fresh update after pending the failed request.
719 c.updateRequests("Peer.receiveChunk error writing chunk")
720 t.onWriteChunkErr(err)
724 c.onDirtiedPiece(pieceIndex(ppReq.Index))
726 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
727 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
728 t.queuePieceCheck(pieceIndex(ppReq.Index))
729 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
730 // chunk status (such as the haveChunk call above) to have to check all the various other
731 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
732 // that chunk pieces are pended at an appropriate time later however.
736 // We do this because we've written a chunk, and may change PieceState.Partial.
737 t.publishPieceStateChange(pieceIndex(ppReq.Index))
742 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
743 if c.peerTouchedPieces == nil {
744 c.peerTouchedPieces = make(map[pieceIndex]struct{})
746 c.peerTouchedPieces[piece] = struct{}{}
747 ds := &c.t.pieces[piece].dirtiers
749 *ds = make(map[*Peer]struct{})
751 (*ds)[c] = struct{}{}
754 func (cn *Peer) netGoodPiecesDirtied() int64 {
755 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
758 func (c *Peer) peerHasWantedPieces() bool {
759 if all, _ := c.peerHasAllPieces(); all {
760 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
763 return !c.peerPieces().IsEmpty()
765 return c.peerPieces().Intersects(&c.t._pendingPieces)
768 // Returns true if an outstanding request is removed. Cancelled requests should be handled
770 func (c *Peer) deleteRequest(r RequestIndex) bool {
771 if !c.requestState.Requests.CheckedRemove(r) {
774 for _, f := range c.callbacks.DeletedRequest {
775 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
777 c.updateExpectingChunks()
778 if c.t.requestingPeer(r) != c {
779 panic("only one peer should have a given request at a time")
781 delete(c.t.requestState, r)
782 // c.t.iterPeers(func(p *Peer) {
783 // if p.isLowOnRequests() {
784 // p.updateRequests("Peer.deleteRequest")
790 func (c *Peer) deleteAllRequests(reason string) {
791 if c.requestState.Requests.IsEmpty() {
794 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
795 if !c.deleteRequest(x) {
796 panic("request should exist")
801 c.t.iterPeers(func(p *Peer) {
802 if p.isLowOnRequests() {
803 p.updateRequests(reason)
809 func (c *Peer) assertNoRequests() {
810 if !c.requestState.Requests.IsEmpty() {
811 panic(c.requestState.Requests.GetCardinality())
815 func (c *Peer) cancelAllRequests() {
816 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
824 func (c *Peer) peerPriority() (peerPriority, error) {
825 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
828 func (c *Peer) remoteIp() net.IP {
829 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
830 return net.ParseIP(host)
833 func (c *Peer) remoteIpPort() IpPort {
834 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
835 return IpPort{ipa.IP, uint16(ipa.Port)}
838 func (c *Peer) trust() connectionTrust {
839 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
842 type connectionTrust struct {
844 NetGoodPiecesDirted int64
847 func (l connectionTrust) Less(r connectionTrust) bool {
848 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
851 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
852 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
853 // TODO: Can we use copy on write?
854 ret := cn.peerPieces().Clone()
855 if all, _ := cn.peerHasAllPieces(); all {
857 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
859 ret.AddRange(0, bitmap.ToEnd)
865 func (cn *Peer) stats() *ConnStats {
869 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
870 pc, ok := p.peerImpl.(*PeerConn)
874 func (p *Peer) uncancelledRequests() uint64 {
875 return p.requestState.Requests.GetCardinality()
878 type peerLocalPublicAddr = IpPort
880 func (p *Peer) isLowOnRequests() bool {
881 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
884 func (p *Peer) decPeakRequests() {
885 // // This can occur when peak requests are altered by the update request timer to be lower than
886 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
887 // // wonder what happens if maxRequests is not signed.
888 // if p.peakRequests < 1 {
889 // panic(p.peakRequests)
894 func (p *Peer) recordBlockForSmartBan(req RequestIndex, blockData []byte) {
895 if p.bannableAddr.Ok {
896 p.t.smartBanCache.RecordBlock(p.bannableAddr.Value, req, blockData)