8 "github.com/anacrolix/torrent/metainfo"
9 pp "github.com/anacrolix/torrent/peer_protocol"
13 pieceHash = crypto.SHA1
14 maxRequests = 250 // Maximum pending requests we allow peers to send us.
15 defaultChunkSize = 0x4000 // 16KiB
16 // Peer ID client identifier prefix. We'll update this occasionally to
17 // reflect changes to client behaviour that other clients may depend on.
18 // Also see `extendedHandshakeClientVersion`.
20 nominalDialTimeout = time.Second * 30
21 minDialTimeout = 5 * time.Second
24 type chunkSpec struct {
25 Begin, Length pp.Integer
33 func newRequest(index, begin, length pp.Integer) request {
34 return request{index, chunkSpec{begin, length}}
37 // The size in bytes of a metadata extension piece.
38 func metadataPieceSize(totalSize int, piece int) int {
39 ret := totalSize - piece*(1<<14)
46 // Return the request that would include the given offset into the torrent data.
47 func torrentOffsetRequest(torrentLength, pieceSize, chunkSize, offset int64) (
49 if offset < 0 || offset >= torrentLength {
52 r.Index = pp.Integer(offset / pieceSize)
53 r.Begin = pp.Integer(offset % pieceSize / chunkSize * chunkSize)
54 r.Length = pp.Integer(chunkSize)
55 pieceLeft := pp.Integer(pieceSize - int64(r.Begin))
56 if r.Length > pieceLeft {
59 torrentLeft := torrentLength - int64(r.Index)*pieceSize - int64(r.Begin)
60 if int64(r.Length) > torrentLeft {
61 r.Length = pp.Integer(torrentLeft)
67 func torrentRequestOffset(torrentLength, pieceSize int64, r request) (off int64) {
68 off = int64(r.Index)*pieceSize + int64(r.Begin)
69 if off < 0 || off >= torrentLength {
70 panic("invalid request")
75 func validateInfo(info *metainfo.Info) error {
76 if len(info.Pieces)%20 != 0 {
77 return errors.New("pieces has invalid length")
79 if int((info.TotalLength()+info.PieceLength-1)/info.PieceLength) != info.NumPieces() {
80 return errors.New("piece count and file lengths are at odds")
85 func chunkIndexSpec(index int, pieceLength, chunkSize pp.Integer) chunkSpec {
86 ret := chunkSpec{pp.Integer(index) * chunkSize, chunkSize}
87 if ret.Begin+ret.Length > pieceLength {
88 ret.Length = pieceLength - ret.Begin