Skip to content

Commit f1601a0

Browse files
author
Alan Shaw
authored
feat: streaming sha256 CAR hash (#162)
1 parent 30b28d2 commit f1601a0

File tree

3 files changed

+96
-47
lines changed

3 files changed

+96
-47
lines changed

cmd/hash.js

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,26 @@
11
import fs from 'fs'
2+
import crypto from 'crypto'
23
import { pipeline } from 'stream/promises'
34
import { CID } from 'multiformats/cid'
5+
import * as Digest from 'multiformats/hashes/digest'
46
import { sha256 } from 'multiformats/hashes/sha2'
57

68
/** CAR CID code */
79
const carCode = 0x0202
810

911
/** @param {string} carPath */
1012
export default async function hash (carPath) {
11-
let bytes
12-
if (carPath) {
13-
bytes = await fs.promises.readFile(carPath)
14-
} else {
15-
bytes = await pipeline(
16-
process.stdin,
17-
async (source) => {
18-
const chunks = []
19-
for await (const chunk of source) {
20-
chunks.push(chunk)
21-
}
22-
return Buffer.concat(chunks)
13+
const hasher = crypto.createHash('sha256')
14+
15+
await pipeline(
16+
carPath ? fs.createReadStream(carPath) : process.stdin,
17+
async (source) => {
18+
for await (const chunk of source) {
19+
hasher.update(chunk)
2320
}
24-
)
25-
}
21+
}
22+
)
2623

27-
console.log(CID.createV1(carCode, await sha256.digest(bytes)).toString())
24+
const digest = Digest.create(sha256.code, hasher.digest())
25+
console.log(CID.createV1(carCode, digest).toString())
2826
}

package-lock.json

Lines changed: 81 additions & 30 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@
3636
"@ipld/dag-cbor": "^9.0.0",
3737
"@ipld/dag-json": "^10.0.1",
3838
"@ipld/dag-pb": "^4.0.2",
39-
"@ipld/unixfs": "^2.1.1",
39+
"@ipld/unixfs": "^3.0.0",
4040
"@web3-storage/car-block-validator": "^1.0.1",
4141
"files-from-path": "^1.0.0",
4242
"ipfs-unixfs-exporter": "^13.0.1",
43-
"multiformats": "^11.0.2",
43+
"multiformats": "^13.0.1",
4444
"sade": "^1.8.1",
4545
"varint": "^6.0.0"
4646
},

0 commit comments

Comments
 (0)