aboutsummaryrefslogtreecommitdiff
path: root/cmd/mybittorrent/meta.go
blob: 34369c4aa8e53df0ee8d42793f2ebf40dfc84386 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package main

import (
	"crypto/sha1"

	bencode "github.com/jackpal/bencode-go"
)

type Meta struct {
	Announce string   `bencode:"announce"`
	Info     FileInfo `bencode:"info"`
}

type FileInfo struct {
	Length      int    `bencode:"length"`
	Name        string `bencode:"name"`
	PieceLength int    `bencode:"piece length"`
	Pieces      string `bencode:"pieces"`
}

func (m Meta) InfoHash() ([]byte, error) {
	sha := sha1.New()
	if err := bencode.Marshal(sha, m.Info); err != nil {
		return nil, err
	}

	return sha.Sum(nil), nil
}

func (m Meta) PieceHashes() []string {
	hashes := make([]string, 0, len(m.Info.Pieces)/20)
	for i := 0; i < len(m.Info.Pieces); i += 20 {
		hashes = append(hashes, m.Info.Pieces[i:i+20])
	}

	return hashes
}