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

Commit

Permalink
feat: support the hashLen option of multihashing (#83)
Browse files Browse the repository at this point in the history
This supports the creation CIDs of particular sizes using the variable size of
multihashes. One use-case is to fit into the 32 bytes word size of Ethereum.
  • Loading branch information
naure authored and vmx committed Oct 13, 2018
1 parent 29411b2 commit 9ffb5e2
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ exports.deserialize = (data, callback) => {
* @param {Object} [options] - Options to create the CID
* @param {number} [options.version=1] - CID version number
* @param {string} [options.hashAlg] - Defaults to hashAlg for the resolver
* @param {number} [options.hashLen] - Optionally trim the digest to this length
* @param {CidCallback} callback - Callback that handles the return value
* @returns {void}
*/
Expand All @@ -135,10 +136,11 @@ exports.cid = (dagNode, options, callback) => {
}
options = options || {}
const hashAlg = options.hashAlg || resolver.defaultHashAlg
const hashLen = options.hashLen
const version = typeof options.version === 'undefined' ? 1 : options.version
waterfall([
(cb) => exports.serialize(dagNode, cb),
(serialized, cb) => multihashing(serialized, hashAlg, cb),
(serialized, cb) => multihashing(serialized, hashAlg, hashLen, cb),
(mh, cb) => cb(null, new CID(version, resolver.multicodec, mh))
], callback)
}
18 changes: 18 additions & 0 deletions test/util.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@ describe('util', () => {
expect(cid.multihash).to.exist()
const mh = multihash.decode(cid.multihash)
expect(mh.name).to.equal('sha2-512')
expect(mh.length).to.equal(64)
done()
})
})

it('.cid with hashAlg and hashLen', (done) => {
dagCBOR.util.cid(obj, { hashAlg: 'keccak-256', hashLen: 28 }, (err, cid) => {
expect(err).to.not.exist()
expect(cid.version).to.equal(1)
expect(cid.codec).to.equal('dag-cbor')
expect(cid.multihash).to.exist()
const mh = multihash.decode(cid.multihash)
expect(mh.name).to.equal('keccak-256')
expect(mh.length).to.equal(28)
// The CID must be 32 bytes including 4 bytes for
// <cid-version><multicodec><hash-function><digest-size>
expect(cid.buffer.length).to.equal(32)
expect(cid.toBaseEncodedString()).to.equal('z6dSUELEcAsg5oXs7gsv42rYfczTLizSBTpGUa5M3bxe')
done()
})
})
Expand Down

0 comments on commit 9ffb5e2

Please sign in to comment.