From 0e781be17713086f211c69005852be1918b834a4 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Tue, 27 Feb 2024 23:30:53 +1100 Subject: [PATCH] Get infohash selection working when adding v2 torrents --- spec.go | 7 ++++++- torrent.go | 9 ++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/spec.go b/spec.go index f1ef584e..29d30adc 100644 --- a/spec.go +++ b/spec.go @@ -69,13 +69,18 @@ func TorrentSpecFromMetaInfoErr(mi *metainfo.MetaInfo) (*TorrentSpec, error) { if err != nil { err = fmt.Errorf("unmarshalling info: %w", err) } + v1Ih := mi.HashInfoBytes() var v2Infohash g.Option[infohash_v2.T] if info.HasV2() { v2Infohash.Set(infohash_v2.HashBytes(mi.InfoBytes)) + if !info.HasV1() { + v1Ih = v2Infohash.Value.ToShort() + } } + return &TorrentSpec{ Trackers: mi.UpvertedAnnounceList(), - InfoHash: mi.HashInfoBytes(), + InfoHash: v1Ih, InfoHashV2: v2Infohash, PieceLayers: mi.PieceLayers, InfoBytes: mi.InfoBytes, diff --git a/torrent.go b/torrent.go index e2afb3e3..8416e4ba 100644 --- a/torrent.go +++ b/torrent.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "github.com/anacrolix/torrent/merkle" + "github.com/anacrolix/torrent/types/infohash" infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2" "io" "math/rand" @@ -538,13 +539,19 @@ func (t *Torrent) onSetInfo() { // Called when metadata for a torrent becomes available. func (t *Torrent) setInfoBytesLocked(b []byte) error { - if metainfo.HashBytes(b) != t.infoHash { + v2Hash := infohash_v2.HashBytes(b) + v1Hash := infohash.HashBytes(b) + v2Short := v2Hash.ToShort() + if v2Short != t.infoHash && v1Hash != t.infoHash { return errors.New("info bytes have wrong hash") } var info metainfo.Info if err := bencode.Unmarshal(b, &info); err != nil { return fmt.Errorf("error unmarshalling info bytes: %s", err) } + if info.HasV2() { + t.infoHashV2.Set(v2Hash) + } t.metadataBytes = b t.metadataCompletedChunks = nil if t.info != nil { -- 2.44.0