-
Notifications
You must be signed in to change notification settings - Fork 4
/
verifier.go
57 lines (44 loc) · 1.12 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
package filechecksum
import (
"bytes"
"hash"
)
type ChecksumLookup interface {
GetStrongChecksumForBlock(blockID int) []byte
}
type HashVerifier struct {
BlockSize uint
Hash hash.Hash
BlockChecksumGetter ChecksumLookup
FinalChunkLen uint
}
func (v *HashVerifier) VerifyBlockRange(startBlockID uint, data []byte) bool {
for i := 0; i*int(v.BlockSize) < len(data); i++ {
start := i * int(v.BlockSize)
end := start + int(v.BlockSize)
if end > len(data) {
end = len(data)
}
blockData := data[start:end]
expectedChecksum := v.BlockChecksumGetter.GetStrongChecksumForBlock(
int(startBlockID) + i,
)
if expectedChecksum == nil {
return true
}
if len(blockData) < int(v.BlockSize) {
zeroFilledBlock := make([]byte, v.BlockSize-uint(len(blockData)))
blockData = append(blockData, zeroFilledBlock...)
}
v.Hash.Write(blockData)
hashedData := v.Hash.Sum(nil)
if len(hashedData) > int(v.FinalChunkLen) {
hashedData = hashedData[:v.FinalChunkLen]
}
if bytes.Compare(expectedChecksum, hashedData) != 0 {
return false
}
v.Hash.Reset()
}
return true
}