9 "github.com/anacrolix/torrent/metainfo"
10 pp "github.com/anacrolix/torrent/peer_protocol"
14 pieceHash = crypto.SHA1
15 maxRequests = 250 // Maximum pending requests we allow peers to send us.
16 defaultChunkSize = 0x4000 // 16KiB
17 // Peer ID client identifier prefix. We'll update this occasionally to
18 // reflect changes to client behaviour that other clients may depend on.
19 // Also see `extendedHandshakeClientVersion`.
21 nominalDialTimeout = time.Second * 30
22 minDialTimeout = 5 * time.Second
30 func (ih InfoHash) AsString() string {
34 func (ih InfoHash) HexString() string {
35 return fmt.Sprintf("%x", ih[:])
38 func lastChunkSpec(pieceLength, chunkSize pp.Integer) (cs chunkSpec) {
39 cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
40 cs.Length = pieceLength - cs.Begin
44 type chunkSpec struct {
45 Begin, Length pp.Integer
53 func newRequest(index, begin, length pp.Integer) request {
54 return request{index, chunkSpec{begin, length}}
58 // Requested data not yet available.
59 errDataNotReady = errors.New("data not ready")
62 // The size in bytes of a metadata extension piece.
63 func metadataPieceSize(totalSize int, piece int) int {
64 ret := totalSize - piece*(1<<14)
71 type superer interface {
75 // Returns ok if there's a parent, and it's not nil.
76 func super(child interface{}) (parent interface{}, ok bool) {
77 s, ok := child.(superer)
86 // Return the request that would include the given offset into the torrent data.
87 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
89 if offset < 0 || offset >= torrentLength {
92 r.Index = pp.Integer(offset / pieceSize)
93 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
94 r.Length = pp.Integer(chunkSize)
95 pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
96 if r.Length > pieceLeft {
99 torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
100 if int64(r.Length) > torrentLeft {
101 r.Length = pp.Integer(torrentLeft)
107 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
108 off = int64(r.Index)*pieceSize + int64(r.Begin)
109 if off < 0 || off >= torrentLength {
110 panic("invalid request")
115 func validateInfo(info *metainfo.Info) error {
116 if len(info.Pieces)%20 != 0 {
117 return errors.New("pieces has invalid length")
119 if int((info.TotalLength()+info.PieceLength-1)/info.PieceLength) != info.NumPieces() {
120 return errors.New("piece count and file lengths are at odds")