@ethersphere/bee-js
Version:
Javascript client for Bee
39 lines (38 loc) • 1.76 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateChunkAddress = void 0;
const cafe_utility_1 = require("cafe-utility");
const error_1 = require("../utils/error");
const typed_bytes_1 = require("../utils/typed-bytes");
const MAX_CHUNK_PAYLOAD_SIZE = 4096;
const SEGMENT_SIZE = 32;
/**
* Calculate a Binary Merkle Tree hash for a chunk
*
* The BMT chunk address is the hash of the 8 byte span and the root
* hash of a binary Merkle tree (BMT) built on the 32-byte segments
* of the underlying data.
*
* If the chunk content is less than 4k, the hash is calculated as
* if the chunk was padded with all zeros up to 4096 bytes.
*
* @param chunkContent Chunk data including span and payload as well
*
* @returns the keccak256 hash in a byte array
*/
function calculateChunkAddress(chunkContent) {
const span = chunkContent.slice(0, typed_bytes_1.Span.LENGTH);
const payload = chunkContent.slice(typed_bytes_1.Span.LENGTH);
const rootHash = calculateBmtRootHash(payload);
const chunkHash = cafe_utility_1.Binary.keccak256(cafe_utility_1.Binary.concatBytes(span, rootHash));
return new typed_bytes_1.Reference(chunkHash);
}
exports.calculateChunkAddress = calculateChunkAddress;
function calculateBmtRootHash(payload) {
if (payload.length > MAX_CHUNK_PAYLOAD_SIZE) {
throw new error_1.BeeArgumentError(`payload size ${payload.length} exceeds maximum chunk payload size ${MAX_CHUNK_PAYLOAD_SIZE}`, payload);
}
const input = new Uint8Array(MAX_CHUNK_PAYLOAD_SIZE);
input.set(payload);
return cafe_utility_1.Binary.log2Reduce(cafe_utility_1.Binary.partition(input, SEGMENT_SIZE), (a, b) => cafe_utility_1.Binary.keccak256(cafe_utility_1.Binary.concatBytes(a, b)));
}