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.Inc(r)
623 cn.updateExpectingChunks()
624 ppReq := cn.t.requestIndexToRequest(r)
625 for _, f := range cn.callbacks.SentRequest {
626 f(PeerRequestEvent{cn, ppReq})
628 return cn.peerImpl._request(ppReq), nil
631 func (me *PeerConn) _request(r Request) bool {
632 return me.write(pp.Message{
640 func (me *Peer) cancel(r RequestIndex) bool {
641 if !me.actualRequestState.Requests.Contains(r) {
647 func (me *PeerConn) _cancel(r RequestIndex) bool {
648 if me.cancelledRequests.Contains(r) {
649 // Already cancelled and waiting for a response.
652 // Transmission does not send rejects for received cancels. See
653 // https://github.com/transmission/transmission/pull/2275.
654 if me.fastEnabled() && !me.remoteIsTransmission() {
655 me.cancelledRequests.Add(r)
657 if !me.deleteRequest(r) {
658 panic("request not existing should have been guarded")
660 if me.isLowOnRequests() {
661 me.updateRequests("Peer.cancel")
664 return me.write(makeCancelMessage(me.t.requestIndexToRequest(r)))
667 func (cn *PeerConn) fillWriteBuffer() {
668 if !cn.maybeUpdateActualRequestState() {
671 if cn.pex.IsEnabled() {
672 if flow := cn.pex.Share(cn.write); !flow {
679 func (cn *PeerConn) have(piece pieceIndex) {
680 if cn.sentHaves.Get(bitmap.BitIndex(piece)) {
685 Index: pp.Integer(piece),
687 cn.sentHaves.Add(bitmap.BitIndex(piece))
690 func (cn *PeerConn) postBitfield() {
691 if cn.sentHaves.Len() != 0 {
692 panic("bitfield must be first have-related message sent")
694 if !cn.t.haveAnyPieces() {
699 Bitfield: cn.t.bitfield(),
701 cn.sentHaves = bitmap.Bitmap{cn.t._completedPieces.Clone()}
704 // Sets a reason to update requests, and if there wasn't already one, handle it.
705 func (cn *Peer) updateRequests(reason string) {
706 if cn.needRequestUpdate != "" {
709 cn.needRequestUpdate = reason
710 cn.handleUpdateRequests()
713 func (cn *PeerConn) handleUpdateRequests() {
714 // The writer determines the request state as needed when it can write.
718 // Emits the indices in the Bitmaps bms in order, never repeating any index.
719 // skip is mutated during execution, and its initial values will never be
721 func iterBitmapsDistinct(skip *bitmap.Bitmap, bms ...bitmap.Bitmap) iter.Func {
722 return func(cb iter.Callback) {
723 for _, bm := range bms {
725 func(_i interface{}) bool {
727 if skip.Contains(bitmap.BitIndex(i)) {
730 skip.Add(bitmap.BitIndex(i))
741 func (cn *Peer) peerPiecesChanged() {
742 cn.t.maybeDropMutuallyCompletePeer(cn)
745 func (cn *PeerConn) raisePeerMinPieces(newMin pieceIndex) {
746 if newMin > cn.peerMinPieces {
747 cn.peerMinPieces = newMin
751 func (cn *PeerConn) peerSentHave(piece pieceIndex) error {
752 if cn.t.haveInfo() && piece >= cn.t.numPieces() || piece < 0 {
753 return errors.New("invalid piece")
755 if cn.peerHasPiece(piece) {
758 cn.raisePeerMinPieces(piece + 1)
759 if !cn.peerHasPiece(piece) {
760 cn.t.incPieceAvailability(piece)
762 cn._peerPieces.Add(uint32(piece))
763 if cn.t.wantPieceIndex(piece) {
764 cn.updateRequests("have")
766 cn.peerPiecesChanged()
770 func (cn *PeerConn) peerSentBitfield(bf []bool) error {
772 panic("expected bitfield length divisible by 8")
774 // We know that the last byte means that at most the last 7 bits are wasted.
775 cn.raisePeerMinPieces(pieceIndex(len(bf) - 7))
776 if cn.t.haveInfo() && len(bf) > int(cn.t.numPieces()) {
777 // Ignore known excess pieces.
778 bf = bf[:cn.t.numPieces()]
780 pp := cn.newPeerPieces()
781 cn.peerSentHaveAll = false
782 for i, have := range bf {
784 cn.raisePeerMinPieces(pieceIndex(i) + 1)
785 if !pp.Contains(bitmap.BitIndex(i)) {
786 cn.t.incPieceAvailability(i)
789 if pp.Contains(bitmap.BitIndex(i)) {
790 cn.t.decPieceAvailability(i)
794 cn._peerPieces.Add(uint32(i))
795 if cn.t.wantPieceIndex(i) {
796 cn.updateRequests("bitfield")
799 cn._peerPieces.Remove(uint32(i))
802 cn.peerPiecesChanged()
806 func (cn *PeerConn) onPeerHasAllPieces() {
809 npp, pc := cn.newPeerPieces(), t.numPieces()
810 for i := 0; i < pc; i += 1 {
811 if !npp.Contains(bitmap.BitIndex(i)) {
812 t.incPieceAvailability(i)
816 cn.peerSentHaveAll = true
817 cn._peerPieces.Clear()
818 if !cn.t._pendingPieces.IsEmpty() {
819 cn.updateRequests("Peer.onPeerHasAllPieces")
821 cn.peerPiecesChanged()
824 func (cn *PeerConn) onPeerSentHaveAll() error {
825 cn.onPeerHasAllPieces()
829 func (cn *PeerConn) peerSentHaveNone() error {
830 cn.t.decPeerPieceAvailability(&cn.Peer)
831 cn._peerPieces.Clear()
832 cn.peerSentHaveAll = false
833 cn.peerPiecesChanged()
837 func (c *PeerConn) requestPendingMetadata() {
841 if c.PeerExtensionIDs[pp.ExtensionNameMetadata] == 0 {
842 // Peer doesn't support this.
845 // Request metadata pieces that we don't have in a random order.
847 for index := 0; index < c.t.metadataPieceCount(); index++ {
848 if !c.t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
849 pending = append(pending, index)
852 rand.Shuffle(len(pending), func(i, j int) { pending[i], pending[j] = pending[j], pending[i] })
853 for _, i := range pending {
854 c.requestMetadataPiece(i)
858 func (cn *PeerConn) wroteMsg(msg *pp.Message) {
859 torrent.Add(fmt.Sprintf("messages written of type %s", msg.Type.String()), 1)
860 if msg.Type == pp.Extended {
861 for name, id := range cn.PeerExtensionIDs {
862 if id != msg.ExtendedID {
865 torrent.Add(fmt.Sprintf("Extended messages written for protocol %q", name), 1)
868 cn.allStats(func(cs *ConnStats) { cs.wroteMsg(msg) })
871 // After handshake, we know what Torrent and Client stats to include for a
873 func (cn *Peer) postHandshakeStats(f func(*ConnStats)) {
879 // All ConnStats that include this connection. Some objects are not known
880 // until the handshake is complete, after which it's expected to reconcile the
882 func (cn *Peer) allStats(f func(*ConnStats)) {
884 if cn.reconciledHandshakeStats {
885 cn.postHandshakeStats(f)
889 func (cn *PeerConn) wroteBytes(n int64) {
890 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesWritten }))
893 func (cn *Peer) readBytes(n int64) {
894 cn.allStats(add(n, func(cs *ConnStats) *Count { return &cs.BytesRead }))
897 // Returns whether the connection could be useful to us. We're seeding and
898 // they want data, we don't have metainfo and they can provide it, etc.
899 func (c *Peer) useful() bool {
901 if c.closed.IsSet() {
905 return c.supportsExtension("ut_metadata")
907 if t.seeding() && c.peerInterested {
910 if c.peerHasWantedPieces() {
916 func (c *Peer) lastHelpful() (ret time.Time) {
917 ret = c.lastUsefulChunkReceived
918 if c.t.seeding() && c.lastChunkSent.After(ret) {
919 ret = c.lastChunkSent
924 func (c *PeerConn) fastEnabled() bool {
925 return c.PeerExtensionBytes.SupportsFast() && c.t.cl.config.Extensions.SupportsFast()
928 func (c *PeerConn) reject(r Request) {
929 if !c.fastEnabled() {
930 panic("fast not enabled")
932 c.write(r.ToMsg(pp.Reject))
933 delete(c.peerRequests, r)
936 func (c *PeerConn) onReadRequest(r Request) error {
937 requestedChunkLengths.Add(strconv.FormatUint(r.Length.Uint64(), 10), 1)
938 if _, ok := c.peerRequests[r]; ok {
939 torrent.Add("duplicate requests received", 1)
943 torrent.Add("requests received while choking", 1)
945 torrent.Add("requests rejected while choking", 1)
950 // TODO: What if they've already requested this?
951 if len(c.peerRequests) >= localClientReqq {
952 torrent.Add("requests received while queue full", 1)
956 // BEP 6 says we may close here if we choose.
959 if !c.t.havePiece(pieceIndex(r.Index)) {
960 // This isn't necessarily them screwing up. We can drop pieces
961 // from our storage, and can't communicate this to peers
962 // except by reconnecting.
963 requestsReceivedForMissingPieces.Add(1)
964 return fmt.Errorf("peer requested piece we don't have: %v", r.Index.Int())
966 // Check this after we know we have the piece, so that the piece length will be known.
967 if r.Begin+r.Length > c.t.pieceLength(pieceIndex(r.Index)) {
968 torrent.Add("bad requests received", 1)
969 return errors.New("bad Request")
971 if c.peerRequests == nil {
972 c.peerRequests = make(map[Request]*peerRequestState, localClientReqq)
974 value := &peerRequestState{}
975 c.peerRequests[r] = value
976 go c.peerRequestDataReader(r, value)
981 func (c *PeerConn) peerRequestDataReader(r Request, prs *peerRequestState) {
982 b, err := readPeerRequestData(r, c)
984 defer c.locker().Unlock()
986 c.peerRequestDataReadFailed(err, r)
989 panic("data must be non-nil to trigger send")
996 // If this is maintained correctly, we might be able to support optional synchronous reading for
997 // chunk sending, the way it used to work.
998 func (c *PeerConn) peerRequestDataReadFailed(err error, r Request) {
999 c.logger.WithDefaultLevel(log.Warning).Printf("error reading chunk for peer Request %v: %v", r, err)
1000 if c.t.closed.IsSet() {
1003 i := pieceIndex(r.Index)
1004 if c.t.pieceComplete(i) {
1005 // There used to be more code here that just duplicated the following break. Piece
1006 // completions are currently cached, so I'm not sure how helpful this update is, except to
1007 // pull any completion changes pushed to the storage backend in failed reads that got us
1009 c.t.updatePieceCompletion(i)
1011 // If we failed to send a chunk, choke the peer to ensure they flush all their requests. We've
1012 // probably dropped a piece from storage, but there's no way to communicate this to the peer. If
1013 // they ask for it again, we'll kick them to allow us to send them an updated bitfield on the
1014 // next connect. TODO: Support rejecting here too.
1016 c.logger.WithDefaultLevel(log.Warning).Printf("already choking peer, requests might not be rejected correctly")
1021 func readPeerRequestData(r Request, c *PeerConn) ([]byte, error) {
1022 b := make([]byte, r.Length)
1023 p := c.t.info.Piece(int(r.Index))
1024 n, err := c.t.readAt(b, p.Offset()+int64(r.Begin))
1031 panic("expected error")
1037 func runSafeExtraneous(f func()) {
1045 func (c *PeerConn) logProtocolBehaviour(level log.Level, format string, arg ...interface{}) {
1046 c.logger.WithLevel(level).WithContextText(fmt.Sprintf(
1047 "peer id %q, ext v %q", c.PeerID, c.PeerClientName.Load(),
1048 )).SkipCallers(1).Printf(format, arg...)
1051 // Processes incoming BitTorrent wire-protocol messages. The client lock is held upon entry and
1052 // exit. Returning will end the connection.
1053 func (c *PeerConn) mainReadLoop() (err error) {
1056 torrent.Add("connection.mainReadLoop returned with error", 1)
1058 torrent.Add("connection.mainReadLoop returned with no error", 1)
1064 decoder := pp.Decoder{
1065 R: bufio.NewReaderSize(c.r, 1<<17),
1066 MaxLength: 256 * 1024,
1074 err = decoder.Decode(&msg)
1076 if cb := c.callbacks.ReadMessage; cb != nil && err == nil {
1079 if t.closed.IsSet() || c.closed.IsSet() {
1085 c.lastMessageReceived = time.Now()
1087 receivedKeepalives.Add(1)
1090 messageTypesReceived.Add(msg.Type.String(), 1)
1091 if msg.Type.FastExtension() && !c.fastEnabled() {
1092 runSafeExtraneous(func() { torrent.Add("fast messages received when extension is disabled", 1) })
1093 return fmt.Errorf("received fast extension message (type=%v) but extension is disabled", msg.Type)
1100 if !c.fastEnabled() {
1101 c.deleteAllRequests()
1103 // We don't decrement pending requests here, let's wait for the peer to either
1104 // reject or satisfy the outstanding requests. Additionally some peers may unchoke
1105 // us and resume where they left off, we don't want to have piled on to those chunks
1106 // in the meanwhile. I think a peers ability to abuse this should be limited: they
1107 // could let us request a lot of stuff, then choke us and never reject, but they're
1108 // only a single peer, our chunk balancing should smooth over this abuse.
1110 c.peerChoking = true
1111 // We can now reset our interest. I think we do this after setting the flag in case the
1112 // peerImpl updates synchronously (webseeds?).
1113 if !c.actualRequestState.Requests.IsEmpty() {
1114 c.updateRequests("choked")
1116 c.updateExpectingChunks()
1119 // Some clients do this for some reason. Transmission doesn't error on this, so we
1120 // won't for consistency.
1121 c.logProtocolBehaviour(log.Debug, "received unchoke when already unchoked")
1124 c.peerChoking = false
1126 c.actualRequestState.Requests.Iterate(func(x uint32) bool {
1127 if !c.peerAllowedFast.Contains(x / c.t.chunksPerRegularPiece()) {
1132 if preservedCount != 0 {
1133 // TODO: Yes this is a debug log but I'm not happy with the state of the logging lib
1135 c.logger.WithLevel(log.Debug).Printf(
1136 "%v requests were preserved while being choked (fast=%v)",
1139 torrent.Add("requestsPreservedThroughChoking", int64(preservedCount))
1141 if !c.t._pendingPieces.IsEmpty() {
1142 c.updateRequests("unchoked")
1144 c.updateExpectingChunks()
1146 c.peerInterested = true
1148 case pp.NotInterested:
1149 c.peerInterested = false
1150 // We don't clear their requests since it isn't clear in the spec.
1151 // We'll probably choke them for this, which will clear them if
1152 // appropriate, and is clearly specified.
1154 err = c.peerSentHave(pieceIndex(msg.Index))
1156 err = c.peerSentBitfield(msg.Bitfield)
1158 r := newRequestFromMessage(&msg)
1159 err = c.onReadRequest(r)
1161 c.doChunkReadStats(int64(len(msg.Piece)))
1162 err = c.receiveChunk(&msg)
1163 if len(msg.Piece) == int(t.chunkSize) {
1164 t.chunkPool.Put(&msg.Piece)
1167 err = fmt.Errorf("receiving chunk: %w", err)
1170 req := newRequestFromMessage(&msg)
1171 c.onPeerSentCancel(req)
1173 ipa, ok := tryIpPortFromNetAddr(c.RemoteAddr)
1177 pingAddr := net.UDPAddr{
1182 pingAddr.Port = int(msg.Port)
1184 cl.eachDhtServer(func(s DhtServer) {
1185 go s.Ping(&pingAddr)
1188 torrent.Add("suggests received", 1)
1189 log.Fmsg("peer suggested piece %d", msg.Index).AddValues(c, msg.Index).SetLevel(log.Debug).Log(c.t.logger)
1190 c.updateRequests("suggested")
1192 err = c.onPeerSentHaveAll()
1194 err = c.peerSentHaveNone()
1196 c.remoteRejectedRequest(c.t.requestIndexFromRequest(newRequestFromMessage(&msg)))
1197 case pp.AllowedFast:
1198 torrent.Add("allowed fasts received", 1)
1199 log.Fmsg("peer allowed fast: %d", msg.Index).AddValues(c).SetLevel(log.Debug).Log(c.t.logger)
1200 c.updateRequests("PeerConn.mainReadLoop allowed fast")
1202 err = c.onReadExtendedMsg(msg.ExtendedID, msg.ExtendedPayload)
1204 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1212 func (c *Peer) remoteRejectedRequest(r RequestIndex) {
1213 if c.deleteRequest(r) {
1214 if c.isLowOnRequests() {
1215 c.updateRequests("Peer.remoteRejectedRequest")
1217 c.decExpectedChunkReceive(r)
1221 func (c *Peer) decExpectedChunkReceive(r RequestIndex) {
1222 count := c.validReceiveChunks[r]
1224 delete(c.validReceiveChunks, r)
1225 } else if count > 1 {
1226 c.validReceiveChunks[r] = count - 1
1232 func (c *PeerConn) onReadExtendedMsg(id pp.ExtensionNumber, payload []byte) (err error) {
1234 // TODO: Should we still do this?
1236 // These clients use their own extension IDs for outgoing message
1237 // types, which is incorrect.
1238 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) || strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1246 case pp.HandshakeExtendedID:
1247 var d pp.ExtendedHandshakeMessage
1248 if err := bencode.Unmarshal(payload, &d); err != nil {
1249 c.logger.Printf("error parsing extended handshake message %q: %s", payload, err)
1250 return fmt.Errorf("unmarshalling extended handshake payload: %w", err)
1252 if cb := c.callbacks.ReadExtendedHandshake; cb != nil {
1255 // c.logger.WithDefaultLevel(log.Debug).Printf("received extended handshake message:\n%s", spew.Sdump(d))
1257 c.PeerMaxRequests = d.Reqq
1259 c.PeerClientName.Store(d.V)
1260 if c.PeerExtensionIDs == nil {
1261 c.PeerExtensionIDs = make(map[pp.ExtensionName]pp.ExtensionNumber, len(d.M))
1263 c.PeerListenPort = d.Port
1264 c.PeerPrefersEncryption = d.Encryption
1265 for name, id := range d.M {
1266 if _, ok := c.PeerExtensionIDs[name]; !ok {
1267 peersSupportingExtension.Add(
1268 // expvar.Var.String must produce valid JSON. "ut_payme\xeet_address" was being
1269 // entered here which caused problems later when unmarshalling.
1270 strconv.Quote(string(name)),
1273 c.PeerExtensionIDs[name] = id
1275 if d.MetadataSize != 0 {
1276 if err = t.setMetadataSize(d.MetadataSize); err != nil {
1277 return fmt.Errorf("setting metadata size to %d: %w", d.MetadataSize, err)
1280 c.requestPendingMetadata()
1281 if !t.cl.config.DisablePEX {
1282 t.pex.Add(c) // we learnt enough now
1286 case metadataExtendedId:
1287 err := cl.gotMetadataExtensionMsg(payload, t, c)
1289 return fmt.Errorf("handling metadata extension message: %w", err)
1293 if !c.pex.IsEnabled() {
1294 return nil // or hang-up maybe?
1296 return c.pex.Recv(payload)
1298 return fmt.Errorf("unexpected extended message ID: %v", id)
1302 // Set both the Reader and Writer for the connection from a single ReadWriter.
1303 func (cn *PeerConn) setRW(rw io.ReadWriter) {
1308 // Returns the Reader and Writer as a combined ReadWriter.
1309 func (cn *PeerConn) rw() io.ReadWriter {
1316 func (c *Peer) doChunkReadStats(size int64) {
1317 c.allStats(func(cs *ConnStats) { cs.receivedChunk(size) })
1320 // Handle a received chunk from a peer.
1321 func (c *Peer) receiveChunk(msg *pp.Message) error {
1322 chunksReceived.Add("total", 1)
1324 ppReq := newRequestFromMessage(msg)
1325 req := c.t.requestIndexFromRequest(ppReq)
1328 chunksReceived.Add("while choked", 1)
1331 if c.validReceiveChunks[req] <= 0 {
1332 chunksReceived.Add("unexpected", 1)
1333 return errors.New("received unexpected chunk")
1335 c.decExpectedChunkReceive(req)
1337 if c.peerChoking && c.peerAllowedFast.Contains(bitmap.BitIndex(ppReq.Index)) {
1338 chunksReceived.Add("due to allowed fast", 1)
1341 // The request needs to be deleted immediately to prevent cancels occurring asynchronously when
1342 // have actually already received the piece, while we have the Client unlocked to write the data
1344 deletedRequest := false
1346 if c.actualRequestState.Requests.Contains(req) {
1347 for _, f := range c.callbacks.ReceivedRequested {
1348 f(PeerMessageEvent{c, msg})
1351 // Request has been satisfied.
1352 if c.deleteRequest(req) {
1353 deletedRequest = true
1355 c._chunksReceivedWhileExpecting++
1357 if c.isLowOnRequests() {
1358 c.updateRequests("Peer.receiveChunk deleted request")
1361 chunksReceived.Add("unwanted", 1)
1368 // Do we actually want this chunk?
1369 if t.haveChunk(ppReq) {
1370 // panic(fmt.Sprintf("%+v", ppReq))
1371 chunksReceived.Add("wasted", 1)
1372 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadWasted }))
1376 piece := &t.pieces[ppReq.Index]
1378 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.ChunksReadUseful }))
1379 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulData }))
1381 c.piecesReceivedSinceLastRequestUpdate++
1382 c.allStats(add(int64(len(msg.Piece)), func(cs *ConnStats) *Count { return &cs.BytesReadUsefulIntendedData }))
1384 for _, f := range c.t.cl.config.Callbacks.ReceivedUsefulData {
1385 f(ReceivedUsefulDataEvent{c, msg})
1387 c.lastUsefulChunkReceived = time.Now()
1389 // Need to record that it hasn't been written yet, before we attempt to do
1390 // anything with it.
1391 piece.incrementPendingWrites()
1392 // Record that we have the chunk, so we aren't trying to download it while
1393 // waiting for it to be written to storage.
1394 piece.unpendChunkIndex(chunkIndexFromChunkSpec(ppReq.ChunkSpec, t.chunkSize))
1396 // Cancel pending requests for this chunk from *other* peers.
1397 t.iterPeers(func(p *Peer) {
1404 err := func() error {
1407 concurrentChunkWrites.Add(1)
1408 defer concurrentChunkWrites.Add(-1)
1409 // Write the chunk out. Note that the upper bound on chunk writing concurrency will be the
1410 // number of connections. We write inline with receiving the chunk (with this lock dance),
1411 // because we want to handle errors synchronously and I haven't thought of a nice way to
1412 // defer any concurrency to the storage and have that notify the client of errors. TODO: Do
1414 return t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1417 piece.decrementPendingWrites()
1420 c.logger.WithDefaultLevel(log.Error).Printf("writing received chunk %v: %v", req, err)
1422 // Necessary to pass TestReceiveChunkStorageFailureSeederFastExtensionDisabled. I think a
1423 // request update runs while we're writing the chunk that just failed. Then we never do a
1424 // fresh update after pending the failed request.
1425 c.updateRequests("Peer.receiveChunk error writing chunk")
1426 t.onWriteChunkErr(err)
1430 c.onDirtiedPiece(pieceIndex(ppReq.Index))
1432 // We need to ensure the piece is only queued once, so only the last chunk writer gets this job.
1433 if t.pieceAllDirty(pieceIndex(ppReq.Index)) && piece.pendingWrites == 0 {
1434 t.queuePieceCheck(pieceIndex(ppReq.Index))
1435 // We don't pend all chunks here anymore because we don't want code dependent on the dirty
1436 // chunk status (such as the haveChunk call above) to have to check all the various other
1437 // piece states like queued for hash, hashing etc. This does mean that we need to be sure
1438 // that chunk pieces are pended at an appropriate time later however.
1441 cl.event.Broadcast()
1442 // We do this because we've written a chunk, and may change PieceState.Partial.
1443 t.publishPieceChange(pieceIndex(ppReq.Index))
1448 func (c *Peer) onDirtiedPiece(piece pieceIndex) {
1449 if c.peerTouchedPieces == nil {
1450 c.peerTouchedPieces = make(map[pieceIndex]struct{})
1452 c.peerTouchedPieces[piece] = struct{}{}
1453 ds := &c.t.pieces[piece].dirtiers
1455 *ds = make(map[*Peer]struct{})
1457 (*ds)[c] = struct{}{}
1460 func (c *PeerConn) uploadAllowed() bool {
1461 if c.t.cl.config.NoUpload {
1464 if c.t.dataUploadDisallowed {
1470 if !c.peerHasWantedPieces() {
1473 // Don't upload more than 100 KiB more than we download.
1474 if c._stats.BytesWrittenData.Int64() >= c._stats.BytesReadData.Int64()+100<<10 {
1480 func (c *PeerConn) setRetryUploadTimer(delay time.Duration) {
1481 if c.uploadTimer == nil {
1482 c.uploadTimer = time.AfterFunc(delay, c.tickleWriter)
1484 c.uploadTimer.Reset(delay)
1488 // Also handles choking and unchoking of the remote peer.
1489 func (c *PeerConn) upload(msg func(pp.Message) bool) bool {
1490 // Breaking or completing this loop means we don't want to upload to the
1491 // peer anymore, and we choke them.
1493 for c.uploadAllowed() {
1494 // We want to upload to the peer.
1495 if !c.unchoke(msg) {
1498 for r, state := range c.peerRequests {
1499 if state.data == nil {
1502 res := c.t.cl.config.UploadRateLimiter.ReserveN(time.Now(), int(r.Length))
1504 panic(fmt.Sprintf("upload rate limiter burst size < %d", r.Length))
1506 delay := res.Delay()
1509 c.setRetryUploadTimer(delay)
1510 // Hard to say what to return here.
1513 more := c.sendChunk(r, msg, state)
1514 delete(c.peerRequests, r)
1525 func (cn *PeerConn) drop() {
1526 cn.t.dropConnection(cn)
1529 func (cn *Peer) netGoodPiecesDirtied() int64 {
1530 return cn._stats.PiecesDirtiedGood.Int64() - cn._stats.PiecesDirtiedBad.Int64()
1533 func (c *Peer) peerHasWantedPieces() bool {
1534 if all, _ := c.peerHasAllPieces(); all {
1535 return !c.t.haveAllPieces() && !c.t._pendingPieces.IsEmpty()
1537 if !c.t.haveInfo() {
1538 return !c.peerPieces().IsEmpty()
1540 return c.peerPieces().Intersects(&c.t._pendingPieces)
1543 func (c *Peer) deleteRequest(r RequestIndex) bool {
1544 if !c.actualRequestState.Requests.CheckedRemove(r) {
1547 c.cancelledRequests.Remove(r)
1548 for _, f := range c.callbacks.DeletedRequest {
1549 f(PeerRequestEvent{c, c.t.requestIndexToRequest(r)})
1551 c.updateExpectingChunks()
1552 c.t.pendingRequests.Dec(r)
1556 func (c *Peer) deleteAllRequests() {
1557 c.actualRequestState.Requests.Clone().Iterate(func(x uint32) bool {
1561 if !c.actualRequestState.Requests.IsEmpty() {
1562 panic(c.actualRequestState.Requests.GetCardinality())
1566 // This is called when something has changed that should wake the writer, such as putting stuff into
1567 // the writeBuffer, or changing some state that the writer can act on.
1568 func (c *PeerConn) tickleWriter() {
1569 c.messageWriter.writeCond.Broadcast()
1572 func (c *PeerConn) sendChunk(r Request, msg func(pp.Message) bool, state *peerRequestState) (more bool) {
1573 c.lastChunkSent = time.Now()
1574 return msg(pp.Message{
1582 func (c *PeerConn) setTorrent(t *Torrent) {
1584 panic("connection already associated with a torrent")
1587 c.logger.WithDefaultLevel(log.Debug).Printf("set torrent=%v", t)
1588 t.reconcileHandshakeStats(c)
1591 func (c *Peer) peerPriority() (peerPriority, error) {
1592 return bep40Priority(c.remoteIpPort(), c.t.cl.publicAddr(c.remoteIp()))
1595 func (c *Peer) remoteIp() net.IP {
1596 host, _, _ := net.SplitHostPort(c.RemoteAddr.String())
1597 return net.ParseIP(host)
1600 func (c *Peer) remoteIpPort() IpPort {
1601 ipa, _ := tryIpPortFromNetAddr(c.RemoteAddr)
1602 return IpPort{ipa.IP, uint16(ipa.Port)}
1605 func (c *PeerConn) pexPeerFlags() pp.PexPeerFlags {
1606 f := pp.PexPeerFlags(0)
1607 if c.PeerPrefersEncryption {
1608 f |= pp.PexPrefersEncryption
1611 f |= pp.PexOutgoingConn
1614 f |= pp.PexSupportsUtp
1619 // This returns the address to use if we want to dial the peer again. It incorporates the peer's
1620 // advertised listen port.
1621 func (c *PeerConn) dialAddr() PeerRemoteAddr {
1622 if !c.outgoing && c.PeerListenPort != 0 {
1623 switch addr := c.RemoteAddr.(type) {
1626 dialAddr.Port = c.PeerListenPort
1630 dialAddr.Port = c.PeerListenPort
1637 func (c *PeerConn) pexEvent(t pexEventType) pexEvent {
1638 f := c.pexPeerFlags()
1639 addr := c.dialAddr()
1640 return pexEvent{t, addr, f, nil}
1643 func (c *PeerConn) String() string {
1644 return fmt.Sprintf("%T %p [id=%q, exts=%v, v=%q]", c, c, c.PeerID, c.PeerExtensionBytes, c.PeerClientName.Load())
1647 func (c *Peer) trust() connectionTrust {
1648 return connectionTrust{c.trusted, c.netGoodPiecesDirtied()}
1651 type connectionTrust struct {
1653 NetGoodPiecesDirted int64
1656 func (l connectionTrust) Less(r connectionTrust) bool {
1657 return multiless.New().Bool(l.Implicit, r.Implicit).Int64(l.NetGoodPiecesDirted, r.NetGoodPiecesDirted).Less()
1660 // Returns the pieces the peer could have based on their claims. If we don't know how many pieces
1661 // are in the torrent, it could be a very large range the peer has sent HaveAll.
1662 func (cn *PeerConn) PeerPieces() *roaring.Bitmap {
1664 defer cn.locker().RUnlock()
1665 return cn.newPeerPieces()
1668 // Returns a new Bitmap that includes bits for all pieces the peer could have based on their claims.
1669 func (cn *Peer) newPeerPieces() *roaring.Bitmap {
1670 // TODO: Can we use copy on write?
1671 ret := cn.peerPieces().Clone()
1672 if all, _ := cn.peerHasAllPieces(); all {
1673 if cn.t.haveInfo() {
1674 ret.AddRange(0, bitmap.BitRange(cn.t.numPieces()))
1676 ret.AddRange(0, bitmap.ToEnd)
1682 func (cn *Peer) stats() *ConnStats {
1686 func (p *Peer) TryAsPeerConn() (*PeerConn, bool) {
1687 pc, ok := p.peerImpl.(*PeerConn)
1691 func (pc *PeerConn) isLowOnRequests() bool {
1692 return pc.actualRequestState.Requests.IsEmpty()
1695 func (pc *PeerConn) remoteIsTransmission() bool {
1696 return bytes.HasPrefix(pc.PeerID[:], []byte("-TR")) && pc.PeerID[7] == '-'