]> Sergey Matveev's repositories - btrtrc.git/blobdiff - piece.go
cmd/btrtrc client
[btrtrc.git] / piece.go
index 607e2f883f475f4b8db5abf16a8c314591d23693..074f6601cd33e3c7642574634e9b9fe096da9637 100644 (file)
--- a/piece.go
+++ b/piece.go
@@ -1,6 +1,8 @@
 package torrent
 
 import (
+       "context"
+       "errors"
        "fmt"
        "sync"
 
@@ -8,30 +10,35 @@ import (
        g "github.com/anacrolix/generics"
        "github.com/anacrolix/missinggo/v2/bitmap"
 
+       "github.com/anacrolix/torrent/merkle"
        "github.com/anacrolix/torrent/metainfo"
        pp "github.com/anacrolix/torrent/peer_protocol"
        "github.com/anacrolix/torrent/storage"
-       infohash_v2 "github.com/anacrolix/torrent/types/infohash-v2"
 )
 
+// Why is it an int64?
+type pieceVerifyCount = int64
+
 type Piece struct {
        // The completed piece SHA1 hash, from the metainfo "pieces" field. Nil if the info is not V1
        // compatible.
        hash   *metainfo.Hash
-       hashV2 g.Option[infohash_v2.T]
+       hashV2 g.Option[[32]byte]
        t      *Torrent
        index  pieceIndex
        files  []*File
 
        readerCond chansync.BroadcastCond
 
-       numVerifies         int64
-       hashing             bool
+       numVerifies     pieceVerifyCount
+       numVerifiesCond chansync.BroadcastCond
+       hashing         bool
+       // The piece state may have changed, and is being synchronized with storage.
        marking             bool
        storageCompletionOk bool
 
        publicPieceState PieceState
-       priority         piecePriority
+       priority         PiecePriority
        // Availability adjustment for this piece relative to len(Torrent.connsWithAllPieces). This is
        // incremented for any piece a peer has when a peer has a piece, Torrent.haveInfo is true, and
        // the Peer isn't recorded in Torrent.connsWithAllPieces.
@@ -52,11 +59,19 @@ func (p *Piece) String() string {
 }
 
 func (p *Piece) Info() metainfo.Piece {
-       return p.t.info.Piece(int(p.index))
+       return p.t.info.Piece(p.index)
 }
 
 func (p *Piece) Storage() storage.Piece {
-       return p.t.storage.Piece(p.Info())
+       var pieceHash g.Option[[]byte]
+       if p.hash != nil {
+               pieceHash.Set(p.hash.Bytes())
+       } else if !p.hasPieceLayer() {
+               pieceHash.Set(p.mustGetOnlyFile().piecesRoot.UnwrapPtr()[:])
+       } else if p.hashV2.Ok {
+               pieceHash.Set(p.hashV2.Value[:])
+       }
+       return p.t.storage.PieceWithHash(p.Info(), pieceHash)
 }
 
 func (p *Piece) Flush() {
@@ -168,23 +183,40 @@ func (p *Piece) bytesLeft() (ret pp.Integer) {
 }
 
 // Forces the piece data to be rehashed.
-func (p *Piece) VerifyData() {
-       p.t.cl.lock()
-       defer p.t.cl.unlock()
-       target := p.numVerifies + 1
-       if p.hashing {
-               target++
+func (p *Piece) VerifyData() error {
+       return p.VerifyDataContext(context.Background())
+}
+
+// Forces the piece data to be rehashed. This might be a temporary method until
+// an event-based one is created. Possibly this blocking style is more suited to
+// external control of hashing concurrency.
+func (p *Piece) VerifyDataContext(ctx context.Context) error {
+       locker := p.t.cl.locker()
+       locker.Lock()
+       target, err := p.t.queuePieceCheck(p.index)
+       locker.Unlock()
+       if err != nil {
+               return err
        }
-       // log.Printf("target: %d", target)
-       p.t.queuePieceCheck(p.index)
+       //log.Printf("target: %d", target)
        for {
-               // log.Printf("got %d verifies", p.numVerifies)
-               if p.numVerifies >= target {
-                       break
+               locker.RLock()
+               done := p.numVerifies >= target
+               //log.Printf("got %d verifies", p.numVerifies)
+               numVerifiesChanged := p.numVerifiesCond.Signaled()
+               locker.RUnlock()
+               if done {
+                       //log.Print("done")
+                       return nil
+               }
+               select {
+               case <-ctx.Done():
+                       return ctx.Err()
+               case <-p.t.closed.Done():
+                       return errTorrentClosed
+               case <-numVerifiesChanged:
                }
-               p.t.cl.event.Wait()
        }
-       // log.Print("done")
 }
 
 func (p *Piece) queuedForHash() bool {
@@ -199,14 +231,15 @@ func (p *Piece) torrentEndOffset() int64 {
        return p.torrentBeginOffset() + int64(p.t.usualPieceSize())
 }
 
-func (p *Piece) SetPriority(prio piecePriority) {
+func (p *Piece) SetPriority(prio PiecePriority) {
        p.t.cl.lock()
        defer p.t.cl.unlock()
        p.priority = prio
        p.t.updatePiecePriority(p.index, "Piece.SetPriority")
 }
 
-func (p *Piece) purePriority() (ret piecePriority) {
+// This is priority based only on piece, file and reader priorities.
+func (p *Piece) purePriority() (ret PiecePriority) {
        for _, f := range p.files {
                ret.Raise(f.prio)
        }
@@ -223,15 +256,22 @@ func (p *Piece) purePriority() (ret piecePriority) {
        return
 }
 
-func (p *Piece) uncachedPriority() (ret piecePriority) {
-       if p.hashing || p.marking || p.t.pieceComplete(p.index) || p.queuedForHash() {
+func (p *Piece) ignoreForRequests() bool {
+       return p.hashing || p.marking || !p.haveHash() || p.t.pieceComplete(p.index) || p.queuedForHash()
+}
+
+// This is the priority adjusted for piece state like completion, hashing etc.
+func (p *Piece) effectivePriority() (ret PiecePriority) {
+       if p.ignoreForRequests() {
                return PiecePriorityNone
        }
        return p.purePriority()
 }
 
 // Tells the Client to refetch the completion status from storage, updating priority etc. if
-// necessary. Might be useful if you know the state of the piece data has changed externally.
+// necessary. Might be useful if you know the state of the piece data has
+// changed externally. TODO: Document why this is public, maybe change name to
+// SyncCompletion or something.
 func (p *Piece) UpdateCompletion() {
        p.t.cl.lock()
        defer p.t.cl.unlock()
@@ -268,3 +308,54 @@ func (p *Piece) mustGetOnlyFile() *File {
        }
        return p.files[0]
 }
+
+// Sets the v2 piece hash, queuing initial piece checks if appropriate.
+func (p *Piece) setV2Hash(v2h [32]byte) {
+       // See Torrent.onSetInfo. We want to trigger an initial check if appropriate, if we didn't yet
+       // have a piece hash (can occur with v2 when we don't start with piece layers).
+       p.t.storageLock.Lock()
+       oldV2Hash := p.hashV2.Set(v2h)
+       p.t.storageLock.Unlock()
+       if !oldV2Hash.Ok && p.hash == nil {
+               p.t.updatePieceCompletion(p.index)
+               p.t.queueInitialPieceCheck(p.index)
+       }
+}
+
+// Can't do certain things if we don't know the piece hash.
+func (p *Piece) haveHash() bool {
+       if p.hash != nil {
+               return true
+       }
+       if !p.hasPieceLayer() {
+               return true
+       }
+       return p.hashV2.Ok
+}
+
+func (p *Piece) hasPieceLayer() bool {
+       return len(p.files) == 1 && p.files[0].length > p.t.info.PieceLength
+}
+
+func (p *Piece) obtainHashV2() (hash [32]byte, err error) {
+       if p.hashV2.Ok {
+               hash = p.hashV2.Value
+               return
+       }
+       if !p.hasPieceLayer() {
+               hash = p.mustGetOnlyFile().piecesRoot.Unwrap()
+               return
+       }
+       storage := p.Storage()
+       if !storage.Completion().Complete {
+               err = errors.New("piece incomplete")
+               return
+       }
+
+       h := merkle.NewHash()
+       if _, err = storage.WriteTo(h); err != nil {
+               return
+       }
+       h.SumMinLength(hash[:0], int(p.t.info.PieceLength))
+       return
+}