17 "github.com/RoaringBitmap/roaring"
18 "github.com/anacrolix/log"
19 "github.com/anacrolix/missinggo/iter"
20 "github.com/anacrolix/missinggo/v2/bitmap"
21 "github.com/anacrolix/multiless"
23 "github.com/anacrolix/chansync"
24 "github.com/anacrolix/torrent/bencode"
25 "github.com/anacrolix/torrent/metainfo"
26 "github.com/anacrolix/torrent/mse"
27 pp "github.com/anacrolix/torrent/peer_protocol"
28 request_strategy "github.com/anacrolix/torrent/request-strategy"
31 type PeerSource string
34 PeerSourceTracker = "Tr"
35 PeerSourceIncoming = "I"
36 PeerSourceDhtGetPeers = "Hg" // Peers we found by searching a DHT.
37 PeerSourceDhtAnnouncePeer = "Ha" // Peers that were announced to us by a DHT.
39 // The peer was given directly, such as through a magnet link.
40 PeerSourceDirect = "M"
43 type peerRequestState struct {
47 type PeerRemoteAddr interface {
51 // Since we have to store all the requests in memory, we can't reasonably exceed what would be
52 // indexable with the memory space available.
55 requestState = request_strategy.PeerNextRequestState
59 // First to ensure 64-bit alignment for atomics. See #262.
69 RemoteAddr PeerRemoteAddr
70 // True if the connection is operating over MSE obfuscation.
72 cryptoMethod mse.CryptoMethod
75 closed chansync.SetOnce
76 // Set true after we've added our ConnStats generated during handshake to
77 // other ConnStat instances as determined when the *Torrent became known.
78 reconciledHandshakeStats bool
80 lastMessageReceived time.Time
81 completedHandshake time.Time
82 lastUsefulChunkReceived time.Time
83 lastChunkSent time.Time
85 // Stuff controlled by the local peer.
86 needRequestUpdate string
87 actualRequestState requestState
88 updateRequestsTimer *time.Timer
89 cancelledRequests roaring.Bitmap
90 lastBecameInterested time.Time
91 priorInterest time.Duration
93 lastStartedExpectingToReceiveChunks time.Time
94 cumulativeExpectedToReceiveChunks time.Duration
95 _chunksReceivedWhileExpecting int64
98 piecesReceivedSinceLastRequestUpdate maxRequests
99 maxPiecesReceivedBetweenRequestUpdates maxRequests
100 // Chunks that we might reasonably expect to receive from the peer. Due to
101 // latency, buffering, and implementation differences, we may receive
102 // chunks that are no longer in the set of requests actually want.
103 validReceiveChunks map[RequestIndex]int
104 // Indexed by metadata piece, set to true if posted and pending a
106 metadataRequests []bool
107 sentHaves bitmap.Bitmap
109 // Stuff controlled by the remote peer.
112 peerRequests map[Request]*peerRequestState
113 PeerPrefersEncryption bool // as indicated by 'e' field in extension handshake
115 // The highest possible number of pieces the torrent could have based on
116 // communication with the peer. Generally only useful until we have the
118 peerMinPieces pieceIndex
119 // Pieces we've accepted chunks for from the peer.
120 peerTouchedPieces map[pieceIndex]struct{}
121 peerAllowedFast roaring.Bitmap
123 PeerMaxRequests maxRequests // Maximum pending requests the peer allows.
124 PeerExtensionIDs map[pp.ExtensionName]pp.ExtensionNumber
125 PeerClientName atomic.Value
130 // Maintains the state of a BitTorrent-protocol based connection with a peer.
131 type PeerConn struct {
134 // A string that should identify the PeerConn's net.Conn endpoints. The net.Conn could
135 // be wrapping WebRTC, uTP, or TCP etc. Used in writing the conn status for peers.
140 PeerExtensionBytes pp.PeerExtensionBits
142 // The actual Conn, used for closing, and setting socket options. Do not use methods on this
143 // while holding any mutexes.
145 // The Reader and Writer for this Conn, with hooks installed for stats,
146 // limiting, deadlines etc.
150 messageWriter peerConnMsgWriter
152 uploadTimer *time.Timer
155 // The pieces the peer has claimed to have.
156 _peerPieces roaring.Bitmap
157 // The peer has everything. This can occur due to a special message, when
158 // we may not even know the number of pieces in the torrent yet.
162 func (cn *PeerConn) connStatusString() string {
163 return fmt.Sprintf("%+-55q %s %s", cn.PeerID, cn.PeerExtensionBytes, cn.connString)
166 func (cn *Peer) updateExpectingChunks() {
167 if cn.expectingChunks() {
168 if cn.lastStartedExpectingToReceiveChunks.IsZero() {
169 cn.lastStartedExpectingToReceiveChunks = time.Now()
172 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
173 cn.cumulativeExpectedToReceiveChunks += time.Since(cn.lastStartedExpectingToReceiveChunks)
174 cn.lastStartedExpectingToReceiveChunks = time.Time{}
179 func (cn *Peer) expectingChunks() bool {
180 if cn.actualRequestState.Requests.IsEmpty() {
183 if !cn.actualRequestState.Interested {
189 haveAllowedFastRequests := false
190 cn.peerAllowedFast.Iterate(func(i uint32) bool {
191 haveAllowedFastRequests = roaringBitmapRangeCardinality(
192 &cn.actualRequestState.Requests,
193 cn.t.pieceRequestIndexOffset(pieceIndex(i)),
194 cn.t.pieceRequestIndexOffset(pieceIndex(i+1)),
196 return !haveAllowedFastRequests
198 return haveAllowedFastRequests
201 func (cn *Peer) remoteChokingPiece(piece pieceIndex) bool {
202 return cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(piece))
205 // Returns true if the connection is over IPv6.
206 func (cn *PeerConn) ipv6() bool {
211 return len(ip) == net.IPv6len
214 // Returns true the if the dialer/initiator has the lower client peer ID. TODO: Find the
215 // specification for this.
216 func (cn *PeerConn) isPreferredDirection() bool {
217 return bytes.Compare(cn.t.cl.peerID[:], cn.PeerID[:]) < 0 == cn.outgoing
220 // Returns whether the left connection should be preferred over the right one,
221 // considering only their networking properties. If ok is false, we can't
223 func (l *PeerConn) hasPreferredNetworkOver(r *PeerConn) (left, ok bool) {
225 ml.NextBool(l.isPreferredDirection(), r.isPreferredDirection())
226 ml.NextBool(!l.utp(), !r.utp())
227 ml.NextBool(l.ipv6(), r.ipv6())
231 func (cn *Peer) cumInterest() time.Duration {
232 ret := cn.priorInterest
233 if cn.actualRequestState.Interested {
234 ret += time.Since(cn.lastBecameInterested)
239 func (cn *PeerConn) peerHasAllPieces() (all bool, known bool) {
240 if cn.peerSentHaveAll {
243 if !cn.t.haveInfo() {
246 return cn._peerPieces.GetCardinality() == uint64(cn.t.numPieces()), true
249 func (cn *Peer) locker() *lockWithDeferreds {
250 return cn.t.cl.locker()
253 func (cn *Peer) supportsExtension(ext pp.ExtensionName) bool {
254 _, ok := cn.PeerExtensionIDs[ext]
258 // The best guess at number of pieces in the torrent for this peer.
259 func (cn *Peer) bestPeerNumPieces() pieceIndex {
261 return cn.t.numPieces()
263 return cn.peerMinPieces
266 func (cn *Peer) completedString() string {
267 have := pieceIndex(cn.peerPieces().GetCardinality())
268 if all, _ := cn.peerHasAllPieces(); all {
269 have = cn.bestPeerNumPieces()
271 return fmt.Sprintf("%d/%d", have, cn.bestPeerNumPieces())
274 func (cn *PeerConn) onGotInfo(info *metainfo.Info) {
275 cn.setNumPieces(info.NumPieces())
278 // Correct the PeerPieces slice length. Return false if the existing slice is invalid, such as by
279 // receiving badly sized BITFIELD, or invalid HAVE messages.
280 func (cn *PeerConn) setNumPieces(num pieceIndex) {
281 cn._peerPieces.RemoveRange(bitmap.BitRange(num), bitmap.ToEnd)
282 cn.peerPiecesChanged()
285 func (cn *PeerConn) peerPieces() *roaring.Bitmap {
286 return &cn._peerPieces
289 func eventAgeString(t time.Time) string {
293 return fmt.Sprintf("%.2fs ago", time.Since(t).Seconds())
296 func (cn *PeerConn) connectionFlags() (ret string) {
298 ret += string([]byte{b})
300 if cn.cryptoMethod == mse.CryptoMethodRC4 {
302 } else if cn.headerEncrypted {
305 ret += string(cn.Discovery)
312 func (cn *PeerConn) utp() bool {
313 return parseNetworkString(cn.Network).Udp
316 // Inspired by https://github.com/transmission/transmission/wiki/Peer-Status-Text.
317 func (cn *Peer) statusFlags() (ret string) {
319 ret += string([]byte{b})
321 if cn.actualRequestState.Interested {
328 ret += cn.connectionFlags()
330 if cn.peerInterested {
339 func (cn *Peer) downloadRate() float64 {
340 num := cn._stats.BytesReadUsefulData.Int64()
344 return float64(num) / cn.totalExpectingTime().Seconds()
347 func (cn *Peer) numRequestsByPiece() (ret map[pieceIndex]int) {
348 ret = make(map[pieceIndex]int)
349 cn.actualRequestState.Requests.Iterate(func(x uint32) bool {
350 ret[pieceIndex(x/cn.t.chunksPerRegularPiece())]++
356 func (cn *Peer) writeStatus(w io.Writer, t *Torrent) {
357 // \t isn't preserved in <pre> blocks?
358 if cn.closed.IsSet() {
359 fmt.Fprint(w, "CLOSED: ")
361 fmt.Fprintln(w, cn.connStatusString())
362 prio, err := cn.peerPriority()
363 prioStr := fmt.Sprintf("%08x", prio)
365 prioStr += ": " + err.Error()
367 fmt.Fprintf(w, " bep40-prio: %v\n", prioStr)
368 fmt.Fprintf(w, " last msg: %s, connected: %s, last helpful: %s, itime: %s, etime: %s\n",
369 eventAgeString(cn.lastMessageReceived),
370 eventAgeString(cn.completedHandshake),
371 eventAgeString(cn.lastHelpful()),
373 cn.totalExpectingTime(),
376 " %s completed, %d pieces touched, good chunks: %v/%v:%v reqq: %d-%v/(%d/%d):%d/%d, flags: %s, dr: %.1f KiB/s\n",
377 cn.completedString(),
378 len(cn.peerTouchedPieces),
379 &cn._stats.ChunksReadUseful,
380 &cn._stats.ChunksRead,
381 &cn._stats.ChunksWritten,
382 cn.actualRequestState.Requests.GetCardinality(),
383 cn.cancelledRequests.GetCardinality(),
384 cn.nominalMaxRequests(),
386 len(cn.peerRequests),
389 cn.downloadRate()/(1<<10),
391 fmt.Fprintf(w, " requested pieces:")
392 type pieceNumRequestsType struct {
396 var pieceNumRequests []pieceNumRequestsType
397 for piece, count := range cn.numRequestsByPiece() {
398 pieceNumRequests = append(pieceNumRequests, pieceNumRequestsType{piece, count})
400 sort.Slice(pieceNumRequests, func(i, j int) bool {
401 return pieceNumRequests[i].piece < pieceNumRequests[j].piece
403 for _, elem := range pieceNumRequests {
404 fmt.Fprintf(w, " %v(%v)", elem.piece, elem.numRequests)
409 func (p *Peer) close() {
413 if p.updateRequestsTimer != nil {
414 p.updateRequestsTimer.Stop()
418 p.t.decPeerPieceAvailability(p)
420 for _, f := range p.callbacks.PeerClosed {
425 func (cn *PeerConn) onClose() {
426 if cn.pex.IsEnabled() {
433 if cb := cn.callbacks.PeerConnClosed; cb != nil {
438 // Peer definitely has a piece, for purposes of requesting. So it's not sufficient that we think
439 // they do (known=true).
440 func (cn *Peer) peerHasPiece(piece pieceIndex) bool {
441 if all, known := cn.peerHasAllPieces(); all && known {
444 return cn.peerPieces().ContainsInt(piece)
447 // 64KiB, but temporarily less to work around an issue with WebRTC. TODO: Update when
448 // https://github.com/pion/datachannel/issues/59 is fixed.
449 const writeBufferHighWaterLen = 1 << 15
451 // Writes a message into the write buffer. Returns whether it's okay to keep writing. Writing is
452 // done asynchronously, so it may be that we're not able to honour backpressure from this method.
453 func (cn *PeerConn) write(msg pp.Message) bool {
454 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
455 // We don't need to track bytes here because the connection's Writer has that behaviour injected
456 // (although there's some delay between us buffering the message, and the connection writer
457 // flushing it out.).
458 notFull := cn.messageWriter.write(msg)
459 // Last I checked only Piece messages affect stats, and we don't write those.
465 func (cn *PeerConn) requestMetadataPiece(index int) {
466 eID := cn.PeerExtensionIDs[pp.ExtensionNameMetadata]
467 if eID == pp.ExtensionDeleteNumber {
470 if index < len(cn.metadataRequests) && cn.metadataRequests[index] {
473 cn.logger.WithDefaultLevel(log.Debug).Printf("requesting metadata piece %d", index)
474 cn.write(pp.MetadataExtensionRequestMsg(eID, index))
475 for index >= len(cn.metadataRequests) {
476 cn.metadataRequests = append(cn.metadataRequests, false)
478 cn.metadataRequests[index] = true
481 func (cn *PeerConn) requestedMetadataPiece(index int) bool {
482 return index < len(cn.metadataRequests) && cn.metadataRequests[index]
485 // The actual value to use as the maximum outbound requests.
486 func (cn *Peer) nominalMaxRequests() (ret maxRequests) {
487 return maxRequests(clamp(1, int64(cn.PeerMaxRequests), 2048))
490 func (cn *Peer) totalExpectingTime() (ret time.Duration) {
491 ret = cn.cumulativeExpectedToReceiveChunks
492 if !cn.lastStartedExpectingToReceiveChunks.IsZero() {
493 ret += time.Since(cn.lastStartedExpectingToReceiveChunks)
498 func (cn *PeerConn) onPeerSentCancel(r Request) {
499 if _, ok := cn.peerRequests[r]; !ok {
500 torrent.Add("unexpected cancels received", 1)
503 if cn.fastEnabled() {
506 delete(cn.peerRequests, r)
510 func (cn *PeerConn) choke(msg messageWriter) (more bool) {
515 more = msg(pp.Message{
518 if cn.fastEnabled() {
519 for r := range cn.peerRequests {
520 // TODO: Don't reject pieces in allowed fast set.
524 cn.peerRequests = nil
529 func (cn *PeerConn) unchoke(msg func(pp.Message) bool) bool {
534 return msg(pp.Message{
539 func (cn *Peer) setInterested(interested bool) bool {
540 if cn.actualRequestState.Interested == interested {
543 cn.actualRequestState.Interested = interested
545 cn.lastBecameInterested = time.Now()
546 } else if !cn.lastBecameInterested.IsZero() {
547 cn.priorInterest += time.Since(cn.lastBecameInterested)
549 cn.updateExpectingChunks()
550 // log.Printf("%p: setting interest: %v", cn, interested)
551 return cn.writeInterested(interested)
554 func (pc *PeerConn) writeInterested(interested bool) bool {
555 return pc.write(pp.Message{
556 Type: func() pp.MessageType {
560 return pp.NotInterested
566 // The function takes a message to be sent, and returns true if more messages
568 type messageWriter func(pp.Message) bool
570 // This function seems to only used by Peer.request. It's all logic checks, so maybe we can no-op it
571 // when we want to go fast.
572 func (cn *Peer) shouldRequest(r RequestIndex) error {
573 pi := pieceIndex(r / cn.t.chunksPerRegularPiece())
574 if !cn.peerHasPiece(pi) {
575 return errors.New("requesting piece peer doesn't have")
577 if !cn.t.peerIsActive(cn) {
578 panic("requesting but not in active conns")
580 if cn.closed.IsSet() {
581 panic("requesting when connection is closed")
583 if cn.t.hashingPiece(pi) {
584 panic("piece is being hashed")
586 if cn.t.pieceQueuedForHash(pi) {
587 panic("piece is queued for hash")
589 if cn.peerChoking && !cn.peerAllowedFast.Contains(bitmap.BitIndex(pi)) {
590 // This could occur if we made a request with the fast extension, and then got choked and
591 // haven't had the request rejected yet.
592 if !cn.actualRequestState.Requests.Contains(r) {
593 panic("peer choking and piece not allowed fast")
599 func (cn *Peer) mustRequest(r RequestIndex) bool {
600 more, err := cn.request(r)
607 func (cn *Peer) request(r RequestIndex) (more bool, err error) {
608 if err := cn.shouldRequest(r); err != nil {
611 if cn.actualRequestState.Requests.Contains(r) {
614 if maxRequests(cn.actualRequestState.Requests.GetCardinality()) >= cn.nominalMaxRequests() {
615 return true, errors.New("too many outstanding requests")
617 cn.actualRequestState.Requests.Add(r)
618 if cn.validReceiveChunks == nil {
619 cn.validReceiveChunks = make(map[RequestIndex]int)
621 cn.validReceiveChunks[r]++
622 cn.t.pendingRequests[r] = cn
623 cn.t.lastRequested[r] = time.Now()
624 cn.updateExpectingChunks()
625 ppReq := cn.t.requestIndexToRequest(r)
626 for _, f := range cn.callbacks.SentRequest {
627 f(PeerRequestEvent{cn, ppReq})
629 return cn.peerImpl._request(ppReq), nil
632 func (me *PeerConn) _request(r Request) bool {
633 return me.write(pp.Message{
641 func (me *Peer) cancel(r RequestIndex) {
642 if !me.actualRequestState.Requests.Contains(r) {
648 func (me *PeerConn) _cancel(r RequestIndex) {
649 if me.cancelledRequests.Contains(r) {
650 // Already cancelled and waiting for a response.
653 // Transmission does not send rejects for received cancels. See
654 // https://github.com/transmission/transmission/pull/2275.
655 if me.fastEnabled() && !me.remoteIsTransmission() {
656 me.cancelledRequests.Add(r)
658 if !me.deleteRequest(r) {
659 panic("request not existing should have been guarded")
661 if me.isLowOnRequests() {
662 me.updateRequests("Peer.cancel")
665 me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
668 func (cn *PeerConn) fillWriteBuffer() {
669 if !cn.maybeUpdateActualRequestState() {
672 if cn.pex.IsEnabled() {
673 if flow := cn.pex.Share(cn.write); !flow {
680 func (cn *PeerConn) have(piece pieceIndex) {
681 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
686 Index: pp.Integer(piece),
688 cn.sentHaves.Add(bitmap.BitIndex(piece))
691 func (cn *PeerConn) postBitfield() {
692 if cn.sentHaves.Len() != 0 {
693 panic("bitfield must be first have-related message sent")
695 if !cn.t.haveAnyPieces() {
700 Bitfield: cn.t.bitfield(),
702 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
705 // Sets a reason to update requests, and if there wasn't already one, handle it.
706 func (cn *Peer) updateRequests(reason string) {
707 if cn.needRequestUpdate != "" {
710 cn.needRequestUpdate = reason
711 cn.handleUpdateRequests()
714 func (cn *PeerConn) handleUpdateRequests() {
715 // The writer determines the request state as needed when it can write.
719 // Emits the indices in the Bitmaps bms in order, never repeating any index.
720 // skip is mutated during execution, and its initial values will never be
722 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
723 return func(cb iter.Callback) {
724 for _, bm := range bms {
726 func(_i interface{}) bool {
728 if skip.Contains(bitmap.BitIndex(i)) {
731 skip.Add(bitmap.BitIndex(i))
742 func (cn *Peer) peerPiecesChanged() {
743 cn.t.maybeDropMutuallyCompletePeer(cn)
746 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
747 if newMin > cn.peerMinPieces {
748 cn.peerMinPieces = newMin
752 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
753 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
754 return errors.New("invalid piece")
756 if cn.peerHasPiece(piece) {
759 cn.raisePeerMinPieces(piece + 1)
760 if !cn.peerHasPiece(piece) {
761 cn.t.incPieceAvailability(piece)
763 cn._peerPieces.Add(uint32(piece))
764 if cn.t.wantPieceIndex(piece) {
765 cn.updateRequests("have")
767 cn.peerPiecesChanged()
771 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
773 panic("expected bitfield length divisible by 8")
775 // We know that the last byte means that at most the last 7 bits are wasted.
776 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
777 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
778 // Ignore known excess pieces.
779 bf = bf[:cn.t.numPieces()]
781 pp := cn.newPeerPieces()
782 cn.peerSentHaveAll = false
783 for i, have := range bf {
785 cn.raisePeerMinPieces(pieceIndex(i) + 1)
786 if !pp.Contains(bitmap.BitIndex(i)) {
787 cn.t.incPieceAvailability(i)
790 if pp.Contains(bitmap.BitIndex(i)) {
791 cn.t.decPieceAvailability(i)
795 cn._peerPieces.Add(uint32(i))
796 if cn.t.wantPieceIndex(i) {
797 cn.updateRequests("bitfield")
800 cn._peerPieces.Remove(uint32(i))
803 cn.peerPiecesChanged()
807 func (cn *PeerConn) onPeerHasAllPieces() {
810 npp, pc := cn.newPeerPieces(), t.numPieces()
811 for i := 0; i < pc; i += 1 {
812 if !npp.Contains(bitmap.BitIndex(i)) {
813 t.incPieceAvailability(i)
817 cn.peerSentHaveAll = true
818 cn._peerPieces.Clear()
819 if !cn.t._pendingPieces.IsEmpty() {
820 cn.updateRequests("Peer.onPeerHasAllPieces")
822 cn.peerPiecesChanged()
825 func (cn *PeerConn) onPeerSentHaveAll() error {
826 cn.onPeerHasAllPieces()
830 func (cn *PeerConn) peerSentHaveNone() error {
831 cn.t.decPeerPieceAvailability(&cn.Peer)
832 cn._peerPieces.Clear()
833 cn.peerSentHaveAll = false
834 cn.peerPiecesChanged()
838 func (c *PeerConn) requestPendingMetadata() {
842 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
843 // Peer doesn't support this.
846 // Request metadata pieces that we don't have in a random order.
848 for index := 0; index < c.t.metadataPieceCount(); index++ {
849 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
850 pending = append(pending, index)
853 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
854 for _, i := range pending {
855 c.requestMetadataPiece(i)
859 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
860 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
861 if msg.Type == pp.Extended {
862 for name, id := range cn.PeerExtensionIDs {
863 if id != msg.ExtendedID {
866 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
869 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
872 // After handshake, we know what Torrent and Client stats to include for a
874 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
880 // All ConnStats that include this connection. Some objects are not known
881 // until the handshake is complete, after which it's expected to reconcile the
883 func (cn *Peer) allStats(f func(*ConnStats)) {
885 if cn.reconciledHandshakeStats {
886 cn.postHandshakeStats(f)
890 func (cn *PeerConn) wroteBytes(n int64) {
891 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
894 func (cn *Peer) readBytes(n int64) {
895 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
898 // Returns whether the connection could be useful to us. We're seeding and
899 // they want data, we don't have metainfo and they can provide it, etc.
900 func (c *Peer) useful() bool {
902 if c.closed.IsSet() {
906 return c.supportsExtension("ut_metadata")
908 if t.seeding() && c.peerInterested {
911 if c.peerHasWantedPieces() {
917 func (c *Peer) lastHelpful() (ret time.Time) {
918 ret = c.lastUsefulChunkReceived
919 if c.t.seeding() && c.lastChunkSent.After(ret) {
920 ret = c.lastChunkSent
925 func (c *PeerConn) fastEnabled() bool {
926 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
929 func (c *PeerConn) reject(r Request) {
930 if !c.fastEnabled() {
931 panic("fast not enabled")
933 c.write(r.ToMsg(pp.Reject))
934 delete(c.peerRequests, r)
937 func (c *PeerConn) onReadRequest(r Request) error {
938 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
939 if _, ok := c.peerRequests[r]; ok {
940 torrent.Add("duplicate requests received", 1)
944 torrent.Add("requests received while choking", 1)
946 torrent.Add("requests rejected while choking", 1)
951 // TODO: What if they've already requested this?
952 if len(c.peerRequests) >= localClientReqq {
953 torrent.Add("requests received while queue full", 1)
957 // BEP 6 says we may close here if we choose.
960 if !c.t.havePiece(pieceIndex(r.Index)) {
961 // This isn't necessarily them screwing up. We can drop pieces
962 // from our storage, and can't communicate this to peers
963 // except by reconnecting.
964 requestsReceivedForMissingPieces.Add(1)
965 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
967 // Check this after we know we have the piece, so that the piece length will be known.
968 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
969 torrent.Add("bad requests received", 1)
970 return errors.New("bad Request")
972 if c.peerRequests == nil {
973 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
975 value := &peerRequestState{}
976 c.peerRequests[r] = value
977 go c.peerRequestDataReader(r, value)
982 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
983 b, err := readPeerRequestData(r, c)
985 defer c.locker().Unlock()
987 c.peerRequestDataReadFailed(err, r)
990 panic("data must be non-nil to trigger send")
997 // If this is maintained correctly, we might be able to support optional synchronous reading for
998 // chunk sending, the way it used to work.
999 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
1000 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1001 if c.t.closed.IsSet() {
1004 i := pieceIndex(r.Index)
1005 if c.t.pieceComplete(i) {
1006 // There used to be more code here that just duplicated the following break. Piece
1007 // completions are currently cached, so I'm not sure how helpful this update is, except to
1008 // pull any completion changes pushed to the storage backend in failed reads that got us
1010 c.t.updatePieceCompletion(i)
1012 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1013 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1014 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1015 // next connect. TODO: Support rejecting here too.
1017 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1022 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1023 b := make([]byte, r.Length)
1024 p := c.t.info.Piece(int(r.Index))
1025 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1032 panic("expected error")
1038 func runSafeExtraneous(f func()) {
1046 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1047 c.logger.WithLevel(level).WithContextText(fmt.Sprintf(
1048 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1049 )).SkipCallers(1).Printf(format, arg...)
1052 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1053 // exit. Returning will end the connection.
1054 func (c *PeerConn) mainReadLoop() (err error) {
1057 torrent.Add("connection.mainReadLoop returned with error", 1)
1059 torrent.Add("connection.mainReadLoop returned with no error", 1)
1065 decoder := pp.Decoder{
1066 R: bufio.NewReaderSize(c.r, 1<<17),
1067 MaxLength: 256 * 1024,
1075 err = decoder.Decode(&msg)
1077 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1080 if t.closed.IsSet() || c.closed.IsSet() {
1086 c.lastMessageReceived = time.Now()
1088 receivedKeepalives.Add(1)
1091 messageTypesReceived.Add(msg.Type.String(), 1)
1092 if msg.Type.FastExtension() && !c.fastEnabled() {
1093 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1094 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1101 if !c.fastEnabled() {
1102 c.deleteAllRequests()
1104 // We don't decrement pending requests here, let's wait for the peer to either
1105 // reject or satisfy the outstanding requests. Additionally some peers may unchoke
1106 // us and resume where they left off, we don't want to have piled on to those chunks
1107 // in the meanwhile. I think a peers ability to abuse this should be limited: they
1108 // could let us request a lot of stuff, then choke us and never reject, but they're
1109 // only a single peer, our chunk balancing should smooth over this abuse.
1111 c.peerChoking = true
1112 // We can now reset our interest. I think we do this after setting the flag in case the
1113 // peerImpl updates synchronously (webseeds?).
1114 if !c.actualRequestState.Requests.IsEmpty() {
1115 c.updateRequests("choked")
1117 c.updateExpectingChunks()
1120 // Some clients do this for some reason. Transmission doesn't error on this, so we
1121 // won't for consistency.
1122 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1125 c.peerChoking = false
1127 c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1128 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1133 if preservedCount != 0 {
1134 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1136 c.logger.WithLevel(log.Debug).Printf(
1137 "%v requests were preserved while being choked (fast=%v)",
1140 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1142 if !c.t._pendingPieces.IsEmpty() {
1143 c.updateRequests("unchoked")
1145 c.updateExpectingChunks()
1147 c.peerInterested = true
1149 case pp.NotInterested:
1150 c.peerInterested = false
1151 // We don't clear their requests since it isn't clear in the spec.
1152 // We'll probably choke them for this, which will clear them if
1153 // appropriate, and is clearly specified.
1155 err = c.peerSentHave(pieceIndex(msg.Index))
1157 err = c.peerSentBitfield(msg.Bitfield)
1159 r := newRequestFromMessage(&msg)
1160 err = c.onReadRequest(r)
1162 c.doChunkReadStats(int64(len(msg.Piece)))
1163 err = c.receiveChunk(&msg)
1164 if len(msg.Piece) == int(t.chunkSize) {
1165 t.chunkPool.Put(&msg.Piece)
1168 err = fmt.Errorf("receiving chunk: %w", err)
1171 req := newRequestFromMessage(&msg)
1172 c.onPeerSentCancel(req)
1174 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1178 pingAddr := net.UDPAddr{
1183 pingAddr.Port = int(msg.Port)
1185 cl.eachDhtServer(func(s DhtServer) {
1186 go s.Ping(&pingAddr)
1189 torrent.Add("suggests received", 1)
1190 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1191 c.updateRequests("suggested")
1193 err = c.onPeerSentHaveAll()
1195 err = c.peerSentHaveNone()
1197 c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1198 case pp.AllowedFast:
1199 torrent.Add("allowed fasts received", 1)
1200 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1201 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1203 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1205 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1213 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1214 if c.deleteRequest(r) {
1215 if c.isLowOnRequests() {
1216 c.updateRequests("Peer.remoteRejectedRequest")
1218 c.decExpectedChunkReceive(r)
1222 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1223 count := c.validReceiveChunks[r]
1225 delete(c.validReceiveChunks, r)
1226 } else if count > 1 {
1227 c.validReceiveChunks[r] = count - 1
1233 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1235 // TODO: Should we still do this?
1237 // These clients use their own extension IDs for outgoing message
1238 // types, which is incorrect.
1239 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1247 case pp.HandshakeExtendedID:
1248 var d pp.ExtendedHandshakeMessage
1249 if err := bencode.Unmarshal(payload, &d); err != nil {
1250 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1251 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1253 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1256 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1258 c.PeerMaxRequests = d.Reqq
1260 c.PeerClientName.Store(d.V)
1261 if c.PeerExtensionIDs == nil {
1262 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1264 c.PeerListenPort = d.Port
1265 c.PeerPrefersEncryption = d.Encryption
1266 for name, id := range d.M {
1267 if _, ok := c.PeerExtensionIDs[name]; !ok {
1268 peersSupportingExtension.Add(
1269 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1270 // entered here which caused problems later when unmarshalling.
1271 strconv.Quote(string(name)),
1274 c.PeerExtensionIDs[name] = id
1276 if d.MetadataSize != 0 {
1277 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1278 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1281 c.requestPendingMetadata()
1282 if !t.cl.config.DisablePEX {
1283 t.pex.Add(c) // we learnt enough now
1287 case metadataExtendedId:
1288 err := cl.gotMetadataExtensionMsg(payload, t, c)
1290 return fmt.Errorf("handling metadata extension message: %w", err)
1294 if !c.pex.IsEnabled() {
1295 return nil // or hang-up maybe?
1297 return c.pex.Recv(payload)
1299 return fmt.Errorf("unexpected extended message ID: %v", id)
1303 // Set both the Reader and Writer for the connection from a single ReadWriter.
1304 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1309 // Returns the Reader and Writer as a combined ReadWriter.
1310 func (cn *PeerConn) rw() io.ReadWriter {
1317 func (c *Peer) doChunkReadStats(size int64) {
1318 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1321 // Handle a received chunk from a peer.
1322 func (c *Peer) receiveChunk(msg *pp.Message) error {
1323 chunksReceived.Add("total", 1)
1325 ppReq := newRequestFromMessage(msg)
1326 req := c.t.requestIndexFromRequest(ppReq)
1329 chunksReceived.Add("while choked", 1)
1332 if c.validReceiveChunks[req] <= 0 {
1333 chunksReceived.Add("unexpected", 1)
1334 return errors.New("received unexpected chunk")
1336 c.decExpectedChunkReceive(req)
1338 if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1339 chunksReceived.Add("due to allowed fast", 1)
1342 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1343 // have actually already received the piece, while we have the Client unlocked to write the data
1345 deletedRequest := false
1347 if c.actualRequestState.Requests.Contains(req) {
1348 for _, f := range c.callbacks.ReceivedRequested {
1349 f(PeerMessageEvent{c, msg})
1352 // Request has been satisfied.
1353 if c.deleteRequest(req) {
1354 deletedRequest = true
1356 c._chunksReceivedWhileExpecting++
1358 if c.isLowOnRequests() {
1359 c.updateRequests("Peer.receiveChunk deleted request")
1362 chunksReceived.Add("unwanted", 1)
1369 // Do we actually want this chunk?
1370 if t.haveChunk(ppReq) {
1371 // panic(fmt.Sprintf("%+v", ppReq))
1372 chunksReceived.Add("wasted", 1)
1373 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1377 piece := &t.pieces[ppReq.Index]
1379 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1380 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1382 c.piecesReceivedSinceLastRequestUpdate++
1383 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1385 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1386 f(ReceivedUsefulDataEvent{c, msg})
1388 c.lastUsefulChunkReceived = time.Now()
1390 // Need to record that it hasn't been written yet, before we attempt to do
1391 // anything with it.
1392 piece.incrementPendingWrites()
1393 // Record that we have the chunk, so we aren't trying to download it while
1394 // waiting for it to be written to storage.
1395 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1397 // Cancel pending requests for this chunk from *other* peers.
1398 if p := t.pendingRequests[req]; p != nil {
1400 panic("should not be pending request from conn that just received it")
1405 err := func() error {
1408 concurrentChunkWrites.Add(1)
1409 defer concurrentChunkWrites.Add(-1)
1410 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1411 // number of connections. We write inline with receiving the chunk (with this lock dance),
1412 // because we want to handle errors synchronously and I haven't thought of a nice way to
1413 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1415 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1418 piece.decrementPendingWrites()
1421 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1423 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1424 // request update runs while we're writing the chunk that just failed. Then we never do a
1425 // fresh update after pending the failed request.
1426 c.updateRequests("Peer.receiveChunk error writing chunk")
1427 t.onWriteChunkErr(err)
1431 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1433 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1434 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1435 t.queuePieceCheck(pieceIndex(ppReq.Index))
1436 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1437 // chunk status (such as the haveChunk call above) to have to check all the various other
1438 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1439 // that chunk pieces are pended at an appropriate time later however.
1442 cl.event.Broadcast()
1443 // We do this because we've written a chunk, and may change PieceState.Partial.
1444 t.publishPieceChange(pieceIndex(ppReq.Index))
1449 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1450 if c.peerTouchedPieces == nil {
1451 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1453 c.peerTouchedPieces[piece] = struct{}{}
1454 ds := &c.t.pieces[piece].dirtiers
1456 *ds = make(map[*Peer]struct{})
1458 (*ds)[c] = struct{}{}
1461 func (c *PeerConn) uploadAllowed() bool {
1462 if c.t.cl.config.NoUpload {
1465 if c.t.dataUploadDisallowed {
1471 if !c.peerHasWantedPieces() {
1474 // Don't upload more than 100 KiB more than we download.
1475 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1481 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1482 if c.uploadTimer == nil {
1483 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1485 c.uploadTimer.Reset(delay)
1489 // Also handles choking and unchoking of the remote peer.
1490 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1491 // Breaking or completing this loop means we don't want to upload to the
1492 // peer anymore, and we choke them.
1494 for c.uploadAllowed() {
1495 // We want to upload to the peer.
1496 if !c.unchoke(msg) {
1499 for r, state := range c.peerRequests {
1500 if state.data == nil {
1503 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1505 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1507 delay := res.Delay()
1510 c.setRetryUploadTimer(delay)
1511 // Hard to say what to return here.
1514 more := c.sendChunk(r, msg, state)
1515 delete(c.peerRequests, r)
1526 func (cn *PeerConn) drop() {
1527 cn.t.dropConnection(cn)
1530 func (cn *Peer) netGoodPiecesDirtied() int64 {
1531 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1534 func (c *Peer) peerHasWantedPieces() bool {
1535 if all, _ := c.peerHasAllPieces(); all {
1536 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1538 if !c.t.haveInfo() {
1539 return !c.peerPieces().IsEmpty()
1541 return c.peerPieces().Intersects(&c.t._pendingPieces)
1544 func (c *Peer) deleteRequest(r RequestIndex) bool {
1545 if !c.actualRequestState.Requests.CheckedRemove(r) {
1548 c.cancelledRequests.Remove(r)
1549 for _, f := range c.callbacks.DeletedRequest {
1550 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1552 c.updateExpectingChunks()
1553 if c.t.requestingPeer(r) == c {
1554 delete(c.t.pendingRequests, r)
1555 delete(c.t.lastRequested, r)
1560 func (c *Peer) deleteAllRequests() {
1561 c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1565 if !c.actualRequestState.Requests.IsEmpty() {
1566 panic(c.actualRequestState.Requests.GetCardinality())
1570 // This is called when something has changed that should wake the writer, such as putting stuff into
1571 // the writeBuffer, or changing some state that the writer can act on.
1572 func (c *PeerConn) tickleWriter() {
1573 c.messageWriter.writeCond.Broadcast()
1576 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1577 c.lastChunkSent = time.Now()
1578 return msg(pp.Message{
1586 func (c *PeerConn) setTorrent(t *Torrent) {
1588 panic("connection already associated with a torrent")
1591 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1592 t.reconcileHandshakeStats(c)
1595 func (c *Peer) peerPriority() (peerPriority, error) {
1596 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1599 func (c *Peer) remoteIp() net.IP {
1600 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1601 return net.ParseIP(host)
1604 func (c *Peer) remoteIpPort() IpPort {
1605 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1606 return IpPort{ipa.IP, uint16(ipa.Port)}
1609 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1610 f := pp.PexPeerFlags(0)
1611 if c.PeerPrefersEncryption {
1612 f |= pp.PexPrefersEncryption
1615 f |= pp.PexOutgoingConn
1618 f |= pp.PexSupportsUtp
1623 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1624 // advertised listen port.
1625 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1626 if !c.outgoing && c.PeerListenPort != 0 {
1627 switch addr := c.RemoteAddr.(type) {
1630 dialAddr.Port = c.PeerListenPort
1634 dialAddr.Port = c.PeerListenPort
1641 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1642 f := c.pexPeerFlags()
1643 addr := c.dialAddr()
1644 return pexEvent{t, addr, f, nil}
1647 func (c *PeerConn) String() string {
1648 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1651 func (c *Peer) trust() connectionTrust {
1652 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1655 type connectionTrust struct {
1657 NetGoodPiecesDirted int64
1660 func (l connectionTrust) Less(r connectionTrust) bool {
1661 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1664 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1665 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1666 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1668 defer cn.locker().RUnlock()
1669 return cn.newPeerPieces()
1672 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1673 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1674 // TODO: Can we use copy on write?
1675 ret := cn.peerPieces().Clone()
1676 if all, _ := cn.peerHasAllPieces(); all {
1677 if cn.t.haveInfo() {
1678 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1680 ret.AddRange(0, bitmap.ToEnd)
1686 func (cn *Peer) stats() *ConnStats {
1690 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1691 pc, ok := p.peerImpl.(*PeerConn)
1695 func (pc *PeerConn) isLowOnRequests() bool {
1696 return pc.actualRequestState.Requests.IsEmpty()
1699 func (p *Peer) uncancelledRequests() uint64 {
1700 return p.actualRequestState.Requests.GetCardinality() - p.cancelledRequests.GetCardinality()
1703 func (pc *PeerConn) remoteIsTransmission() bool {
1704 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'