github.com/anacrolix/torrent@v1.61.0/dht.go (about)

     1  package torrent
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net"
     7  
     8  	"github.com/anacrolix/dht/v2"
     9  	"github.com/anacrolix/dht/v2/krpc"
    10  	peer_store "github.com/anacrolix/dht/v2/peer-store"
    11  	"github.com/davecgh/go-spew/spew"
    12  )
    13  
    14  // DHT server interface for use by a Torrent or Client. It's reasonable for this to make assumptions
    15  // for torrent-use that might not be the default behaviour for the DHT server.
    16  type DhtServer interface {
    17  	Stats() interface{}
    18  	ID() [20]byte
    19  	Addr() net.Addr
    20  	AddNode(ni krpc.NodeInfo) error
    21  	// This is called asynchronously when receiving PORT messages.
    22  	Ping(addr *net.UDPAddr)
    23  	Announce(hash [20]byte, port int, impliedPort bool) (DhtAnnounce, error)
    24  	WriteStatus(io.Writer)
    25  }
    26  
    27  // Optional interface for DhtServer's that can expose their peer store (if any).
    28  type PeerStorer interface {
    29  	PeerStore() peer_store.Interface
    30  }
    31  
    32  type DhtAnnounce interface {
    33  	Close()
    34  	Peers() <-chan dht.PeersValues
    35  }
    36  
    37  type AnacrolixDhtServerWrapper struct {
    38  	*dht.Server
    39  }
    40  
    41  func (me AnacrolixDhtServerWrapper) Stats() interface{} {
    42  	return me.Server.Stats()
    43  }
    44  
    45  type anacrolixDhtAnnounceWrapper struct {
    46  	*dht.Announce
    47  }
    48  
    49  func (me anacrolixDhtAnnounceWrapper) Peers() <-chan dht.PeersValues {
    50  	return me.Announce.Peers
    51  }
    52  
    53  func (me AnacrolixDhtServerWrapper) Announce(hash [20]byte, port int, impliedPort bool) (DhtAnnounce, error) {
    54  	ann, err := me.Server.Announce(hash, port, impliedPort)
    55  	return anacrolixDhtAnnounceWrapper{ann}, err
    56  }
    57  
    58  func (me AnacrolixDhtServerWrapper) Ping(addr *net.UDPAddr) {
    59  	me.Server.PingQueryInput(addr, dht.QueryInput{
    60  		RateLimiting: dht.QueryRateLimiting{NoWaitFirst: true},
    61  	})
    62  }
    63  
    64  var _ DhtServer = AnacrolixDhtServerWrapper{}
    65  
    66  func writeDhtServerStatus(w io.Writer, s DhtServer) {
    67  	dhtStats := s.Stats()
    68  	fmt.Fprintf(w, " ID: %x\n", s.ID())
    69  	spew.Fdump(w, dhtStats)
    70  }