Skip to content
Closed
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
4 changes: 4 additions & 0 deletions src/hashes/digest.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { coerce, equals as equalBytes } from '../bytes.js'
import * as varint from '../varint.js'
import { identity } from './identity.js'
import type { MultihashDigest } from './interface.js'

/**
Expand Down Expand Up @@ -30,6 +31,9 @@ export function decode (multihash: Uint8Array): MultihashDigest {
if (digest.byteLength !== size) {
throw new Error('Incorrect length')
}
if (code === 0x0 && size > identity.DefaultMaxIdentityDigestSize) {
throw new Error(`Identity digest exceeds maximum size of ${identity.DefaultMaxIdentityDigestSize} bytes`)
}

return new Digest(code, size, digest, bytes)
}
Expand Down
8 changes: 7 additions & 1 deletion src/hashes/identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import type { DigestOptions } from './hasher.js'
const code: 0x0 = 0x0
const name = 'identity'

const DefaultMaxIdentityDigestSize = 128

const encode: (input: Uint8Array) => Uint8Array = coerce

function digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<typeof code, number> {
Expand All @@ -16,7 +18,11 @@ function digest (input: Uint8Array, options?: DigestOptions): Digest.Digest<type
input = input.subarray(0, options.truncate)
}

if (input.byteLength > DefaultMaxIdentityDigestSize) {
throw new Error(`Identity digest exceeds maximum size of ${DefaultMaxIdentityDigestSize} bytes`)
}

return Digest.create(code, encode(input))
}

export const identity = { code, name, encode, digest }
export const identity = { code, name, encode, digest, DefaultMaxIdentityDigestSize }
7 changes: 6 additions & 1 deletion test/test-multihash.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { hash as slSha256 } from '@stablelib/sha256'
import { hash as slSha512 } from '@stablelib/sha512'
import { assert } from 'aegir/chai'
import { assert, expect } from 'aegir/chai'
import { sha1 as chSha1 } from 'crypto-hash'
import { fromHex, fromString } from '../src/bytes.js'
import { decode as decodeDigest, create as createDigest, hasCode as digestHasCode } from '../src/hashes/digest.js'
Expand Down Expand Up @@ -172,6 +172,11 @@ describe('multihash', () => {
assert.deepStrictEqual(hash2.bytes, hash.bytes)
})

it('hash identity oversized', () => {
const oversized = new Uint8Array(129).fill(0x61)
expect(() => identity.digest(oversized)).to.throw(/Identity digest exceeds maximum size of 128 bytes/)
})

it('hash identity truncated', async () => {
const hash = identity.digest(fromString('test'), {
truncate: 2
Expand Down