aboutsummaryrefslogtreecommitdiff
path: root/commitgraph/read/hash.go
blob: e9543eac36bc58680ad171099e55e37e0fb424c2 (about) (plain) (blame)
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
package read

import (
	"bytes"
	"fmt"
	"io"

	"codeberg.org/lindenii/furgit/objectid"
)

// HashVersion returns the commit-graph hash version.
func (reader *Reader) HashVersion() uint8 {
	return reader.hashVersion
}

func validateChainBaseHashes(algo objectid.Algorithm, chain []string, idx int, graph *layer) error {
	if idx == 0 {
		if len(graph.chunkBaseGraphs) != 0 {
			return &MalformedError{Path: graph.path, Reason: "unexpected BASE chunk in first graph"}
		}

		return nil
	}

	hashSize := algo.Size()

	expectedLen := idx * hashSize
	if len(graph.chunkBaseGraphs) != expectedLen {
		return &MalformedError{
			Path:   graph.path,
			Reason: fmt.Sprintf("BASE chunk length %d does not match expected %d", len(graph.chunkBaseGraphs), expectedLen),
		}
	}

	for i := range idx {
		start := i * hashSize
		end := start + hashSize

		baseHash, err := objectid.FromBytes(algo, graph.chunkBaseGraphs[start:end])
		if err != nil {
			return err
		}

		if baseHash.String() != chain[i] {
			return &MalformedError{
				Path:   graph.path,
				Reason: fmt.Sprintf("BASE chunk mismatch at index %d", i),
			}
		}
	}

	return nil
}

func verifyTrailerHash(data []byte, algo objectid.Algorithm, path string) error {
	hashSize := algo.Size()
	if len(data) < hashSize {
		return &MalformedError{Path: path, Reason: "file too short for trailer"}
	}

	hashImpl, err := algo.New()
	if err != nil {
		return err
	}

	_, err = io.Copy(hashImpl, bytes.NewReader(data[:len(data)-hashSize]))
	if err != nil {
		return err
	}

	got := hashImpl.Sum(nil)

	want := data[len(data)-hashSize:]
	if !bytes.Equal(got, want) {
		return &MalformedError{Path: path, Reason: "trailer hash mismatch"}
	}

	return nil
}