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
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 PeerSourceUtHolepunch = "C"
121 PeerSourceTracker = "Tr"
122 PeerSourceIncoming = "I"
123 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
124 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
126 // The peer was given directly, such as through a magnet link.
127 PeerSourceDirect = "M"
130 // Returns the Torrent a Peer belongs to. Shouldn't change for the lifetime of the Peer. May be nil
131 // if we are the receiving end of a connection and the handshake hasn't been received or accepted
133 func (p *Peer) Torrent() *Torrent {
137 func (p *Peer) initRequestState() {
138 p.requestState.Requests = &peerRequests{}
141 func (cn *Peer) updateExpectingChunks() {
142 if cn.expectingChunks() {
143 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
144 cn.lastStartedExpectingToReceiveChunks = time.Now()
147 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
148 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
149 cn.lastStartedExpectingToReceiveChunks = time.Time{}
154 func (cn *Peer) expectingChunks() bool {
155 if cn.requestState.Requests.IsEmpty() {
158 if !cn.requestState.Interested {
164 haveAllowedFastRequests := false
165 cn.peerAllowedFast.Iterate(func(i pieceIndex) bool {
166 haveAllowedFastRequests = roaringBitmapRangeCardinality[RequestIndex](
167 cn.requestState.Requests,
168 cn.t.pieceRequestIndexOffset(i),
169 cn.t.pieceRequestIndexOffset(i+1),
171 return !haveAllowedFastRequests
173 return haveAllowedFastRequests
176 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
177 return cn.peerChoking && !cn.peerAllowedFast.Contains(piece)
180 func (cn *Peer) cumInterest() time.Duration {
181 ret := cn.priorInterest
182 if cn.requestState.Interested {
183 ret += time.Since(cn.lastBecameInterested)
188 func (cn *Peer) locker() *lockWithDeferreds {
189 return cn.t.cl.locker()
192 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
193 _, ok := cn.PeerExtensionIDs[ext]
197 // The best guess at number of pieces in the torrent for this peer.
198 func (cn *Peer) bestPeerNumPieces() pieceIndex {
200 return cn.t.numPieces()
202 return cn.peerMinPieces
205 func (cn *Peer) completedString() string {
206 have := pieceIndex(cn.peerPieces().GetCardinality())
207 if all, _ := cn.peerHasAllPieces(); all {
208 have = cn.bestPeerNumPieces()
210 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
213 func eventAgeString(t time.Time) string {
217 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
220 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
221 func (cn *Peer) statusFlags() (ret string) {
223 ret += string([]byte{b})
225 if cn.requestState.Interested {
232 ret += cn.connectionFlags()
234 if cn.peerInterested {
243 func (cn *Peer) downloadRate() float64 {
244 num := cn._stats.BytesReadUsefulData.Int64()
248 return float64(num) / cn.totalExpectingTime().Seconds()
251 func (cn *Peer) DownloadRate() float64 {
253 defer cn.locker().RUnlock()
255 return cn.downloadRate()
258 func (cn *Peer) iterContiguousPieceRequests(f func(piece pieceIndex, count int)) {
259 var last Option[pieceIndex]
261 next := func(item Option[pieceIndex]) {
272 cn.requestState.Requests.Iterate(func(requestIndex request_strategy.RequestIndex) bool {
273 next(Some(cn.t.pieceIndexOfRequestIndex(requestIndex)))
276 next(None[pieceIndex]())
279 func (cn *Peer) writeStatus(w io.Writer) {
280 // \t isn't preserved in <pre> blocks?
281 if cn.closed.IsSet() {
282 fmt.Fprint(w, "CLOSED: ")
284 fmt.Fprintln(w, strings.Join(cn.peerImplStatusLines(), "\n"))
285 prio, err := cn.peerPriority()
286 prioStr := fmt.Sprintf("%08x", prio)
288 prioStr += ": " + err.Error()
290 fmt.Fprintf(w, "bep40-prio: %v\n", prioStr)
291 fmt.Fprintf(w, "last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
292 eventAgeString(cn.lastMessageReceived),
293 eventAgeString(cn.completedHandshake),
294 eventAgeString(cn.lastHelpful()),
296 cn.totalExpectingTime(),
299 "%s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d+%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
300 cn.completedString(),
301 len(cn.peerTouchedPieces),
302 &cn._stats.ChunksReadUseful,
303 &cn._stats.ChunksRead,
304 &cn._stats.ChunksWritten,
305 cn.requestState.Requests.GetCardinality(),
306 cn.requestState.Cancelled.GetCardinality(),
307 cn.nominalMaxRequests(),
309 len(cn.peerRequests),
312 cn.downloadRate()/(1<<10),
314 fmt.Fprintf(w, "requested pieces:")
315 cn.iterContiguousPieceRequests(func(piece pieceIndex, count int) {
316 fmt.Fprintf(w, " %v(%v)", piece, count)
321 func (p *Peer) close() {
325 if p.updateRequestsTimer != nil {
326 p.updateRequestsTimer.Stop()
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 if !me.requestState.Cancelled.CheckedAdd(r) {
470 panic("request already cancelled")
474 if me.isLowOnRequests() {
475 me.updateRequests("Peer.cancel")
479 // Sets a reason to update requests, and if there wasn't already one, handle it.
480 func (cn *Peer) updateRequests(reason string) {
481 if cn.needRequestUpdate != "" {
484 if reason != peerUpdateRequestsTimerReason && !cn.isLowOnRequests() {
487 cn.needRequestUpdate = reason
488 cn.handleUpdateRequests()
491 // Emits the indices in the Bitmaps bms in order, never repeating any index.
492 // skip is mutated during execution, and its initial values will never be
494 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
495 return func(cb iter.Callback) {
496 for _, bm := range bms {
498 func(_i interface{}) bool {
500 if skip.Contains(bitmap.BitIndex(i)) {
503 skip.Add(bitmap.BitIndex(i))
514 func (cn *Peer) peerPiecesChanged() {
515 cn.t.maybeDropMutuallyCompletePeer(cn)
518 // After handshake, we know what Torrent and Client stats to include for a
520 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
526 // All ConnStats that include this connection. Some objects are not known
527 // until the handshake is complete, after which it's expected to reconcile the
529 func (cn *Peer) allStats(f func(*ConnStats)) {
531 if cn.reconciledHandshakeStats {
532 cn.postHandshakeStats(f)
536 func (cn *Peer) readBytes(n int64) {
537 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
540 // Returns whether the connection could be useful to us. We're seeding and
541 // they want data, we don't have metainfo and they can provide it, etc.
542 func (c *Peer) useful() bool {
544 if c.closed.IsSet() {
548 return c.supportsExtension("ut_metadata")
550 if t.seeding() && c.peerInterested {
553 if c.peerHasWantedPieces() {
559 func (c *Peer) lastHelpful() (ret time.Time) {
560 ret = c.lastUsefulChunkReceived
561 if c.t.seeding() && c.lastChunkSent.After(ret) {
562 ret = c.lastChunkSent
567 // Returns whether any part of the chunk would lie outside a piece of the given length.
568 func chunkOverflowsPiece(cs ChunkSpec, pieceLength pp.Integer) bool {
572 case cs.Begin+cs.Length > pieceLength:
573 // Check for integer overflow
574 case cs.Begin > pp.IntegerMax-cs.Length:
579 func runSafeExtraneous(f func()) {
587 // Returns true if it was valid to reject the request.
588 func (c *Peer) remoteRejectedRequest(r RequestIndex) bool {
589 if c.deleteRequest(r) {
591 } else if !c.requestState.Cancelled.CheckedRemove(r) {
594 if c.isLowOnRequests() {
595 c.updateRequests("Peer.remoteRejectedRequest")
597 c.decExpectedChunkReceive(r)
601 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
602 count := c.validReceiveChunks[r]
604 delete(c.validReceiveChunks, r)
605 } else if count > 1 {
606 c.validReceiveChunks[r] = count - 1
612 func (c *Peer) doChunkReadStats(size int64) {
613 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
616 // Handle a received chunk from a peer.
617 func (c *Peer) receiveChunk(msg *pp.Message) error {
618 chunksReceived.Add("total", 1)
620 ppReq := newRequestFromMessage(msg)
622 err := t.checkValidReceiveChunk(ppReq)
624 err = log.WithLevel(log.Warning, err)
627 req := c.t.requestIndexFromRequest(ppReq)
629 if c.bannableAddr.Ok {
630 t.smartBanCache.RecordBlock(c.bannableAddr.Value, req, msg.Piece)
634 chunksReceived.Add("while choked", 1)
637 if c.validReceiveChunks[req] <= 0 {
638 chunksReceived.Add("unexpected", 1)
639 return errors.New("received unexpected chunk")
641 c.decExpectedChunkReceive(req)
643 if c.peerChoking && c.peerAllowedFast.Contains(pieceIndex(ppReq.Index)) {
644 chunksReceived.Add("due to allowed fast", 1)
647 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
648 // have actually already received the piece, while we have the Client unlocked to write the data
652 if c.requestState.Requests.Contains(req) {
653 for _, f := range c.callbacks.ReceivedRequested {
654 f(PeerMessageEvent{c, msg})
657 // Request has been satisfied.
658 if c.deleteRequest(req) || c.requestState.Cancelled.CheckedRemove(req) {
661 c._chunksReceivedWhileExpecting++
663 if c.isLowOnRequests() {
664 c.updateRequests("Peer.receiveChunk deleted request")
667 chunksReceived.Add("unintended", 1)
673 // Do we actually want this chunk?
674 if t.haveChunk(ppReq) {
675 // panic(fmt.Sprintf("%+v", ppReq))
676 chunksReceived.Add("redundant", 1)
677 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
681 piece := &t.pieces[ppReq.Index]
683 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
684 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
686 c.piecesReceivedSinceLastRequestUpdate++
687 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
689 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
690 f(ReceivedUsefulDataEvent{c, msg})
692 c.lastUsefulChunkReceived = time.Now()
694 // Need to record that it hasn't been written yet, before we attempt to do
696 piece.incrementPendingWrites()
697 // Record that we have the chunk, so we aren't trying to download it while
698 // waiting for it to be written to storage.
699 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
701 // Cancel pending requests for this chunk from *other* peers.
702 if p := t.requestingPeer(req); p != nil {
704 panic("should not be pending request from conn that just received it")
712 concurrentChunkWrites.Add(1)
713 defer concurrentChunkWrites.Add(-1)
714 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
715 // number of connections. We write inline with receiving the chunk (with this lock dance),
716 // because we want to handle errors synchronously and I haven't thought of a nice way to
717 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
719 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
722 piece.decrementPendingWrites()
725 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
727 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
728 // request update runs while we're writing the chunk that just failed. Then we never do a
729 // fresh update after pending the failed request.
730 c.updateRequests("Peer.receiveChunk error writing chunk")
731 t.onWriteChunkErr(err)
735 c.onDirtiedPiece(pieceIndex(ppReq.Index))
737 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
738 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
739 t.queuePieceCheck(pieceIndex(ppReq.Index))
740 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
741 // chunk status (such as the haveChunk call above) to have to check all the various other
742 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
743 // that chunk pieces are pended at an appropriate time later however.
747 // We do this because we've written a chunk, and may change PieceState.Partial.
748 t.publishPieceChange(pieceIndex(ppReq.Index))
753 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
754 if c.peerTouchedPieces == nil {
755 c.peerTouchedPieces = make(map[pieceIndex]struct{})
757 c.peerTouchedPieces[piece] = struct{}{}
758 ds := &c.t.pieces[piece].dirtiers
760 *ds = make(map[*Peer]struct{})
762 (*ds)[c] = struct{}{}
765 func (cn *Peer) netGoodPiecesDirtied() int64 {
766 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
769 func (c *Peer) peerHasWantedPieces() bool {
770 if all, _ := c.peerHasAllPieces(); all {
771 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
774 return !c.peerPieces().IsEmpty()
776 return c.peerPieces().Intersects(&c.t._pendingPieces)
779 // Returns true if an outstanding request is removed. Cancelled requests should be handled
781 func (c *Peer) deleteRequest(r RequestIndex) bool {
782 if !c.requestState.Requests.CheckedRemove(r) {
785 for _, f := range c.callbacks.DeletedRequest {
786 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
788 c.updateExpectingChunks()
789 if c.t.requestingPeer(r) != c {
790 panic("only one peer should have a given request at a time")
792 delete(c.t.requestState, r)
793 // c.t.iterPeers(func(p *Peer) {
794 // if p.isLowOnRequests() {
795 // p.updateRequests("Peer.deleteRequest")
801 func (c *Peer) deleteAllRequests(reason string) {
802 if c.requestState.Requests.IsEmpty() {
805 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
806 if !c.deleteRequest(x) {
807 panic("request should exist")
812 c.t.iterPeers(func(p *Peer) {
813 if p.isLowOnRequests() {
814 p.updateRequests(reason)
820 func (c *Peer) assertNoRequests() {
821 if !c.requestState.Requests.IsEmpty() {
822 panic(c.requestState.Requests.GetCardinality())
826 func (c *Peer) cancelAllRequests() {
827 c.requestState.Requests.IterateSnapshot(func(x RequestIndex) bool {
835 func (c *Peer) peerPriority() (peerPriority, error) {
836 return bep40Priority(c.remoteIpPort(), c.localPublicAddr)
839 func (c *Peer) remoteIp() net.IP {
840 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
841 return net.ParseIP(host)
844 func (c *Peer) remoteIpPort() IpPort {
845 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
846 return IpPort{ipa.IP, uint16(ipa.Port)}
849 func (c *Peer) trust() connectionTrust {
850 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
853 type connectionTrust struct {
855 NetGoodPiecesDirted int64
858 func (l connectionTrust) Less(r connectionTrust) bool {
859 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
862 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
863 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
864 // TODO: Can we use copy on write?
865 ret := cn.peerPieces().Clone()
866 if all, _ := cn.peerHasAllPieces(); all {
868 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
870 ret.AddRange(0, bitmap.ToEnd)
876 func (cn *Peer) stats() *ConnStats {
880 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
881 pc, ok := p.peerImpl.(*PeerConn)
885 func (p *Peer) uncancelledRequests() uint64 {
886 return p.requestState.Requests.GetCardinality()
889 type peerLocalPublicAddr = IpPort
891 func (p *Peer) isLowOnRequests() bool {
892 return p.requestState.Requests.IsEmpty() && p.requestState.Cancelled.IsEmpty()
895 func (p *Peer) decPeakRequests() {
896 // // This can occur when peak requests are altered by the update request timer to be lower than
897 // // the actual number of outstanding requests. Let's let it go negative and see what happens. I
898 // // wonder what happens if maxRequests is not signed.
899 // if p.peakRequests < 1 {
900 // panic(p.peakRequests)