/* merkle.h — BitTorrent v2 (BEP-52) SHA-256 Merkle trees. * * In v2 each file is split into 16 KiB leaf blocks; the leaf hashes form a * binary Merkle tree whose interior nodes are SHA-256(left || right). When the * leaf count is not a power of two, the tree is padded with *zero hashes* (a * block of 32 zero bytes at the leaf level, then SHA-256 of two children up the * tree) so the shape is a perfect binary tree. The root at the "piece layer" * boundary gives per-piece verifiability; the whole-file root goes in the * metainfo file tree. * * This module provides the tree primitive; metainfo/storage wire it to files. */ #ifndef NAUT_MERKLE_H #define NAUT_MERKLE_H #include "naut/common.h" #include "naut/hash.h" #define NAUT_MERKLE_LEAF (16u * 1024u) /* BEP-52 block size */ /* Compute the Merkle root of `nleaves` 32-byte leaf hashes, padding up to the * next power of two with zero hashes. nleaves==0 yields the all-zero hash. * `leaves` is nleaves*32 bytes; out is 32 bytes. Scratch is allocated * internally. Returns NAUT_OK or NAUT_ERR_NOMEM. */ naut_err naut_merkle_root(const uint8_t *leaves, size_t nleaves, uint8_t out[NAUT_SHA256_LEN]); /* As above but pad to a fixed `block_count` (>= nleaves, power of two) rather * than the next power of two — used to compute a piece-layer root where the * tree height is fixed by the piece size. */ naut_err naut_merkle_root_padded(const uint8_t *leaves, size_t nleaves, size_t block_count, uint8_t out[NAUT_SHA256_LEN]); /* Hash a contiguous data buffer into leaf hashes (one SHA-256 per 16 KiB, last * leaf may be short). out must hold ceil(len/16KiB)*32 bytes. Returns the leaf * count. */ size_t naut_merkle_leaves(const uint8_t *data, size_t len, uint8_t *out); #endif /* NAUT_MERKLE_H */