-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchecksum.go
82 lines (65 loc) · 1.34 KB
/
checksum.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
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"crypto/rand"
"fmt"
"io"
"github.com/minio/highwayhash"
)
const ChecksumBlockSize = 16
// 32 bytes of random hash key
var hashKey []byte
func init() {
hashKey = make([]byte, 32)
rand.Read(hashKey)
h, err := highwayhash.New128(hashKey)
if err != nil {
panic(err)
}
if h.Size() != ChecksumBlockSize {
panic("unexpected block size")
}
}
// updateDB is false if the file being checksummed has not yet been added to the DB
func (t *fileTable) Checksum(r *fileRecord, updateDB bool) error {
if r.HasChecksum {
return nil
}
if r.FailedChecksum != nil {
return r.FailedChecksum
}
t.progress(r.RelPath, false)
f, err := t.options.OpenFile(r.FilePath)
if err != nil {
r.FailedChecksum = err
t.totals.Errors.Add(r)
fmt.Printf("%s: %s\n", r.RelPath, err)
return err
}
defer f.Close()
b, err := hwhChecksum(f)
if err != nil {
r.FailedChecksum = err
t.totals.Errors.Add(r)
fmt.Printf("%s: %s\n", r.RelPath, err)
return err
}
r.Checksum.size = r.Size()
copy(r.Checksum.hash[:], b)
r.HasChecksum = true
if updateDB {
// Update indexes with new checksum
t.db.insert(r)
}
return nil
}
func hwhChecksum(r io.Reader) ([]byte, error) {
h, err := highwayhash.New128(hashKey)
if err != nil {
return nil, err
}
_, err = io.Copy(h, r)
if err != nil {
return nil, err
}
return h.Sum(nil), nil
}