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

Commit 9ffb5e2

Browse files
naurevmx
authored andcommitted
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.
1 parent 29411b2 commit 9ffb5e2

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

src/util.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ exports.deserialize = (data, callback) => {
125125
* @param {Object} [options] - Options to create the CID
126126
* @param {number} [options.version=1] - CID version number
127127
* @param {string} [options.hashAlg] - Defaults to hashAlg for the resolver
128+
* @param {number} [options.hashLen] - Optionally trim the digest to this length
128129
* @param {CidCallback} callback - Callback that handles the return value
129130
* @returns {void}
130131
*/
@@ -135,10 +136,11 @@ exports.cid = (dagNode, options, callback) => {
135136
}
136137
options = options || {}
137138
const hashAlg = options.hashAlg || resolver.defaultHashAlg
139+
const hashLen = options.hashLen
138140
const version = typeof options.version === 'undefined' ? 1 : options.version
139141
waterfall([
140142
(cb) => exports.serialize(dagNode, cb),
141-
(serialized, cb) => multihashing(serialized, hashAlg, cb),
143+
(serialized, cb) => multihashing(serialized, hashAlg, hashLen, cb),
142144
(mh, cb) => cb(null, new CID(version, resolver.multicodec, mh))
143145
], callback)
144146
}

test/util.spec.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,24 @@ describe('util', () => {
7474
expect(cid.multihash).to.exist()
7575
const mh = multihash.decode(cid.multihash)
7676
expect(mh.name).to.equal('sha2-512')
77+
expect(mh.length).to.equal(64)
78+
done()
79+
})
80+
})
81+
82+
it('.cid with hashAlg and hashLen', (done) => {
83+
dagCBOR.util.cid(obj, { hashAlg: 'keccak-256', hashLen: 28 }, (err, cid) => {
84+
expect(err).to.not.exist()
85+
expect(cid.version).to.equal(1)
86+
expect(cid.codec).to.equal('dag-cbor')
87+
expect(cid.multihash).to.exist()
88+
const mh = multihash.decode(cid.multihash)
89+
expect(mh.name).to.equal('keccak-256')
90+
expect(mh.length).to.equal(28)
91+
// The CID must be 32 bytes including 4 bytes for
92+
// <cid-version><multicodec><hash-function><digest-size>
93+
expect(cid.buffer.length).to.equal(32)
94+
expect(cid.toBaseEncodedString()).to.equal('z6dSUELEcAsg5oXs7gsv42rYfczTLizSBTpGUa5M3bxe')
7795
done()
7896
})
7997
})

0 commit comments

Comments
 (0)