@ethersphere/bee-js
Version:
Javascript client for Bee
41 lines • 1.62 kB
JavaScript
import { Binary } from 'cafe-utility';
import { Bytes } from "../utils/bytes.js";
import { Span } from "../utils/typed-bytes.js";
import { calculateChunkAddress } from "./bmt.js";
export const MIN_PAYLOAD_SIZE = 1;
export const 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
*/
export function makeContentAddressedChunk(payloadBytes) {
if (!(payloadBytes instanceof Uint8Array)) {
payloadBytes = ENCODER.encode(payloadBytes);
}
if (payloadBytes.length < MIN_PAYLOAD_SIZE || payloadBytes.length > MAX_PAYLOAD_SIZE) {
throw new RangeError(`payload size ${payloadBytes.length} exceeds limits [${MIN_PAYLOAD_SIZE}, ${MAX_PAYLOAD_SIZE}]`);
}
const span = Span.fromBigInt(BigInt(payloadBytes.length));
const data = Binary.concatBytes(span.toUint8Array(), payloadBytes);
return {
data,
span,
payload: Bytes.fromSlice(data, Span.LENGTH),
address: calculateChunkAddress(data)
};
}
export function asContentAddressedChunk(chunkBytes) {
if (chunkBytes.length < MIN_PAYLOAD_SIZE + Span.LENGTH || chunkBytes.length > MAX_PAYLOAD_SIZE + Span.LENGTH) {
throw new RangeError(`chunk size ${chunkBytes.length} exceeds limits [${MIN_PAYLOAD_SIZE + Span.LENGTH}, ${Span.LENGTH}]`);
}
const span = Span.fromSlice(chunkBytes, 0);
const data = Binary.concatBytes(span.toUint8Array(), chunkBytes.slice(Span.LENGTH));
return {
data,
span,
payload: Bytes.fromSlice(data, Span.LENGTH),
address: calculateChunkAddress(data)
};
}