]> Sergey Matveev's repositories - btrtrc.git/blobdiff - piece.go
cmd/btrtrc client
[btrtrc.git] / piece.go
index c65ba9a0020407c64e92919f98019708c7f894e3..074f6601cd33e3c7642574634e9b9fe096da9637 100644 (file)
--- a/piece.go
+++ b/piece.go
@@ -1,6 +1,8 @@
 package torrent
 
 import (
+       "context"
+       "errors"
        "fmt"
        "sync"
 
@@ -8,25 +10,30 @@ 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
 
@@ -52,15 +59,17 @@ 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 {
        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.Bytes())
+               pieceHash.Set(p.hashV2.Value[:])
        }
        return p.t.storage.PieceWithHash(p.Info(), pieceHash)
 }
@@ -174,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 {
@@ -243,7 +269,9 @@ func (p *Piece) effectivePriority() (ret PiecePriority) {
 }
 
 // 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()
@@ -285,7 +313,10 @@ func (p *Piece) mustGetOnlyFile() *File {
 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).
-       if !p.hashV2.Set(v2h).Ok && p.hash == nil {
+       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)
        }
@@ -293,9 +324,38 @@ func (p *Piece) setV2Hash(v2h [32]byte) {
 
 // Can't do certain things if we don't know the piece hash.
 func (p *Piece) haveHash() bool {
-       return p.hash != nil || p.hashV2.Ok
+       if p.hash != nil {
+               return true
+       }
+       if !p.hasPieceLayer() {
+               return true
+       }
+       return p.hashV2.Ok
 }
 
-func pieceStateAllowsMessageWrites(p *Piece, pc *PeerConn) bool {
-       return (pc.shouldRequestHashes() && !p.haveHash()) || !p.t.ignorePieceForRequests(p.index)
+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
 }