UNPKG

hackpro-sdk

Version:
88 lines 3.13 kB
"use strict"; /* * Copyright 2019 balena.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); const crc_1 = require("crc"); const crypto_1 = require("crypto"); const lodash_1 = require("lodash"); const XXHash = require("xxhash"); const xxhash_1 = require("xxhash"); const constants_1 = require("../constants"); const errors_1 = require("../errors"); class CRC32Hasher { update(data) { this.value = crc_1.crc32(data, this.value); } digest(_encoding) { return lodash_1.padStart(this.value.toString(16), 8, '0'); } } function createHasher(checksumType) { if (checksumType === 'crc32') { return new CRC32Hasher(); } else if (checksumType === 'sha1' || checksumType === 'sha256') { return crypto_1.createHash(checksumType); } else if (checksumType === 'xxhash32') { return new XXHash(constants_1.XXHASH_SEED); } else if (checksumType === 'xxhash64') { return new xxhash_1.XXHash64(constants_1.XXHASH_SEED); } } function* createSparseReaderStateIterator(blocks, verify, generateChecksums) { if (verify && generateChecksums) { throw new Error('verify and generateChecksums are mutually exclusive'); } if (generateChecksums) { for (const block of blocks) { if (block.checksumType === undefined) { throw new Error('All blocks must have a checksumType if generateChecksums is true'); } } } for (const block of blocks) { const hasher = createHasher(block.checksumType); for (const subBlock of block.blocks) { yield { block, subBlock, hasher }; } verifyOrGenerateChecksum(hasher, block, verify, generateChecksums); } } exports.createSparseReaderStateIterator = createSparseReaderStateIterator; function verifyOrGenerateChecksum(hasher, blocks, verify, generateChecksums) { if (hasher !== undefined) { const checksum = hasher.digest('hex'); if (generateChecksums) { blocks.checksum = checksum; } else if (verify && blocks.checksum !== checksum) { throw new errors_1.BlocksVerificationError(blocks, checksum); } } } function blocksLength(blocks) { let sum = 0; for (const block of blocks) { for (const blk of block.blocks) { sum += blk.length; } } return sum; } exports.blocksLength = blocksLength; //# sourceMappingURL=shared.js.map