Skip to content

Commit

Permalink
feat: disambiguate errors (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan Shaw authored May 9, 2023
1 parent 09165c5 commit 0c984a6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
19 changes: 17 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,37 @@ export const hashMap = new Map(
].map(hash => [hash.code, hash])
)

/** The multihash hasher is not supported by this library. */
export class UnsupportedHashError extends Error {
/** @param {number} code */
constructor (code) {
super(`multihash code ${code} is not supported`)
}
}

/** The bytes did not hash to the same value as the passed multihash. */
export class HashMismatchError extends Error {
constructor () {
super('CID hash does not match bytes')
}
}

/**
* Validates IPLD block bytes.
* @param {Block} block
*/
export function validateBlock (block) {
const hasher = hashMap.get(block.cid.multihash.code)
if (!hasher) {
throw new Error(`multihash code ${block.cid.multihash.code} is not supported`)
throw new UnsupportedHashError(block.cid.multihash.code)
}

const result = hasher.digest(block.bytes)

/** @param {import('multiformats/hashes/interface').MultihashDigest} h */
const compareDigests = h => {
if (!equals(h.digest, block.cid.multihash.digest)) {
throw new Error('CID hash does not match bytes')
throw new HashMismatchError()
}
}

Expand Down
22 changes: 20 additions & 2 deletions test/test.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import test from 'ava'
import * as pb from '@ipld/dag-pb'
import { CID } from 'multiformats/cid'
import { CarWriter, CarBlockIterator } from '@ipld/car'
import { blake2b512 } from '@multiformats/blake2/blake2b'

import { validateBlock, hashMap } from '../src/index.js'
import { validateBlock, hashMap, HashMismatchError, UnsupportedHashError } from '../src/index.js'

const bytes = pb.encode({ Data: new Uint8Array([1, 2, 3]), Links: [] })

Expand Down Expand Up @@ -37,7 +38,24 @@ for (const [code, hasher] of hashMap) {
const reader = await CarBlockIterator.fromIterable(out)

for await (const block of reader) {
t.throwsAsync(async () => validateBlock(block))
const err = await t.throwsAsync(async () => validateBlock(block))
t.true(err instanceof HashMismatchError)
}
})
}

test('throws when validating blocks with unsupported hashers', async (t) => {
const hash = await blake2b512.digest(bytes)
const cid = CID.create(1, pb.code, hash)

const { writer, out } = CarWriter.create([cid])
writer.put({ cid, bytes })
writer.close()

const reader = await CarBlockIterator.fromIterable(out)

for await (const block of reader) {
const err = await t.throwsAsync(async () => validateBlock(block))
t.true(err instanceof UnsupportedHashError)
}
})

0 comments on commit 0c984a6

Please sign in to comment.