aboutsummaryrefslogtreecommitdiff
path: root/cmd/mybittorrent/meta.go
diff options
context:
space:
mode:
authorjet2tlf <jet2tlf@gmail.com>2024-06-03 17:54:41 +0000
committerjet2tlf <jet2tlf@gmail.com>2024-06-03 17:54:41 +0000
commit944cfe99f03034c37b2d963f7048c41c56f21b9f (patch)
treeb35fe96dedc9efe821cd2ef0f8f902e28c5b42ef /cmd/mybittorrent/meta.go
parentb01c839940e6ea22ddc28aa0c975d3cd3da69e72 (diff)
downloadbittorrent-go-944cfe99f03034c37b2d963f7048c41c56f21b9f.tar.gz
bittorrent-go-944cfe99f03034c37b2d963f7048c41c56f21b9f.zip
codecrafters submit [skip ci]
Diffstat (limited to 'cmd/mybittorrent/meta.go')
-rw-r--r--cmd/mybittorrent/meta.go37
1 files changed, 37 insertions, 0 deletions
diff --git a/cmd/mybittorrent/meta.go b/cmd/mybittorrent/meta.go
new file mode 100644
index 0000000..34369c4
--- /dev/null
+++ b/cmd/mybittorrent/meta.go
@@ -0,0 +1,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
+}