diff --git a/common/helpers.ts b/common/helpers.ts index c21a91c6..78543649 100644 --- a/common/helpers.ts +++ b/common/helpers.ts @@ -1,3 +1,6 @@ +import fs from 'fs'; +import { keccak256 } from 'js-sha3'; + /** * Returns true if and only if the value is null or undefined. * @@ -18,3 +21,12 @@ export function isObject (value: any): boolean { // to confirm it's just an object. return typeof value === 'object' && !Array.isArray(value); } + +/** + * Returns the keccak256 hash of a file. + * + * @param path The path to the file to be hashed. + */ +export function hashFile (path: string): string { + return '0x' + keccak256(fs.readFileSync(path, { encoding: 'binary' })); +} diff --git a/downloader.ts b/downloader.ts index 344ac9b1..a246b195 100755 --- a/downloader.ts +++ b/downloader.ts @@ -1,7 +1,7 @@ import * as fs from 'fs'; import { https } from 'follow-redirects'; import MemoryStream from 'memorystream'; -import { keccak256 } from 'js-sha3'; +import { hashFile } from './common/helpers'; function getVersionList (host: string): Promise { console.log('Retrieving available version list...'); @@ -44,7 +44,7 @@ function downloadBinary (host: string, outputName: string, releaseFile: string, response.pipe(file); file.on('finish', function () { file.close(); - const hash = '0x' + keccak256(fs.readFileSync(outputName, { encoding: 'binary' })); + const hash = hashFile(outputName); if (expectedHash !== hash) { reject(new Error('Hash mismatch: expected ' + expectedHash + ' but got ' + hash)); } else { diff --git a/test/downloader.ts b/test/downloader.ts index 0d0c069e..d443db04 100644 --- a/test/downloader.ts +++ b/test/downloader.ts @@ -3,9 +3,10 @@ import tape from 'tape'; import nock from 'nock'; import fs from 'fs'; import path from 'path'; -import { keccak256 } from 'js-sha3'; import { https } from 'follow-redirects'; import downloader from '../downloader'; +import { keccak256 } from 'js-sha3'; +import { hashFile } from '../common/helpers'; const assets = path.resolve(__dirname, 'resources/assets'); @@ -15,10 +16,6 @@ tape.onFinish(() => { } }); -function hash (filePath: string): string { - return '0x' + keccak256(fs.readFileSync(filePath, { encoding: 'binary' })); -} - function generateTestFile (t: tape.Test, content: string): tmp.FileResult { // As the `keep` option is set to true the removeCallback must be called by the caller // to cleanup the files after the test. @@ -126,7 +123,7 @@ tape('Download binary', async function (t) { server.origin, targetFilename, file.name, - hash(file.name) + hashFile(file.name) ); if (!fs.existsSync(targetFilename)) {