Skip to content
This repository has been archived by the owner on Aug 24, 2021. It is now read-only.

feat: add types to the library #92

Merged
merged 8 commits into from
Feb 2, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
14 changes: 10 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@
"browser": {
"./src/sha.js": "./src/sha.browser.js"
},
"types": "dist/src/index.d.ts",
"repository": "github:multiformats/js-multihashing-async",
"scripts": {
"test": "aegir test",
"test:browser": "aegir test -t browser",
"test:node": "aegir test -t node",
"lint": "aegir lint",
"check": "aegir ts -p check",
"prepare": "aegir build --no-bundle",
"docs": "aegir docs",
"release": "aegir release --docs",
"release-minor": "aegir release --type minor --docs",
Expand All @@ -35,17 +38,20 @@
},
"dependencies": {
"blakejs": "^1.1.0",
"err-code": "^2.0.0",
"err-code": "^2.0.3",
"js-sha3": "^0.8.0",
"multihashes": "^3.0.1",
"multihashes": "multiformats/js-multihash#fix/temp-types",
"murmurhash3js-revisited": "^3.0.0",
"uint8arrays": "^1.0.0"
"uint8arrays": "^2.0.5"
},
"devDependencies": {
"aegir": "^25.0.0",
"aegir": "ipfs/aegir#feat/docs2.0",
"benchmark": "^2.1.4",
"sinon": "^9.0.2"
},
"eslintConfig": {
"extends": "ipfs"
},
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
Expand Down
10 changes: 10 additions & 0 deletions src/blake.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict'

// @ts-ignore - no types available
const blake = require('blakejs')

