-
Notifications
You must be signed in to change notification settings - Fork 121
/
deepHash.ts
50 lines (42 loc) · 1.34 KB
/
deepHash.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import Arweave from "../common";
// In TypeScript 3.7, could be written as a single type:
// `type DeepHashChunk = Uint8Array | DeepHashChunk[];`
type DeepHashChunk = Uint8Array | DeepHashChunks;
interface DeepHashChunks extends Array<DeepHashChunk> {}
export default async function deepHash(
data: DeepHashChunk
): Promise<Uint8Array> {
if (Array.isArray(data)) {
const tag = Arweave.utils.concatBuffers([
Arweave.utils.stringToBuffer("list"),
Arweave.utils.stringToBuffer(data.length.toString()),
]);
return await deepHashChunks(
data,
await Arweave.crypto.hash(tag, "SHA-384")
);
}
const tag = Arweave.utils.concatBuffers([
Arweave.utils.stringToBuffer("blob"),
Arweave.utils.stringToBuffer(data.byteLength.toString()),
]);
const taggedHash = Arweave.utils.concatBuffers([
await Arweave.crypto.hash(tag, "SHA-384"),
await Arweave.crypto.hash(data, "SHA-384"),
]);
return await Arweave.crypto.hash(taggedHash, "SHA-384");
}
async function deepHashChunks(
chunks: DeepHashChunks,
acc: Uint8Array
): Promise<Uint8Array> {
if (chunks.length < 1) {
return acc;
}
const hashPair = Arweave.utils.concatBuffers([
acc,
await deepHash(chunks[0]),
]);
const newAcc = await Arweave.crypto.hash(hashPair, "SHA-384");
return await deepHashChunks(chunks.slice(1), newAcc);
}