Skip to content

Commit cdd4ce7

Browse files
committed
Merge branch 'simulator'
2 parents 645ae72 + 940a7a2 commit cdd4ce7

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

api/firmware/device_test.go

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import (
4141
"github.com/BitBoxSwiss/bitbox02-api-go/api/firmware/messages"
4242
"github.com/BitBoxSwiss/bitbox02-api-go/api/firmware/mocks"
4343
"github.com/BitBoxSwiss/bitbox02-api-go/communication/u2fhid"
44+
"github.com/BitBoxSwiss/bitbox02-api-go/util/errp"
4445
"github.com/BitBoxSwiss/bitbox02-api-go/util/semver"
4546
"github.com/flynn/noise"
4647
"github.com/stretchr/testify/require"
@@ -109,6 +110,15 @@ func downloadSimulators() ([]string, error) {
109110
return nil, err
110111
}
111112

113+
hashesMatch := func(file *os.File, expectedHash string) (bool, error) {
114+
hasher := sha256.New()
115+
if _, err := io.Copy(hasher, file); err != nil {
116+
return false, err
117+
}
118+
actualHash := hex.EncodeToString(hasher.Sum(nil))
119+
return actualHash == expectedHash, nil
120+
}
121+
112122
fileNotExistOrHashMismatch := func(filename, expectedHash string) (bool, error) {
113123
file, err := os.Open(filename)
114124
if os.IsNotExist(err) {
@@ -119,13 +129,11 @@ func downloadSimulators() ([]string, error) {
119129
}
120130
defer file.Close()
121131

122-
hasher := sha256.New()
123-
if _, err := io.Copy(hasher, file); err != nil {
132+
match, err := hashesMatch(file, expectedHash)
133+
if err != nil {
124134
return false, err
125135
}
126-
actualHash := hex.EncodeToString(hasher.Sum(nil))
127-
128-
return actualHash != expectedHash, nil
136+
return !match, nil
129137
}
130138

131139
downloadFile := func(url, filename string) error {
@@ -164,12 +172,28 @@ func downloadSimulators() ([]string, error) {
164172
return nil, err
165173
}
166174
if doDownload {
175+
fmt.Printf("Downloading %s to %s\n", simulator.URL, filename)
167176
if err := downloadFile(simulator.URL, filename); err != nil {
168177
return nil, err
169178
}
179+
// If we downloaded the file, check again the hash.
180+
file, err := os.Open(filename)
181+
if err != nil {
182+
// This should never happen, as we just downloaded it
183+
return nil, err
184+
}
185+
match, err := hashesMatch(file, simulator.Sha256)
186+
if err != nil {
187+
return nil, err
188+
}
189+
if !match {
190+
return nil, errp.Newf("downloaded file %s does not match expected hash %s", filename, simulator.Sha256)
191+
}
170192
if err := os.Chmod(filename, 0755); err != nil {
171193
return nil, err
172194
}
195+
} else {
196+
fmt.Printf("Skipping download of %s, file already exists and has the correct hash\n", filename)
173197
}
174198
filenames = append(filenames, filename)
175199
}

0 commit comments

Comments
 (0)