-
Notifications
You must be signed in to change notification settings - Fork 75
/
verifier.go
71 lines (61 loc) · 1.27 KB
/
verifier.go
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package verifier
import (
"crypto/sha1"
"github.com/cenkalti/rain/internal/bitfield"
"github.com/cenkalti/rain/internal/piece"
)
// Verifier verifies the pieces on disk.
type Verifier struct {
Bitfield *bitfield.Bitfield
Error error
closeC chan struct{}
doneC chan struct{}
}
// Progress information about the verification.
type Progress struct {
Checked uint32
}
// New returns a new Verifier.
func New() *Verifier {
return &Verifier{
closeC: make(chan struct{}),
doneC: make(chan struct{}),
}
}
// Close the verifier.
func (v *Verifier) Close() {
close(v.closeC)
<-v.doneC
}
// Run and verify all pieces of the torrent.
func (v *Verifier) Run(pieces []piece.Piece, progressC chan Progress, resultC chan *Verifier) {
defer close(v.doneC)
defer func() {
select {
case resultC <- v:
case <-v.closeC:
}
}()
v.Bitfield = bitfield.New(uint32(len(pieces)))
buf := make([]byte, pieces[0].Length)
hash := sha1.New()
var numOK uint32
for _, p := range pieces {
buf = buf[:p.Length]
_, v.Error = p.Data.ReadAt(buf, 0)
if v.Error != nil {
return
}
ok := p.VerifyHash(buf, hash)
if ok {
v.Bitfield.Set(p.Index)
numOK++
}
select {
case progressC <- Progress{Checked: p.Index + 1}:
case <-v.closeC:
return
}
hash.Reset()
}
}