27 lines
1020 B
JavaScript
27 lines
1020 B
JavaScript
/* hash.js — streaming SHA-256 of files on disk (never loads a whole video).
|
|
* The hex digest of a validated file is its P2P content id (cid). */
|
|
import { createHash } from 'node:crypto';
|
|
import { createReadStream } from 'node:fs';
|
|
|
|
export function sha256File(path) {
|
|
return new Promise((resolve, reject) => {
|
|
const h = createHash('sha256');
|
|
createReadStream(path, { highWaterMark: 1024 * 1024 })
|
|
.on('data', (d) => h.update(d))
|
|
.on('error', reject)
|
|
.on('end', () => resolve(h.digest('hex')));
|
|
});
|
|
}
|
|
|
|
// Hash of bytes [offset, offset+length) — used for holder range challenges.
|
|
export function sha256Range(path, offset, length) {
|
|
return new Promise((resolve, reject) => {
|
|
if (!(length > 0)) { resolve(createHash('sha256').digest('hex')); return; }
|
|
const h = createHash('sha256');
|
|
createReadStream(path, { start: offset, end: offset + length - 1 })
|
|
.on('data', (d) => h.update(d))
|
|
.on('error', reject)
|
|
.on('end', () => resolve(h.digest('hex')));
|
|
});
|
|
}
|