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 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
338 // they do (known=true).
339 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
340 if all, known := cn.peerHasAllPieces(); all && known {
343 return cn.peerPieces().ContainsInt(piece)
346 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
347 // https://github.com/pion/datachannel/issues/59 is fixed.
349 writeBufferHighWaterLen = 1 << 15
350 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
354 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
355 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
356 // This is the maximum request count that could fit in the write buffer if it's at or below the
357 // low water mark when we run maybeUpdateActualRequestState.
358 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
361 // The actual value to use as the maximum outbound requests.
362 func (cn *Peer) nominalMaxRequests() maxRequests {
363 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
366 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
367 ret = cn.cumulativeExpectedToReceiveChunks
368 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
369 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
374 func (cn *Peer) setInterested(interested bool) bool {
375 if cn.requestState.Interested == interested {
378 cn.requestState.Interested = interested
380 cn.lastBecameInterested = time.Now()
381 } else if !cn.lastBecameInterested.IsZero() {
382 cn.priorInterest += time.Since(cn.lastBecameInterested)
384 cn.updateExpectingChunks()
385 // log.Printf("%p: setting interest: %v", cn, interested)
386 return cn.writeInterested(interested)
389 // The function takes a message to be sent, and returns true if more messages
391 type messageWriter func(pp.Message) bool
393 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
394 // when we want to go fast.
395 func (cn *Peer) shouldRequest(r RequestIndex) error {
396 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
400 pi := cn.t.pieceIndexOfRequestIndex(r)
401 if cn.requestState.Cancelled.Contains(r) {
402 return errors.New("request is cancelled and waiting acknowledgement")
404 if !cn.peerHasPiece(pi) {
405 return errors.New("requesting piece peer doesn't have")
407 if !cn.t.peerIsActive(cn) {
408 panic("requesting but not in active conns")
410 if cn.closed.IsSet() {
411 panic("requesting when connection is closed")
413 if cn.t.hashingPiece(pi) {
414 panic("piece is being hashed")
416 if cn.t.pieceQueuedForHash(pi) {
417 panic("piece is queued for hash")
419 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
420 // This could occur if we made a request with the fast extension, and then got choked and
421 // haven't had the request rejected yet.
422 if !cn.requestState.Requests.Contains(r) {
423 panic("peer choking and piece not allowed fast")
429 func (cn *Peer) mustRequest(r RequestIndex) bool {
430 more, err := cn.request(r)
437 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
438 if err := cn.shouldRequest(r); err != nil {
441 if cn.requestState.Requests.Contains(r) {
444 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
445 return true, errors.New("too many outstanding requests")
447 cn.requestState.Requests.Add(r)
448 if cn.validReceiveChunks == nil {
449 cn.validReceiveChunks = make(map[RequestIndex]int)
451 cn.validReceiveChunks[r]++
452 cn.t.requestState[r] = requestState{
456 cn.updateExpectingChunks()
457 ppReq := cn.t.requestIndexToRequest(r)
458 for _, f := range cn.callbacks.SentRequest {
459 f(PeerRequestEvent{cn, ppReq})
461 return cn.peerImpl._request(ppReq), nil
464 func (me *Peer) cancel(r RequestIndex) {
465 if !me.deleteRequest(r) {
466 panic("request not existing should have been guarded")
469 // Record that we expect to get a cancel ack.
470 if !me.requestState.Cancelled.CheckedAdd(r) {
471 panic("request already cancelled")
475 if me.isLowOnRequests() {
476 me.updateRequests("Peer.cancel")
480 // Sets a reason to update requests, and if there wasn't already one, handle it.
481 func (cn *Peer) updateRequests(reason string) {
482 if cn.needRequestUpdate != "" {
485 cn.needRequestUpdate = reason
486 cn.handleUpdateRequests()
489 // Emits the indices in the Bitmaps bms in order, never repeating any index.
490 // skip is mutated during execution, and its initial values will never be
492 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
493 return func(cb iter.Callback) {
494 for _, bm := range bms {
496 func(_i interface{}) bool {
498 if skip.Contains(bitmap.BitIndex(i)) {
501 skip.Add(bitmap.BitIndex(i))
512 // After handshake, we know what Torrent and Client stats to include for a
514 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
520 // All ConnStats that include this connection. Some objects are not known
521 // until the handshake is complete, after which it's expected to reconcile the
523 func (cn *Peer) allStats(f func(*ConnStats)) {
525 if cn.reconciledHandshakeStats {
526 cn.postHandshakeStats(f)
530 func (cn *Peer) readBytes(n int64) {
531 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
534 func (c *Peer) lastHelpful() (ret time.Time) {
535 ret = c.lastUsefulChunkReceived
536 if c.t.seeding() && c.lastChunkSent.After(ret) {
537 ret = c.lastChunkSent
542 // Returns whether any part of the chunk would lie outside a piece of the given length.
543 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
547 case cs.Begin+cs.Length > pieceLength:
548 // Check for integer overflow
549 case cs.Begin > pp.IntegerMax-cs.Length:
554 func runSafeExtraneous(f func()) {
562 // Returns true if it was valid to reject the request.
563 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
564 if c.deleteRequest(r) {
566 } else if !c.requestState.Cancelled.CheckedRemove(r) {
569 if c.isLowOnRequests() {
570 c.updateRequests("Peer.remoteRejectedRequest")
572 c.decExpectedChunkReceive(r)
576 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
577 count := c.validReceiveChunks[r]
579 delete(c.validReceiveChunks, r)
580 } else if count > 1 {
581 c.validReceiveChunks[r] = count - 1
587 func (c *Peer) doChunkReadStats(size int64) {
588 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
591 // Handle a received chunk from a peer.
592 func (c *Peer) receiveChunk(msg *pp.Message) error {
593 chunksReceived.Add("total", 1)
595 ppReq := newRequestFromMessage(msg)
597 err := t.checkValidReceiveChunk(ppReq)
599 err = log.WithLevel(log.Warning, err)
602 req := c.t.requestIndexFromRequest(ppReq)
604 recordBlockForSmartBan := sync.OnceFunc(func() {
605 c.recordBlockForSmartBan(req, msg.Piece)
607 // This needs to occur before we return, but we try to do it when the client is unlocked. It
608 // can't be done before checking if chunks are valid because they won't be deallocated by piece
609 // hashing if they're out of bounds.
610 defer recordBlockForSmartBan()
613 chunksReceived.Add("while choked", 1)
616 if c.validReceiveChunks[req] <= 0 {
617 chunksReceived.Add("unexpected", 1)
618 return errors.New("received unexpected chunk")
620 c.decExpectedChunkReceive(req)
622 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
623 chunksReceived.Add("due to allowed fast", 1)
626 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
627 // have actually already received the piece, while we have the Client unlocked to write the data
631 if c.requestState.Requests.Contains(req) {
632 for _, f := range c.callbacks.ReceivedRequested {
633 f(PeerMessageEvent{c, msg})
636 // Request has been satisfied.
637 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
640 c._chunksReceivedWhileExpecting++
642 if c.isLowOnRequests() {
643 c.updateRequests("Peer.receiveChunk deleted request")
646 chunksReceived.Add("unintended", 1)
652 // Do we actually want this chunk?
653 if t.haveChunk(ppReq) {
654 // panic(fmt.Sprintf("%+v", ppReq))
655 chunksReceived.Add("redundant", 1)
656 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
660 piece := &t.pieces[ppReq.Index]
662 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
663 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
665 c.piecesReceivedSinceLastRequestUpdate++
666 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
668 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
669 f(ReceivedUsefulDataEvent{c, msg})
671 c.lastUsefulChunkReceived = time.Now()
673 // Need to record that it hasn't been written yet, before we attempt to do
675 piece.incrementPendingWrites()
676 // Record that we have the chunk, so we aren't trying to download it while
677 // waiting for it to be written to storage.
678 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
680 // Cancel pending requests for this chunk from *other* peers.
681 if p := t.requestingPeer(req); p != nil {
683 panic("should not be pending request from conn that just received it")
691 // Opportunistically do this here while we aren't holding the client lock.
692 recordBlockForSmartBan()
693 concurrentChunkWrites.Add(1)
694 defer concurrentChunkWrites.Add(-1)
695 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
696 // number of connections. We write inline with receiving the chunk (with this lock dance),
697 // because we want to handle errors synchronously and I haven't thought of a nice way to
698 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
700 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
703 piece.decrementPendingWrites()
706 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
708 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
709 // request update runs while we're writing the chunk that just failed. Then we never do a
710 // fresh update after pending the failed request.
711 c.updateRequests("Peer.receiveChunk error writing chunk")
712 t.onWriteChunkErr(err)
716 c.onDirtiedPiece(pieceIndex(ppReq.Index))
718 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
719 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
720 t.queuePieceCheck(pieceIndex(ppReq.Index))
721 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
722 // chunk status (such as the haveChunk call above) to have to check all the various other
723 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
724 // that chunk pieces are pended at an appropriate time later however.
728 // We do this because we've written a chunk, and may change PieceState.Partial.
729 t.publishPieceStateChange(pieceIndex(ppReq.Index))
734 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
735 if c.peerTouchedPieces == nil {
736 c.peerTouchedPieces = make(map[pieceIndex]struct{})
738 c.peerTouchedPieces[piece] = struct{}{}
739 ds := &c.t.pieces[piece].dirtiers
741 *ds = make(map[*Peer]struct{})
743 (*ds)[c] = struct{}{}
746 func (cn *Peer) netGoodPiecesDirtied() int64 {
747 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
750 func (c *Peer) peerHasWantedPieces() bool {
751 if all, _ := c.peerHasAllPieces(); all {
752 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
755 return !c.peerPieces().IsEmpty()
757 return c.peerPieces().Intersects(&c.t._pendingPieces)
760 // Returns true if an outstanding request is removed. Cancelled requests should be handled
762 func (c *Peer) deleteRequest(r RequestIndex) bool {
763 if !c.requestState.Requests.CheckedRemove(r) {
766 for _, f := range c.callbacks.DeletedRequest {
767 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
769 c.updateExpectingChunks()
770 if c.t.requestingPeer(r) != c {
771 panic("only one peer should have a given request at a time")
773 delete(c.t.requestState, r)
774 // c.t.iterPeers(func(p *Peer) {
775 // if p.isLowOnRequests() {
776 // p.updateRequests("Peer.deleteRequest")
782 func (c *Peer) deleteAllRequests(reason string) {
783 if c.requestState.Requests.IsEmpty() {
786 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
787 if !c.deleteRequest(x) {
788 panic("request should exist")
793 c.t.iterPeers(func(p *Peer) {
794 if p.isLowOnRequests() {
795 p.updateRequests(reason)
801 func (c *Peer) assertNoRequests() {
802 if !c.requestState.Requests.IsEmpty() {
803 panic(c.requestState.Requests.GetCardinality())
807 func (c *Peer) cancelAllRequests() {
808 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
816 func (c *Peer) peerPriority() (peerPriority, error) {
817 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
820 func (c *Peer) remoteIp() net.IP {
821 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
822 return net.ParseIP(host)
825 func (c *Peer) remoteIpPort() IpPort {
826 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
827 return IpPort{ipa.IP, uint16(ipa.Port)}
830 func (c *Peer) trust() connectionTrust {
831 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
834 type connectionTrust struct {
836 NetGoodPiecesDirted int64
839 func (l connectionTrust) Less(r connectionTrust) bool {
840 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
843 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
844 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
845 // TODO: Can we use copy on write?
846 ret := cn.peerPieces().Clone()
847 if all, _ := cn.peerHasAllPieces(); all {
849 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
851 ret.AddRange(0, bitmap.ToEnd)
857 func (cn *Peer) stats() *ConnStats {
861 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
862 pc, ok := p.peerImpl.(*PeerConn)
866 func (p *Peer) uncancelledRequests() uint64 {
867 return p.requestState.Requests.GetCardinality()
870 type peerLocalPublicAddr = IpPort
872 func (p *Peer) isLowOnRequests() bool {
873 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
876 func (p *Peer) decPeakRequests() {
877 // // This can occur when peak requests are altered by the update request timer to be lower than
878 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
879 // // wonder what happens if maxRequests is not signed.
880 // if p.peakRequests < 1 {
881 // panic(p.peakRequests)
886 func (p *Peer) recordBlockForSmartBan(req RequestIndex, blockData []byte) {
887 if p.bannableAddr.Ok {
888 p.t.smartBanCache.RecordBlock(p.bannableAddr.Value, req, blockData)