-
Notifications
You must be signed in to change notification settings - Fork 45
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: streaming sha256 CAR hash (#162)
- Loading branch information
Alan Shaw
authored
Jan 22, 2024
1 parent
30b28d2
commit f1601a0
Showing
3 changed files
with
96 additions
and
47 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,26 @@ | ||
import fs from 'fs' | ||
import crypto from 'crypto' | ||
import { pipeline } from 'stream/promises' | ||
import { CID } from 'multiformats/cid' | ||
import * as Digest from 'multiformats/hashes/digest' | ||
import { sha256 } from 'multiformats/hashes/sha2' | ||
|
||
/** CAR CID code */ | ||
const carCode = 0x0202 | ||
|
||
/** @param {string} carPath */ | ||
export default async function hash (carPath) { | ||
let bytes | ||
if (carPath) { | ||
bytes = await fs.promises.readFile(carPath) | ||
} else { | ||
bytes = await pipeline( | ||
process.stdin, | ||
async (source) => { | ||
const chunks = [] | ||
for await (const chunk of source) { | ||
chunks.push(chunk) | ||
} | ||
return Buffer.concat(chunks) | ||
const hasher = crypto.createHash('sha256') | ||
|
||
await pipeline( | ||
carPath ? fs.createReadStream(carPath) : process.stdin, | ||
async (source) => { | ||
for await (const chunk of source) { | ||
hasher.update(chunk) | ||
} | ||
) | ||
} | ||
} | ||
) | ||
|
||
console.log(CID.createV1(carCode, await sha256.digest(bytes)).toString()) | ||
const digest = Digest.create(sha256.code, hasher.digest()) | ||
console.log(CID.createV1(carCode, digest).toString()) | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters