From 9ffb5e2822310d5f689f13dd1ce59528c38e5a00 Mon Sep 17 00:00:00 2001 From: naure Date: Sat, 13 Oct 2018 13:19:41 +0200 Subject: [PATCH] feat: support the hashLen option of multihashing (#83) 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. --- src/util.js | 4 +++- test/util.spec.js | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/util.js b/src/util.js index 195eefc..64191c5 100644 --- a/src/util.js +++ b/src/util.js @@ -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} */ @@ -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) } diff --git a/test/util.spec.js b/test/util.spec.js index 019e519..ca5823e 100644 --- a/test/util.spec.js +++ b/test/util.spec.js @@ -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 + // + expect(cid.buffer.length).to.equal(32) + expect(cid.toBaseEncodedString()).to.equal('z6dSUELEcAsg5oXs7gsv42rYfczTLizSBTpGUa5M3bxe') done() }) })