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.
98 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
99 PeerClientName atomic.Value
106 peerRequestState struct {
108 allocReservation *alloclim.Reservation
111 PeerRemoteAddr interface {
115 peerRequests = orderedBitmap[RequestIndex]
119 PeerSourceUtHolepunch = "C"
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()
327 for _, prs := range p.peerRequests {
328 prs.allocReservation.Drop()
332 p.t.decPeerPieceAvailability(p)
334 for _, f := range p.callbacks.PeerClosed {
339 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
340 // they do (known=true).
341 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
342 if all, known := cn.peerHasAllPieces(); all && known {
345 return cn.peerPieces().ContainsInt(piece)
348 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
349 // https://github.com/pion/datachannel/issues/59 is fixed.
351 writeBufferHighWaterLen = 1 << 15
352 writeBufferLowWaterLen = writeBufferHighWaterLen / 2
356 interestedMsgLen = len(pp.Message{Type: pp.Interested}.MustMarshalBinary())
357 requestMsgLen = len(pp.Message{Type: pp.Request}.MustMarshalBinary())
358 // This is the maximum request count that could fit in the write buffer if it's at or below the
359 // low water mark when we run maybeUpdateActualRequestState.
360 maxLocalToRemoteRequests = (writeBufferHighWaterLen - writeBufferLowWaterLen - interestedMsgLen) / requestMsgLen
363 // The actual value to use as the maximum outbound requests.
364 func (cn *Peer) nominalMaxRequests() maxRequests {
365 return maxInt(1, minInt(cn.PeerMaxRequests, cn.peakRequests*2, maxLocalToRemoteRequests))
368 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
369 ret = cn.cumulativeExpectedToReceiveChunks
370 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
371 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
376 func (cn *Peer) setInterested(interested bool) bool {
377 if cn.requestState.Interested == interested {
380 cn.requestState.Interested = interested
382 cn.lastBecameInterested = time.Now()
383 } else if !cn.lastBecameInterested.IsZero() {
384 cn.priorInterest += time.Since(cn.lastBecameInterested)
386 cn.updateExpectingChunks()
387 // log.Printf("%p: setting interest: %v", cn, interested)
388 return cn.writeInterested(interested)
391 // The function takes a message to be sent, and returns true if more messages
393 type messageWriter func(pp.Message) bool
395 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
396 // when we want to go fast.
397 func (cn *Peer) shouldRequest(r RequestIndex) error {
398 err := cn.t.checkValidReceiveChunk(cn.t.requestIndexToRequest(r))
402 pi := cn.t.pieceIndexOfRequestIndex(r)
403 if cn.requestState.Cancelled.Contains(r) {
404 return errors.New("request is cancelled and waiting acknowledgement")
406 if !cn.peerHasPiece(pi) {
407 return errors.New("requesting piece peer doesn't have")
409 if !cn.t.peerIsActive(cn) {
410 panic("requesting but not in active conns")
412 if cn.closed.IsSet() {
413 panic("requesting when connection is closed")
415 if cn.t.hashingPiece(pi) {
416 panic("piece is being hashed")
418 if cn.t.pieceQueuedForHash(pi) {
419 panic("piece is queued for hash")
421 if cn.peerChoking && !cn.peerAllowedFast.Contains(pi) {
422 // This could occur if we made a request with the fast extension, and then got choked and
423 // haven't had the request rejected yet.
424 if !cn.requestState.Requests.Contains(r) {
425 panic("peer choking and piece not allowed fast")
431 func (cn *Peer) mustRequest(r RequestIndex) bool {
432 more, err := cn.request(r)
439 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
440 if err := cn.shouldRequest(r); err != nil {
443 if cn.requestState.Requests.Contains(r) {
446 if maxRequests(cn.requestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
447 return true, errors.New("too many outstanding requests")
449 cn.requestState.Requests.Add(r)
450 if cn.validReceiveChunks == nil {
451 cn.validReceiveChunks = make(map[RequestIndex]int)
453 cn.validReceiveChunks[r]++
454 cn.t.requestState[r] = requestState{
458 cn.updateExpectingChunks()
459 ppReq := cn.t.requestIndexToRequest(r)
460 for _, f := range cn.callbacks.SentRequest {
461 f(PeerRequestEvent{cn, ppReq})
463 return cn.peerImpl._request(ppReq), nil
466 func (me *Peer) cancel(r RequestIndex) {
467 if !me.deleteRequest(r) {
468 panic("request not existing should have been guarded")
471 if !me.requestState.Cancelled.CheckedAdd(r) {
472 panic("request already cancelled")
476 if me.isLowOnRequests() {
477 me.updateRequests("Peer.cancel")
481 // Sets a reason to update requests, and if there wasn't already one, handle it.
482 func (cn *Peer) updateRequests(reason string) {
483 if cn.needRequestUpdate != "" {
486 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
489 cn.needRequestUpdate = reason
490 cn.handleUpdateRequests()
493 // Emits the indices in the Bitmaps bms in order, never repeating any index.
494 // skip is mutated during execution, and its initial values will never be
496 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
497 return func(cb iter.Callback) {
498 for _, bm := range bms {
500 func(_i interface{}) bool {
502 if skip.Contains(bitmap.BitIndex(i)) {
505 skip.Add(bitmap.BitIndex(i))
516 func (cn *Peer) peerPiecesChanged() {
517 cn.t.maybeDropMutuallyCompletePeer(cn)
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 // Returns whether the connection could be useful to us. We're seeding and
543 // they want data, we don't have metainfo and they can provide it, etc.
544 func (c *Peer) useful() bool {
546 if c.closed.IsSet() {
550 return c.supportsExtension("ut_metadata")
552 if t.seeding() && c.peerInterested {
555 if c.peerHasWantedPieces() {
561 func (c *Peer) lastHelpful() (ret time.Time) {
562 ret = c.lastUsefulChunkReceived
563 if c.t.seeding() && c.lastChunkSent.After(ret) {
564 ret = c.lastChunkSent
569 // Returns whether any part of the chunk would lie outside a piece of the given length.
570 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
574 case cs.Begin+cs.Length > pieceLength:
575 // Check for integer overflow
576 case cs.Begin > pp.IntegerMax-cs.Length:
581 func runSafeExtraneous(f func()) {
589 // Returns true if it was valid to reject the request.
590 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
591 if c.deleteRequest(r) {
593 } else if !c.requestState.Cancelled.CheckedRemove(r) {
596 if c.isLowOnRequests() {
597 c.updateRequests("Peer.remoteRejectedRequest")
599 c.decExpectedChunkReceive(r)
603 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
604 count := c.validReceiveChunks[r]
606 delete(c.validReceiveChunks, r)
607 } else if count > 1 {
608 c.validReceiveChunks[r] = count - 1
614 func (c *Peer) doChunkReadStats(size int64) {
615 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
618 // Handle a received chunk from a peer.
619 func (c *Peer) receiveChunk(msg *pp.Message) error {
620 chunksReceived.Add("total", 1)
622 ppReq := newRequestFromMessage(msg)
624 err := t.checkValidReceiveChunk(ppReq)
626 err = log.WithLevel(log.Warning, err)
629 req := c.t.requestIndexFromRequest(ppReq)
631 if c.bannableAddr.Ok {
632 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
636 chunksReceived.Add("while choked", 1)
639 if c.validReceiveChunks[req] <= 0 {
640 chunksReceived.Add("unexpected", 1)
641 return errors.New("received unexpected chunk")
643 c.decExpectedChunkReceive(req)
645 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
646 chunksReceived.Add("due to allowed fast", 1)
649 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
650 // have actually already received the piece, while we have the Client unlocked to write the data
654 if c.requestState.Requests.Contains(req) {
655 for _, f := range c.callbacks.ReceivedRequested {
656 f(PeerMessageEvent{c, msg})
659 // Request has been satisfied.
660 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
663 c._chunksReceivedWhileExpecting++
665 if c.isLowOnRequests() {
666 c.updateRequests("Peer.receiveChunk deleted request")
669 chunksReceived.Add("unintended", 1)
675 // Do we actually want this chunk?
676 if t.haveChunk(ppReq) {
677 // panic(fmt.Sprintf("%+v", ppReq))
678 chunksReceived.Add("redundant", 1)
679 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
683 piece := &t.pieces[ppReq.Index]
685 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
686 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
688 c.piecesReceivedSinceLastRequestUpdate++
689 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
691 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
692 f(ReceivedUsefulDataEvent{c, msg})
694 c.lastUsefulChunkReceived = time.Now()
696 // Need to record that it hasn't been written yet, before we attempt to do
698 piece.incrementPendingWrites()
699 // Record that we have the chunk, so we aren't trying to download it while
700 // waiting for it to be written to storage.
701 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
703 // Cancel pending requests for this chunk from *other* peers.
704 if p := t.requestingPeer(req); p != nil {
706 panic("should not be pending request from conn that just received it")
714 concurrentChunkWrites.Add(1)
715 defer concurrentChunkWrites.Add(-1)
716 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
717 // number of connections. We write inline with receiving the chunk (with this lock dance),
718 // because we want to handle errors synchronously and I haven't thought of a nice way to
719 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
721 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
724 piece.decrementPendingWrites()
727 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
729 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
730 // request update runs while we're writing the chunk that just failed. Then we never do a
731 // fresh update after pending the failed request.
732 c.updateRequests("Peer.receiveChunk error writing chunk")
733 t.onWriteChunkErr(err)
737 c.onDirtiedPiece(pieceIndex(ppReq.Index))
739 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
740 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
741 t.queuePieceCheck(pieceIndex(ppReq.Index))
742 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
743 // chunk status (such as the haveChunk call above) to have to check all the various other
744 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
745 // that chunk pieces are pended at an appropriate time later however.
749 // We do this because we've written a chunk, and may change PieceState.Partial.
750 t.publishPieceChange(pieceIndex(ppReq.Index))
755 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
756 if c.peerTouchedPieces == nil {
757 c.peerTouchedPieces = make(map[pieceIndex]struct{})
759 c.peerTouchedPieces[piece] = struct{}{}
760 ds := &c.t.pieces[piece].dirtiers
762 *ds = make(map[*Peer]struct{})
764 (*ds)[c] = struct{}{}
767 func (cn *Peer) netGoodPiecesDirtied() int64 {
768 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
771 func (c *Peer) peerHasWantedPieces() bool {
772 if all, _ := c.peerHasAllPieces(); all {
773 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
776 return !c.peerPieces().IsEmpty()
778 return c.peerPieces().Intersects(&c.t._pendingPieces)
781 // Returns true if an outstanding request is removed. Cancelled requests should be handled
783 func (c *Peer) deleteRequest(r RequestIndex) bool {
784 if !c.requestState.Requests.CheckedRemove(r) {
787 for _, f := range c.callbacks.DeletedRequest {
788 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
790 c.updateExpectingChunks()
791 if c.t.requestingPeer(r) != c {
792 panic("only one peer should have a given request at a time")
794 delete(c.t.requestState, r)
795 // c.t.iterPeers(func(p *Peer) {
796 // if p.isLowOnRequests() {
797 // p.updateRequests("Peer.deleteRequest")
803 func (c *Peer) deleteAllRequests(reason string) {
804 if c.requestState.Requests.IsEmpty() {
807 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
808 if !c.deleteRequest(x) {
809 panic("request should exist")
814 c.t.iterPeers(func(p *Peer) {
815 if p.isLowOnRequests() {
816 p.updateRequests(reason)
822 func (c *Peer) assertNoRequests() {
823 if !c.requestState.Requests.IsEmpty() {
824 panic(c.requestState.Requests.GetCardinality())
828 func (c *Peer) cancelAllRequests() {
829 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
837 func (c *Peer) peerPriority() (peerPriority, error) {
838 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
841 func (c *Peer) remoteIp() net.IP {
842 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
843 return net.ParseIP(host)
846 func (c *Peer) remoteIpPort() IpPort {
847 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
848 return IpPort{ipa.IP, uint16(ipa.Port)}
851 func (c *Peer) trust() connectionTrust {
852 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
855 type connectionTrust struct {
857 NetGoodPiecesDirted int64
860 func (l connectionTrust) Less(r connectionTrust) bool {
861 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
864 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
865 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
866 // TODO: Can we use copy on write?
867 ret := cn.peerPieces().Clone()
868 if all, _ := cn.peerHasAllPieces(); all {
870 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
872 ret.AddRange(0, bitmap.ToEnd)
878 func (cn *Peer) stats() *ConnStats {
882 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
883 pc, ok := p.peerImpl.(*PeerConn)
887 func (p *Peer) uncancelledRequests() uint64 {
888 return p.requestState.Requests.GetCardinality()
891 type peerLocalPublicAddr = IpPort
893 func (p *Peer) isLowOnRequests() bool {
894 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
897 func (p *Peer) decPeakRequests() {
898 // // This can occur when peak requests are altered by the update request timer to be lower than
899 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
900 // // wonder what happens if maxRequests is not signed.
901 // if p.peakRequests < 1 {
902 // panic(p.peakRequests)