const minB = 0xb201
Expand All @@ -21,12 +22,21 @@ const blake2s = {
// the function as async because it must return a Promise to match the API
// for other functions that do perform asynchronous work (see sha.browser.js)
// eslint-disable-next-line

/**
* @param {number} size
* @param {any} hf
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: perhaps useful to type hf?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes but im going to defer that to another PR

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#96

* @returns {import('./types').Digest}
*/
const makeB2Hash = (size, hf) => async (data) => {
const ctx = hf.init(size, null)
hf.update(ctx, data)
return hf.digest(ctx)
}

/**
* @param {Record<number, import('./types').Digest>} table
*/
module.exports = (table) => {
for (let i = 0; i < 64; i++) {
table[minB + i] = makeB2Hash(i + 1, blake2b)
Expand Down
6 changes: 6 additions & 0 deletions src/crypto.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict'

const sha3 = require('js-sha3')
// @ts-ignore - no types available
const mur = require('murmurhash3js-revisited')
const { factory: sha } = require('./sha')
const { fromNumberTo32BitBuf } = require('./utils')
Expand All @@ -10,6 +11,10 @@ const uint8ArrayFromString = require('uint8arrays/from-string')
// the function as async because it must return a Promise to match the API
// for other functions that do perform asynchronous work (see sha.browser.js)
// eslint-disable-next-line
/**
* @param {string} algorithm
* @returns {import('./types').Digest}
*/
const hash = (algorithm) => async (data) => {
switch (algorithm) {
case 'sha3-224':
Expand Down Expand Up @@ -42,6 +47,7 @@ const hash = (algorithm) => async (data) => {
}
}

/** @type {import('./types').Digest} */
const identity = data => data

module.exports = {
Expand Down
53 changes: 33 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,20 @@ const crypto = require('./crypto')
const equals = require('uint8arrays/equals')

/**
* Hash the given `buf` using the algorithm specified by `alg`.
* @param {Uint8Array} buf - The value to hash.
* @param {number|string} alg - The algorithm to use eg 'sha1'
* @typedef {import("./types").Digest} Digest
* @typedef {import("./types").HashName} HashName
*/

/**
* Hash the given `bytes` using the algorithm specified by `alg`.
*
* @param {Uint8Array} bytes - The value to hash.
* @param {HashName} alg - The algorithm to use eg 'sha1'
* @param {number} [length] - Optionally trim the result to this length.
* @returns {Promise<Uint8Array>}
*/
async function Multihashing (buf, alg, length) {
const digest = await Multihashing.digest(buf, alg, length)
async function Multihashing (bytes, alg, length) {
const digest = await Multihashing.digest(bytes, alg, length)
return multihash.encode(digest, alg, length)
}

Expand All @@ -23,47 +29,49 @@ async function Multihashing (buf, alg, length) {
Multihashing.multihash = multihash

/**
* @param {Uint8Array} buf - The value to hash.
* @param {number|string} alg - The algorithm to use eg 'sha1'
* @param {Uint8Array} bytes - The value to hash.
* @param {HashName} alg - The algorithm to use eg 'sha1'
* @param {number} [length] - Optionally trim the result to this length.
* @returns {Promise<Uint8Array>}
*/
Multihashing.digest = async (buf, alg, length) => {
Multihashing.digest = async (bytes, alg, length) => {
const hash = Multihashing.createHash(alg)
const digest = await hash(buf)
const digest = await hash(bytes)
return length ? digest.slice(0, length) : digest
}

/**
* Creates a function that hashes with the given algorithm
*
* @param {string|number} alg - The algorithm to use eg 'sha1'
*
* @returns {function} - The hash function corresponding to `alg`
* @param {HashName} alg - The algorithm to use eg 'sha1'
* @returns {Digest} - The hash function corresponding to `alg`
*/
Multihashing.createHash = function (alg) {
if (!alg) {
throw errcode(new Error('hash algorithm must be specified'), 'ERR_HASH_ALGORITHM_NOT_SPECIFIED')
const e = errcode(new Error('hash algorithm must be specified'), 'ERR_HASH_ALGORITHM_NOT_SPECIFIED')
throw e
}

alg = multihash.coerceCode(alg)
if (!Multihashing.functions[alg]) {
const code = multihash.coerceCode(alg)
if (!Multihashing.functions[code]) {
throw errcode(new Error(`multihash function '${alg}' not yet supported`), 'ERR_HASH_ALGORITHM_NOT_SUPPORTED')
}

return Multihashing.functions[alg]
return Multihashing.functions[code]
}

/**
* Mapping of multihash codes to their hashing functions.
* @type {Object}
*
* @type {Record<number, Digest>}
*/
// @ts-ignore - most of those functions aren't typed
Multihashing.functions = {
// identity
0x00: crypto.identity,
// sha1
0x11: crypto.sha1,
// sha2-256
// // sha2-256
hugomrdias marked this conversation as resolved.
Show resolved Hide resolved
0x12: crypto.sha2256,
// sha2-512
0x13: crypto.sha2512,
Expand Down Expand Up @@ -98,8 +106,13 @@ Multihashing.functions = {
// add blake functions
crypto.addBlake(Multihashing.functions)

Multihashing.validate = async (buf, hash) => {
const newHash = await Multihashing(buf, multihash.decode(hash).name)
/**
* @param {Uint8Array} bytes
* @param {Uint8Array} hash
* @returns {Promise<boolean>}
*/
Multihashing.validate = async (bytes, hash) => {
const newHash = await Multihashing(bytes, multihash.decode(hash).name)

return equals(hash, newHash)
}
Expand Down
25 changes: 22 additions & 3 deletions src/sha.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,20 @@

const multihash = require('multihashes')

const crypto = self.crypto || self.msCrypto
const crypto =
self.crypto ||
/** @type {typeof window.crypto} */
// @ts-ignore - unknown property
(self.msCrypto)

/**
*
* @param {Uint8Array} data
* @param {import('./types').HashName} alg
* @returns {Promise<Uint8Array>}
*/
const digest = async (data, alg) => {
if (typeof self === 'undefined' || (!self.crypto && !self.msCrypto)) {
if (typeof self === 'undefined' || !crypto) {
throw new Error(
'Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context'
)
Expand All @@ -28,12 +38,21 @@ const digest = async (data, alg) => {
}

module.exports = {
/**
* @param {import('./types').HashName} alg
* @returns {import('./types').Digest}
*/
factory: (alg) => async (data) => {
return digest(data, alg)
},
digest,
/**
* @param {Uint8Array} buf
* @param {import('./types').HashName} alg
* @param {number} [length]
*/
multihashing: async (buf, alg, length) => {
const h = await digest(buf, alg, length)
const h = await digest(buf, alg)
return multihash.encode(h, alg, length)
}
}
17 changes: 16 additions & 1 deletion src/sha.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const multihash = require('multihashes')
// the function as async because it must return a Promise to match the API
// for other functions that do perform asynchronous work (see sha.browser.js)
// eslint-disable-next-line

/**
* @param {Uint8Array} data
* @param {import('./types').HashName} alg
* @returns {Promise<Uint8Array>}
*/
const digest = async (data, alg) => {
switch (alg) {
case 'sha1':
Expand All @@ -25,12 +31,21 @@ const digest = async (data, alg) => {
}

module.exports = {
/**
* @param {import('./types').HashName} alg
* @returns {import('./types').Digest}
*/
factory: (alg) => async (data) => {
return digest(data, alg)
},
digest,
/**
* @param {Uint8Array} buf
* @param {import('./types').HashName} alg
* @param {number} [length]
*/
multihashing: async (buf, alg, length) => {
const h = await digest(buf, alg, length)
const h = await digest(buf, alg)
return multihash.encode(h, alg, length)
}
}
9 changes: 9 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { HashName } from 'multihashes'

export interface Digest {
(data: Uint8Array): Promise<Uint8Array> | Uint8Array
}

// This works around the TS bug which emits bad import paths
hugomrdias marked this conversation as resolved.
Show resolved Hide resolved
// on imports in js files.
export type { HashName }
4 changes: 4 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
'use strict'

/**
* @param {number} number
* @returns {Uint8Array}
*/
const fromNumberTo32BitBuf = (number) => {
const bytes = new Uint8Array(4)

Expand Down
3 changes: 3 additions & 0 deletions test/fixtures/encodes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
'use strict'

/**
* @type {Array<[string, import('../../src/types').HashName, string]>}
*/
module.exports = [[
'beep boop',
'identity',
Expand Down
7 changes: 7 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ describe('error handling', () => {
const methods = {
multihashing: multihashing,
digest: multihashing.digest,
/**
* @param {Uint8Array} buff
* @param {import('../src/types').HashName} alg
*/
createHash: (buff, alg) => multihashing.createHash(alg)
}

Expand All @@ -70,6 +74,7 @@ describe('error handling', () => {
const buf = uint8ArrayFromString('beep boop')

try {
// @ts-expect-error - alg argument is expected
await fn(buf)
} catch (err) {
expect(err).to.exist()
Expand All @@ -82,8 +87,10 @@ describe('error handling', () => {
it('throws an error when the hashing algorithm is not supported', async () => {
const buf = uint8ArrayFromString('beep boop')

// @ts-ignore - sinon is inferring that snake-oil isn't a valid alg
const stub = sinon.stub(require('multihashes'), 'coerceCode').returns('snake-oil')
try {
// @ts-expect-error - non valid algorithm
await fn(buf, 'snake-oil')
} catch (err) {
expect(err).to.exist()
Expand Down
10 changes: 10 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "aegir/src/config/tsconfig.aegir.json",
"compilerOptions": {
"outDir": "dist"
Gozala marked this conversation as resolved.
Show resolved Hide resolved
},
"include": [
"test",
"src"
]
}