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 "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
90 // The highest possible number of pieces the torrent could have based on
91 // communication with the peer. Generally only useful until we have the
93 peerMinPieces pieceIndex
94 // Pieces we've accepted chunks for from the peer.
95 peerTouchedPieces map[pieceIndex]struct{}
96 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
98 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
99 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
100 PeerClientName atomic.Value
107 peerRequestState struct {
109 allocReservation *alloclim.Reservation
112 PeerRemoteAddr interface {
116 peerRequests = orderedBitmap[RequestIndex]
120 PeerSourceTracker = "Tr"
121 PeerSourceIncoming = "I"
122 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
123 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
125 // The peer was given directly, such as through a magnet link.
126 PeerSourceDirect = "M"
129 // Returns the Torrent a Peer belongs to. Shouldn't change for the lifetime of the Peer. May be nil
130 // if we are the receiving end of a connection and the handshake hasn't been received or accepted
132 func (p *Peer) Torrent() *Torrent {
136 func (p *Peer) initRequestState() {
137 p.requestState.Requests = &peerRequests{}
140 func (cn *Peer) updateExpectingChunks() {
141 if cn.expectingChunks() {
142 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
143 cn.lastStartedExpectingToReceiveChunks = time.Now()
146 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
147 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
148 cn.lastStartedExpectingToReceiveChunks = time.Time{}
153 func (cn *Peer) expectingChunks() bool {
154 if cn.requestState.Requests.IsEmpty() {
157 if !cn.requestState.Interested {
163 haveAllowedFastRequests := false
164 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
165 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
166 cn.requestState.Requests,
167 cn.t.pieceRequestIndexOffset(i),
168 cn.t.pieceRequestIndexOffset(i+1),
170 return !haveAllowedFastRequests
172 return haveAllowedFastRequests
175 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
176 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
179 func (cn *Peer) cumInterest() time.Duration {
180 ret := cn.priorInterest
181 if cn.requestState.Interested {
182 ret += time.Since(cn.lastBecameInterested)
187 func (cn *Peer) locker() *lockWithDeferreds {
188 return cn.t.cl.locker()
191 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
192 _, ok := cn.PeerExtensionIDs[ext]
196 // The best guess at number of pieces in the torrent for this peer.
197 func (cn *Peer) bestPeerNumPieces() pieceIndex {
199 return cn.t.numPieces()
201 return cn.peerMinPieces
204 func (cn *Peer) completedString() string {
205 have := pieceIndex(cn.peerPieces().GetCardinality())
206 if all, _ := cn.peerHasAllPieces(); all {
207 have = cn.bestPeerNumPieces()
209 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
212 func eventAgeString(t time.Time) string {
216 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
219 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
220 func (cn *Peer) statusFlags() (ret string) {
222 ret += string([]byte{b})
224 if cn.requestState.Interested {
231 ret += cn.connectionFlags()
233 if cn.peerInterested {
242 func (cn *Peer) downloadRate() float64 {
243 num := cn._stats.BytesReadUsefulData.Int64()
247 return float64(num) / cn.totalExpectingTime().Seconds()
250 func (cn *Peer) DownloadRate() float64 {
252 defer cn.locker().RUnlock()
254 return cn.downloadRate()
257 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
258 var last Option[pieceIndex]
260 next := func(item Option[pieceIndex]) {
271 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
272 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
275 next(None[pieceIndex]())
278 func (cn *Peer) writeStatus(w io.Writer) {
279 // \t isn't preserved in <pre> blocks?
280 if cn.closed.IsSet() {
281 fmt.Fprint(w, "CLOSED: ")
283 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
284 prio, err := cn.peerPriority()
285 prioStr := fmt.Sprintf("%08x", prio)
287 prioStr += ": " + err.Error()
289 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
290 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
291 eventAgeString(cn.lastMessageReceived),
292 eventAgeString(cn.completedHandshake),
293 eventAgeString(cn.lastHelpful()),
295 cn.totalExpectingTime(),
298 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
299 cn.completedString(),
300 len(cn.peerTouchedPieces),
301 &cn._stats.ChunksReadUseful,
302 &cn._stats.ChunksRead,
303 &cn._stats.ChunksWritten,
304 cn.requestState.Requests.GetCardinality(),
305 cn.requestState.Cancelled.GetCardinality(),
306 cn.nominalMaxRequests(),
308 len(cn.peerRequests),
311 cn.downloadRate()/(1<<10),
313 fmt.Fprintf(w, "requested pieces:")
314 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
315 fmt.Fprintf(w, " %v(%v)", piece, count)
320 func (p *Peer) close() {
324 if p.updateRequestsTimer != nil {
325 p.updateRequestsTimer.Stop()
329 p.t.decPeerPieceAvailability(p)
331 for _, f := range p.callbacks.PeerClosed {
336 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
337 // they do (known=true).
338 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
339 if all, known := cn.peerHasAllPieces(); all && known {
342 return cn.peerPieces().ContainsInt(piece)
345 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
346 // https://github.com/pion/datachannel/issues/59 is fixed.
348 writeBufferHighWaterLen = 1 << 15
349 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
353 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
354 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
355 // This is the maximum request count that could fit in the write buffer if it's at or below the
356 // low water mark when we run maybeUpdateActualRequestState.
357 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
360 // The actual value to use as the maximum outbound requests.
361 func (cn *Peer) nominalMaxRequests() maxRequests {
362 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
365 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
366 ret = cn.cumulativeExpectedToReceiveChunks
367 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
368 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
373 func (cn *Peer) setInterested(interested bool) bool {
374 if cn.requestState.Interested == interested {
377 cn.requestState.Interested = interested
379 cn.lastBecameInterested = time.Now()
380 } else if !cn.lastBecameInterested.IsZero() {
381 cn.priorInterest += time.Since(cn.lastBecameInterested)
383 cn.updateExpectingChunks()
384 // log.Printf("%p: setting interest: %v", cn, interested)
385 return cn.writeInterested(interested)
388 // The function takes a message to be sent, and returns true if more messages
390 type messageWriter func(pp.Message) bool
392 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
393 // when we want to go fast.
394 func (cn *Peer) shouldRequest(r RequestIndex) error {
395 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
399 pi := cn.t.pieceIndexOfRequestIndex(r)
400 if cn.requestState.Cancelled.Contains(r) {
401 return errors.New("request is cancelled and waiting acknowledgement")
403 if !cn.peerHasPiece(pi) {
404 return errors.New("requesting piece peer doesn't have")
406 if !cn.t.peerIsActive(cn) {
407 panic("requesting but not in active conns")
409 if cn.closed.IsSet() {
410 panic("requesting when connection is closed")
412 if cn.t.hashingPiece(pi) {
413 panic("piece is being hashed")
415 if cn.t.pieceQueuedForHash(pi) {
416 panic("piece is queued for hash")
418 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
419 // This could occur if we made a request with the fast extension, and then got choked and
420 // haven't had the request rejected yet.
421 if !cn.requestState.Requests.Contains(r) {
422 panic("peer choking and piece not allowed fast")
428 func (cn *Peer) mustRequest(r RequestIndex) bool {
429 more, err := cn.request(r)
436 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
437 if err := cn.shouldRequest(r); err != nil {
440 if cn.requestState.Requests.Contains(r) {
443 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
444 return true, errors.New("too many outstanding requests")
446 cn.requestState.Requests.Add(r)
447 if cn.validReceiveChunks == nil {
448 cn.validReceiveChunks = make(map[RequestIndex]int)
450 cn.validReceiveChunks[r]++
451 cn.t.requestState[r] = requestState{
455 cn.updateExpectingChunks()
456 ppReq := cn.t.requestIndexToRequest(r)
457 for _, f := range cn.callbacks.SentRequest {
458 f(PeerRequestEvent{cn, ppReq})
460 return cn.peerImpl._request(ppReq), nil
463 func (me *Peer) cancel(r RequestIndex) {
464 if !me.deleteRequest(r) {
465 panic("request not existing should have been guarded")
468 if !me.requestState.Cancelled.CheckedAdd(r) {
469 panic("request already cancelled")
473 if me.isLowOnRequests() {
474 me.updateRequests("Peer.cancel")
478 // Sets a reason to update requests, and if there wasn't already one, handle it.
479 func (cn *Peer) updateRequests(reason string) {
480 if cn.needRequestUpdate != "" {
483 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
486 cn.needRequestUpdate = reason
487 cn.handleUpdateRequests()
490 // Emits the indices in the Bitmaps bms in order, never repeating any index.
491 // skip is mutated during execution, and its initial values will never be
493 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
494 return func(cb iter.Callback) {
495 for _, bm := range bms {
497 func(_i interface{}) bool {
499 if skip.Contains(bitmap.BitIndex(i)) {
502 skip.Add(bitmap.BitIndex(i))
513 func (cn *Peer) peerPiecesChanged() {
514 cn.t.maybeDropMutuallyCompletePeer(cn)
517 // After handshake, we know what Torrent and Client stats to include for a
519 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
525 // All ConnStats that include this connection. Some objects are not known
526 // until the handshake is complete, after which it's expected to reconcile the
528 func (cn *Peer) allStats(f func(*ConnStats)) {
530 if cn.reconciledHandshakeStats {
531 cn.postHandshakeStats(f)
535 func (cn *Peer) readBytes(n int64) {
536 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
539 // Returns whether the connection could be useful to us. We're seeding and
540 // they want data, we don't have metainfo and they can provide it, etc.
541 func (c *Peer) useful() bool {
543 if c.closed.IsSet() {
547 return c.supportsExtension("ut_metadata")
549 if t.seeding() && c.peerInterested {
552 if c.peerHasWantedPieces() {
558 func (c *Peer) lastHelpful() (ret time.Time) {
559 ret = c.lastUsefulChunkReceived
560 if c.t.seeding() && c.lastChunkSent.After(ret) {
561 ret = c.lastChunkSent
566 // Returns whether any part of the chunk would lie outside a piece of the given length.
567 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
571 case cs.Begin+cs.Length > pieceLength:
572 // Check for integer overflow
573 case cs.Begin > pp.IntegerMax-cs.Length:
578 func runSafeExtraneous(f func()) {
586 // Returns true if it was valid to reject the request.
587 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
588 if c.deleteRequest(r) {
590 } else if !c.requestState.Cancelled.CheckedRemove(r) {
593 if c.isLowOnRequests() {
594 c.updateRequests("Peer.remoteRejectedRequest")
596 c.decExpectedChunkReceive(r)
600 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
601 count := c.validReceiveChunks[r]
603 delete(c.validReceiveChunks, r)
604 } else if count > 1 {
605 c.validReceiveChunks[r] = count - 1
611 func (c *Peer) doChunkReadStats(size int64) {
612 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
615 // Handle a received chunk from a peer.
616 func (c *Peer) receiveChunk(msg *pp.Message) error {
617 chunksReceived.Add("total", 1)
619 ppReq := newRequestFromMessage(msg)
621 err := t.checkValidReceiveChunk(ppReq)
623 err = log.WithLevel(log.Warning, err)
626 req := c.t.requestIndexFromRequest(ppReq)
628 if c.bannableAddr.Ok {
629 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
633 chunksReceived.Add("while choked", 1)
636 if c.validReceiveChunks[req] <= 0 {
637 chunksReceived.Add("unexpected", 1)
638 return errors.New("received unexpected chunk")
640 c.decExpectedChunkReceive(req)
642 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
643 chunksReceived.Add("due to allowed fast", 1)
646 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
647 // have actually already received the piece, while we have the Client unlocked to write the data
651 if c.requestState.Requests.Contains(req) {
652 for _, f := range c.callbacks.ReceivedRequested {
653 f(PeerMessageEvent{c, msg})
656 // Request has been satisfied.
657 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
660 c._chunksReceivedWhileExpecting++
662 if c.isLowOnRequests() {
663 c.updateRequests("Peer.receiveChunk deleted request")
666 chunksReceived.Add("unintended", 1)
672 // Do we actually want this chunk?
673 if t.haveChunk(ppReq) {
674 // panic(fmt.Sprintf("%+v", ppReq))
675 chunksReceived.Add("redundant", 1)
676 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
680 piece := &t.pieces[ppReq.Index]
682 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
683 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
685 c.piecesReceivedSinceLastRequestUpdate++
686 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
688 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
689 f(ReceivedUsefulDataEvent{c, msg})
691 c.lastUsefulChunkReceived = time.Now()
693 // Need to record that it hasn't been written yet, before we attempt to do
695 piece.incrementPendingWrites()
696 // Record that we have the chunk, so we aren't trying to download it while
697 // waiting for it to be written to storage.
698 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
700 // Cancel pending requests for this chunk from *other* peers.
701 if p := t.requestingPeer(req); p != nil {
703 panic("should not be pending request from conn that just received it")
711 concurrentChunkWrites.Add(1)
712 defer concurrentChunkWrites.Add(-1)
713 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
714 // number of connections. We write inline with receiving the chunk (with this lock dance),
715 // because we want to handle errors synchronously and I haven't thought of a nice way to
716 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
718 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
721 piece.decrementPendingWrites()
724 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
726 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
727 // request update runs while we're writing the chunk that just failed. Then we never do a
728 // fresh update after pending the failed request.
729 c.updateRequests("Peer.receiveChunk error writing chunk")
730 t.onWriteChunkErr(err)
734 c.onDirtiedPiece(pieceIndex(ppReq.Index))
736 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
737 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
738 t.queuePieceCheck(pieceIndex(ppReq.Index))
739 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
740 // chunk status (such as the haveChunk call above) to have to check all the various other
741 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
742 // that chunk pieces are pended at an appropriate time later however.
746 // We do this because we've written a chunk, and may change PieceState.Partial.
747 t.publishPieceChange(pieceIndex(ppReq.Index))
752 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
753 if c.peerTouchedPieces == nil {
754 c.peerTouchedPieces = make(map[pieceIndex]struct{})
756 c.peerTouchedPieces[piece] = struct{}{}
757 ds := &c.t.pieces[piece].dirtiers
759 *ds = make(map[*Peer]struct{})
761 (*ds)[c] = struct{}{}
764 func (cn *Peer) netGoodPiecesDirtied() int64 {
765 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
768 func (c *Peer) peerHasWantedPieces() bool {
769 if all, _ := c.peerHasAllPieces(); all {
770 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
773 return !c.peerPieces().IsEmpty()
775 return c.peerPieces().Intersects(&c.t._pendingPieces)
778 // Returns true if an outstanding request is removed. Cancelled requests should be handled
780 func (c *Peer) deleteRequest(r RequestIndex) bool {
781 if !c.requestState.Requests.CheckedRemove(r) {
784 for _, f := range c.callbacks.DeletedRequest {
785 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
787 c.updateExpectingChunks()
788 if c.t.requestingPeer(r) != c {
789 panic("only one peer should have a given request at a time")
791 delete(c.t.requestState, r)
792 // c.t.iterPeers(func(p *Peer) {
793 // if p.isLowOnRequests() {
794 // p.updateRequests("Peer.deleteRequest")
800 func (c *Peer) deleteAllRequests(reason string) {
801 if c.requestState.Requests.IsEmpty() {
804 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
805 if !c.deleteRequest(x) {
806 panic("request should exist")
811 c.t.iterPeers(func(p *Peer) {
812 if p.isLowOnRequests() {
813 p.updateRequests(reason)
819 func (c *Peer) assertNoRequests() {
820 if !c.requestState.Requests.IsEmpty() {
821 panic(c.requestState.Requests.GetCardinality())
825 func (c *Peer) cancelAllRequests() {
826 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
834 func (c *Peer) peerPriority() (peerPriority, error) {
835 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
838 func (c *Peer) remoteIp() net.IP {
839 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
840 return net.ParseIP(host)
843 func (c *Peer) remoteIpPort() IpPort {
844 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
845 return IpPort{ipa.IP, uint16(ipa.Port)}
848 func (c *Peer) trust() connectionTrust {
849 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
852 type connectionTrust struct {
854 NetGoodPiecesDirted int64
857 func (l connectionTrust) Less(r connectionTrust) bool {
858 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
861 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
862 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
863 // TODO: Can we use copy on write?
864 ret := cn.peerPieces().Clone()
865 if all, _ := cn.peerHasAllPieces(); all {
867 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
869 ret.AddRange(0, bitmap.ToEnd)
875 func (cn *Peer) stats() *ConnStats {
879 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
880 pc, ok := p.peerImpl.(*PeerConn)
884 func (p *Peer) uncancelledRequests() uint64 {
885 return p.requestState.Requests.GetCardinality()
888 type peerLocalPublicAddr = IpPort
890 func (p *Peer) isLowOnRequests() bool {
891 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
894 func (p *Peer) decPeakRequests() {
895 // // This can occur when peak requests are altered by the update request timer to be lower than
896 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
897 // // wonder what happens if maxRequests is not signed.
898 // if p.peakRequests < 1 {
899 // panic(p.peakRequests)