@ethersphere/bee-js
Version:
Javascript client for Bee
47 lines (46 loc) • 2.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.asContentAddressedChunk = exports.makeContentAddressedChunk = exports.MAX_PAYLOAD_SIZE = exports.MIN_PAYLOAD_SIZE = void 0;
const cafe_utility_1 = require("cafe-utility");
const bytes_1 = require("../utils/bytes");
const typed_bytes_1 = require("../utils/typed-bytes");
const bmt_1 = require("./bmt");
exports.MIN_PAYLOAD_SIZE = 1;
exports.MAX_PAYLOAD_SIZE = 4096;
const ENCODER = new TextEncoder();
/**
* Creates a content addressed chunk and verifies the payload size.
*
* @param payloadBytes the data to be stored in the chunk
*/
function makeContentAddressedChunk(payloadBytes) {
if (!(payloadBytes instanceof Uint8Array)) {
payloadBytes = ENCODER.encode(payloadBytes);
}
if (payloadBytes.length < exports.MIN_PAYLOAD_SIZE || payloadBytes.length > exports.MAX_PAYLOAD_SIZE) {
throw new RangeError(`payload size ${payloadBytes.length} exceeds limits [${exports.MIN_PAYLOAD_SIZE}, ${exports.MAX_PAYLOAD_SIZE}]`);
}
const span = typed_bytes_1.Span.fromBigInt(BigInt(payloadBytes.length));
const data = cafe_utility_1.Binary.concatBytes(span.toUint8Array(), payloadBytes);
return {
data,
span,
payload: bytes_1.Bytes.fromSlice(data, typed_bytes_1.Span.LENGTH),
address: (0, bmt_1.calculateChunkAddress)(data),
};
}
exports.makeContentAddressedChunk = makeContentAddressedChunk;
function asContentAddressedChunk(chunkBytes) {
if (chunkBytes.length < exports.MIN_PAYLOAD_SIZE + typed_bytes_1.Span.LENGTH || chunkBytes.length > exports.MAX_PAYLOAD_SIZE + typed_bytes_1.Span.LENGTH) {
throw new RangeError(`chunk size ${chunkBytes.length} exceeds limits [${exports.MIN_PAYLOAD_SIZE + typed_bytes_1.Span.LENGTH}, ${typed_bytes_1.Span.LENGTH}]`);
}
const span = typed_bytes_1.Span.fromSlice(chunkBytes, 0);
const data = cafe_utility_1.Binary.concatBytes(span.toUint8Array(), chunkBytes.slice(typed_bytes_1.Span.LENGTH));
return {
data,
span,
payload: bytes_1.Bytes.fromSlice(data, typed_bytes_1.Span.LENGTH),
address: (0, bmt_1.calculateChunkAddress)(data),
};
}
exports.asContentAddressedChunk = asContentAddressedChunk;