11 "github.com/RoaringBitmap/roaring"
12 "github.com/anacrolix/chansync"
13 . "github.com/anacrolix/generics"
14 "github.com/anacrolix/log"
15 "github.com/anacrolix/missinggo/iter"
16 "github.com/anacrolix/missinggo/v2/bitmap"
17 "github.com/anacrolix/multiless"
19 "github.com/anacrolix/torrent/internal/alloclim"
20 "github.com/anacrolix/torrent/mse"
21 pp "github.com/anacrolix/torrent/peer_protocol"
22 request_strategy "github.com/anacrolix/torrent/request-strategy"
23 typedRoaring "github.com/anacrolix/torrent/typed-roaring"
28 // First to ensure 64-bit alignment for atomics. See #262.
38 RemoteAddr PeerRemoteAddr
39 // The local address as observed by the remote peer. WebRTC seems to get this right without needing hints from the
41 localPublicAddr peerLocalPublicAddr
42 bannableAddr Option[bannableAddr]
43 // True if the connection is operating over MSE obfuscation.
45 cryptoMethod mse.CryptoMethod
48 closed chansync.SetOnce
49 // Set true after we've added our ConnStats generated during handshake to
50 // other ConnStat instances as determined when the *Torrent became known.
51 reconciledHandshakeStats bool
53 lastMessageReceived time.Time
54 completedHandshake time.Time
55 lastUsefulChunkReceived time.Time
56 lastChunkSent time.Time
58 // Stuff controlled by the local peer.
59 needRequestUpdate string
60 requestState request_strategy.PeerRequestState
61 updateRequestsTimer *time.Timer
62 lastRequestUpdate time.Time
63 peakRequests maxRequests
64 lastBecameInterested time.Time
65 priorInterest time.Duration
67 lastStartedExpectingToReceiveChunks time.Time
68 cumulativeExpectedToReceiveChunks time.Duration
69 _chunksReceivedWhileExpecting int64
72 piecesReceivedSinceLastRequestUpdate maxRequests
73 maxPiecesReceivedBetweenRequestUpdates maxRequests
74 // Chunks that we might reasonably expect to receive from the peer. Due to latency, buffering,
75 // and implementation differences, we may receive chunks that are no longer in the set of
76 // requests actually want. This could use a roaring.BSI if the memory use becomes noticeable.
77 validReceiveChunks map[RequestIndex]int
78 // Indexed by metadata piece, set to true if posted and pending a
80 metadataRequests []bool
81 sentHaves bitmap.Bitmap
83 // Stuff controlled by the remote peer.
86 peerRequests map[Request]*peerRequestState
87 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
88 // The highest possible number of pieces the torrent could have based on
89 // communication with the peer. Generally only useful until we have the
91 peerMinPieces pieceIndex
92 // Pieces we've accepted chunks for from the peer.
93 peerTouchedPieces map[pieceIndex]struct{}
94 peerAllowedFast typedRoaring.Bitmap[pieceIndex]
96 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
103 peerRequestState struct {
105 allocReservation *alloclim.Reservation
108 PeerRemoteAddr interface {
112 peerRequests = orderedBitmap[RequestIndex]
116 PeerSourceUtHolepunch = "C"
117 PeerSourceTracker = "Tr"
118 PeerSourceIncoming = "I"
119 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
120 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
122 // The peer was given directly, such as through a magnet link.
123 PeerSourceDirect = "M"
126 // Returns the Torrent a Peer belongs to. Shouldn't change for the lifetime of the Peer. May be nil
127 // if we are the receiving end of a connection and the handshake hasn't been received or accepted
129 func (p *Peer) Torrent() *Torrent {
133 func (p *Peer) initRequestState() {
134 p.requestState.Requests = &peerRequests{}
137 func (cn *Peer) updateExpectingChunks() {
138 if cn.expectingChunks() {
139 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
140 cn.lastStartedExpectingToReceiveChunks = time.Now()
143 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
144 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
145 cn.lastStartedExpectingToReceiveChunks = time.Time{}
150 func (cn *Peer) expectingChunks() bool {
151 if cn.requestState.Requests.IsEmpty() {
154 if !cn.requestState.Interested {
160 haveAllowedFastRequests := false
161 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
162 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
163 cn.requestState.Requests,
164 cn.t.pieceRequestIndexOffset(i),
165 cn.t.pieceRequestIndexOffset(i+1),
167 return !haveAllowedFastRequests
169 return haveAllowedFastRequests
172 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
173 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
176 func (cn *Peer) cumInterest() time.Duration {
177 ret := cn.priorInterest
178 if cn.requestState.Interested {
179 ret += time.Since(cn.lastBecameInterested)
184 func (cn *Peer) locker() *lockWithDeferreds {
185 return cn.t.cl.locker()
188 func (cn *PeerConn) supportsExtension(ext pp.ExtensionName) bool {
189 _, ok := cn.PeerExtensionIDs[ext]
193 // The best guess at number of pieces in the torrent for this peer.
194 func (cn *Peer) bestPeerNumPieces() pieceIndex {
196 return cn.t.numPieces()
198 return cn.peerMinPieces
201 func (cn *Peer) completedString() string {
202 have := pieceIndex(cn.peerPieces().GetCardinality())
203 if all, _ := cn.peerHasAllPieces(); all {
204 have = cn.bestPeerNumPieces()
206 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
209 func eventAgeString(t time.Time) string {
213 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
216 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
217 func (cn *Peer) statusFlags() (ret string) {
219 ret += string([]byte{b})
221 if cn.requestState.Interested {
228 ret += cn.connectionFlags()
230 if cn.peerInterested {
239 func (cn *Peer) downloadRate() float64 {
240 num := cn._stats.BytesReadUsefulData.Int64()
244 return float64(num) / cn.totalExpectingTime().Seconds()
247 func (cn *Peer) DownloadRate() float64 {
249 defer cn.locker().RUnlock()
251 return cn.downloadRate()
254 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
255 var last Option[pieceIndex]
257 next := func(item Option[pieceIndex]) {
268 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
269 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
272 next(None[pieceIndex]())
275 func (cn *Peer) writeStatus(w io.Writer) {
276 // \t isn't preserved in <pre> blocks?
277 if cn.closed.IsSet() {
278 fmt.Fprint(w, "CLOSED: ")
280 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
281 prio, err := cn.peerPriority()
282 prioStr := fmt.Sprintf("%08x", prio)
284 prioStr += ": " + err.Error()
286 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
287 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
288 eventAgeString(cn.lastMessageReceived),
289 eventAgeString(cn.completedHandshake),
290 eventAgeString(cn.lastHelpful()),
292 cn.totalExpectingTime(),
295 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
296 cn.completedString(),
297 len(cn.peerTouchedPieces),
298 &cn._stats.ChunksReadUseful,
299 &cn._stats.ChunksRead,
300 &cn._stats.ChunksWritten,
301 cn.requestState.Requests.GetCardinality(),
302 cn.requestState.Cancelled.GetCardinality(),
303 cn.nominalMaxRequests(),
305 len(cn.peerRequests),
308 cn.downloadRate()/(1<<10),
310 fmt.Fprintf(w, "requested pieces:")
311 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
312 fmt.Fprintf(w, " %v(%v)", piece, count)
317 func (p *Peer) close() {
321 if p.updateRequestsTimer != nil {
322 p.updateRequestsTimer.Stop()
324 for _, prs := range p.peerRequests {
325 prs.allocReservation.Drop()
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 // After handshake, we know what Torrent and Client stats to include for a
515 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
521 // All ConnStats that include this connection. Some objects are not known
522 // until the handshake is complete, after which it's expected to reconcile the
524 func (cn *Peer) allStats(f func(*ConnStats)) {
526 if cn.reconciledHandshakeStats {
527 cn.postHandshakeStats(f)
531 func (cn *Peer) readBytes(n int64) {
532 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
535 func (c *Peer) lastHelpful() (ret time.Time) {
536 ret = c.lastUsefulChunkReceived
537 if c.t.seeding() && c.lastChunkSent.After(ret) {
538 ret = c.lastChunkSent
543 // Returns whether any part of the chunk would lie outside a piece of the given length.
544 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
548 case cs.Begin+cs.Length > pieceLength:
549 // Check for integer overflow
550 case cs.Begin > pp.IntegerMax-cs.Length:
555 func runSafeExtraneous(f func()) {
563 // Returns true if it was valid to reject the request.
564 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
565 if c.deleteRequest(r) {
567 } else if !c.requestState.Cancelled.CheckedRemove(r) {
570 if c.isLowOnRequests() {
571 c.updateRequests("Peer.remoteRejectedRequest")
573 c.decExpectedChunkReceive(r)
577 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
578 count := c.validReceiveChunks[r]
580 delete(c.validReceiveChunks, r)
581 } else if count > 1 {
582 c.validReceiveChunks[r] = count - 1
588 func (c *Peer) doChunkReadStats(size int64) {
589 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
592 // Handle a received chunk from a peer.
593 func (c *Peer) receiveChunk(msg *pp.Message) error {
594 chunksReceived.Add("total", 1)
596 ppReq := newRequestFromMessage(msg)
598 err := t.checkValidReceiveChunk(ppReq)
600 err = log.WithLevel(log.Warning, err)
603 req := c.t.requestIndexFromRequest(ppReq)
605 if c.bannableAddr.Ok {
606 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
610 chunksReceived.Add("while choked", 1)
613 if c.validReceiveChunks[req] <= 0 {
614 chunksReceived.Add("unexpected", 1)
615 return errors.New("received unexpected chunk")
617 c.decExpectedChunkReceive(req)
619 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
620 chunksReceived.Add("due to allowed fast", 1)
623 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
624 // have actually already received the piece, while we have the Client unlocked to write the data
628 if c.requestState.Requests.Contains(req) {
629 for _, f := range c.callbacks.ReceivedRequested {
630 f(PeerMessageEvent{c, msg})
633 // Request has been satisfied.
634 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
637 c._chunksReceivedWhileExpecting++
639 if c.isLowOnRequests() {
640 c.updateRequests("Peer.receiveChunk deleted request")
643 chunksReceived.Add("unintended", 1)
649 // Do we actually want this chunk?
650 if t.haveChunk(ppReq) {
651 // panic(fmt.Sprintf("%+v", ppReq))
652 chunksReceived.Add("redundant", 1)
653 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
657 piece := &t.pieces[ppReq.Index]
659 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
660 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
662 c.piecesReceivedSinceLastRequestUpdate++
663 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
665 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
666 f(ReceivedUsefulDataEvent{c, msg})
668 c.lastUsefulChunkReceived = time.Now()
670 // Need to record that it hasn't been written yet, before we attempt to do
672 piece.incrementPendingWrites()
673 // Record that we have the chunk, so we aren't trying to download it while
674 // waiting for it to be written to storage.
675 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
677 // Cancel pending requests for this chunk from *other* peers.
678 if p := t.requestingPeer(req); p != nil {
680 panic("should not be pending request from conn that just received it")
688 concurrentChunkWrites.Add(1)
689 defer concurrentChunkWrites.Add(-1)
690 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
691 // number of connections. We write inline with receiving the chunk (with this lock dance),
692 // because we want to handle errors synchronously and I haven't thought of a nice way to
693 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
695 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
698 piece.decrementPendingWrites()
701 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
703 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
704 // request update runs while we're writing the chunk that just failed. Then we never do a
705 // fresh update after pending the failed request.
706 c.updateRequests("Peer.receiveChunk error writing chunk")
707 t.onWriteChunkErr(err)
711 c.onDirtiedPiece(pieceIndex(ppReq.Index))
713 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
714 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
715 t.queuePieceCheck(pieceIndex(ppReq.Index))
716 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
717 // chunk status (such as the haveChunk call above) to have to check all the various other
718 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
719 // that chunk pieces are pended at an appropriate time later however.
723 // We do this because we've written a chunk, and may change PieceState.Partial.
724 t.publishPieceChange(pieceIndex(ppReq.Index))
729 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
730 if c.peerTouchedPieces == nil {
731 c.peerTouchedPieces = make(map[pieceIndex]struct{})
733 c.peerTouchedPieces[piece] = struct{}{}
734 ds := &c.t.pieces[piece].dirtiers
736 *ds = make(map[*Peer]struct{})
738 (*ds)[c] = struct{}{}
741 func (cn *Peer) netGoodPiecesDirtied() int64 {
742 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
745 func (c *Peer) peerHasWantedPieces() bool {
746 if all, _ := c.peerHasAllPieces(); all {
747 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
750 return !c.peerPieces().IsEmpty()
752 return c.peerPieces().Intersects(&c.t._pendingPieces)
755 // Returns true if an outstanding request is removed. Cancelled requests should be handled
757 func (c *Peer) deleteRequest(r RequestIndex) bool {
758 if !c.requestState.Requests.CheckedRemove(r) {
761 for _, f := range c.callbacks.DeletedRequest {
762 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
764 c.updateExpectingChunks()
765 if c.t.requestingPeer(r) != c {
766 panic("only one peer should have a given request at a time")
768 delete(c.t.requestState, r)
769 // c.t.iterPeers(func(p *Peer) {
770 // if p.isLowOnRequests() {
771 // p.updateRequests("Peer.deleteRequest")
777 func (c *Peer) deleteAllRequests(reason string) {
778 if c.requestState.Requests.IsEmpty() {
781 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
782 if !c.deleteRequest(x) {
783 panic("request should exist")
788 c.t.iterPeers(func(p *Peer) {
789 if p.isLowOnRequests() {
790 p.updateRequests(reason)
796 func (c *Peer) assertNoRequests() {
797 if !c.requestState.Requests.IsEmpty() {
798 panic(c.requestState.Requests.GetCardinality())
802 func (c *Peer) cancelAllRequests() {
803 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
811 func (c *Peer) peerPriority() (peerPriority, error) {
812 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
815 func (c *Peer) remoteIp() net.IP {
816 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
817 return net.ParseIP(host)
820 func (c *Peer) remoteIpPort() IpPort {
821 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
822 return IpPort{ipa.IP, uint16(ipa.Port)}
825 func (c *Peer) trust() connectionTrust {
826 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
829 type connectionTrust struct {
831 NetGoodPiecesDirted int64
834 func (l connectionTrust) Less(r connectionTrust) bool {
835 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
838 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
839 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
840 // TODO: Can we use copy on write?
841 ret := cn.peerPieces().Clone()
842 if all, _ := cn.peerHasAllPieces(); all {
844 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
846 ret.AddRange(0, bitmap.ToEnd)
852 func (cn *Peer) stats() *ConnStats {
856 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
857 pc, ok := p.peerImpl.(*PeerConn)
861 func (p *Peer) uncancelledRequests() uint64 {
862 return p.requestState.Requests.GetCardinality()
865 type peerLocalPublicAddr = IpPort
867 func (p *Peer) isLowOnRequests() bool {
868 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
871 func (p *Peer) decPeakRequests() {
872 // // This can occur when peak requests are altered by the update request timer to be lower than
873 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
874 // // wonder what happens if maxRequests is not signed.
875 // if p.peakRequests < 1 {
876 // panic(p.peakRequests)