Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bin.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ cli
cli
.command('hash [car]')
.describe('Generate CID for a CAR.')
.option('-m, --only-multihash', 'Output base58btc encoded multihash instead of a CID.')
.action(createAction('./cmd/hash.js'))

cli.parse(process.argv)
Expand Down
14 changes: 11 additions & 3 deletions cmd/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import { pipeline } from 'stream/promises'
import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { sha256 } from 'multiformats/hashes/sha2'
import { base58btc } from 'multiformats/bases/base58'

/** CAR CID code */
const carCode = 0x0202

/** @param {string} carPath */
export default async function hash (carPath) {
/**
* @param {string} carPath
* @param {{ 'only-multihash': boolean }} [opts]
*/
export default async function hash (carPath, opts) {
const hasher = crypto.createHash('sha256')

await pipeline(
Expand All @@ -22,5 +26,9 @@ export default async function hash (carPath) {
)

const digest = Digest.create(sha256.code, hasher.digest())
console.log(CID.createV1(carCode, digest).toString())
if (opts?.['only-multihash']) {
console.log(base58btc.encode(digest.bytes))
} else {
console.log(CID.createV1(carCode, digest).toString())
}
}
6 changes: 6 additions & 0 deletions test/bin.node.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,12 @@ describe('CLI', function () {
assert.equal(res.stdout, 'bagbaieraycsgjotn63wc2tdyiyadvkdach5vphpdmoeehnseebjbtapgi44q')
})

it('generate multihash', () => {
const carPath = './test/fixtures/comic.car'
const res = execaSync(binPath, ['hash', carPath, '--only-multihash'])
assert.equal(res.stdout, 'zQmbJeNsbY4jTphnsZ4RBHG2jC8STcBanGVPi3V3A9FQxSU')
})

it('stdin | generate CAR CID', () => {
const carPath = './test/fixtures/comic.car'
const res = execaSync(binPath, ['hash'], {
Expand Down