biketrack-app/node_modules/@ethersphere/bee-js/dist/cjs/chunk/cac.js

57 lines
2.2 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertValidChunkData = exports.isValidChunkData = exports.makeContentAddressedChunk = exports.MAX_PAYLOAD_SIZE = exports.MIN_PAYLOAD_SIZE = void 0;
const error_1 = require("../utils/error");
const bmt_1 = require("./bmt");
const bytes_1 = require("../utils/bytes");
const serialize_1 = require("./serialize");
const span_1 = require("./span");
exports.MIN_PAYLOAD_SIZE = 1;
exports.MAX_PAYLOAD_SIZE = 4096;
const CAC_SPAN_OFFSET = 0;
const CAC_PAYLOAD_OFFSET = CAC_SPAN_OFFSET + span_1.SPAN_SIZE;
/**
* Creates a content addressed chunk and verifies the payload size.
*
* @param payloadBytes the data to be stored in the chunk
*/
function makeContentAddressedChunk(payloadBytes) {
const span = (0, span_1.makeSpan)(payloadBytes.length);
(0, bytes_1.assertFlexBytes)(payloadBytes, exports.MIN_PAYLOAD_SIZE, exports.MAX_PAYLOAD_SIZE);
const data = (0, serialize_1.serializeBytes)(span, payloadBytes);
return {
data,
span: () => span,
payload: () => (0, bytes_1.flexBytesAtOffset)(data, CAC_PAYLOAD_OFFSET, exports.MIN_PAYLOAD_SIZE, exports.MAX_PAYLOAD_SIZE),
address: () => (0, bmt_1.bmtHash)(data),
};
}
exports.makeContentAddressedChunk = makeContentAddressedChunk;
/**
* Type guard for valid content addressed chunk data
*
* @param data The chunk data
* @param chunkAddress The address of the chunk
*/
function isValidChunkData(data, chunkAddress) {
if (!(data instanceof Uint8Array))
return false;
const address = (0, bmt_1.bmtHash)(data);
return (0, bytes_1.bytesEqual)(address, chunkAddress);
}
exports.isValidChunkData = isValidChunkData;
/**
* Asserts if data are representing given address of its chunk.
*
* @param data The chunk data
* @param chunkAddress The address of the chunk
*
* @returns a valid content addressed chunk or throws error
*/
function assertValidChunkData(data, chunkAddress) {
if (!isValidChunkData(data, chunkAddress)) {
throw new error_1.BeeError('Address of content address chunk does not match given data!');
}
}
exports.assertValidChunkData = assertValidChunkData;