From 177ddc5a41504d2902db242381b1223f08449809 Mon Sep 17 00:00:00 2001 From: Richard Schneider Date: Wed, 27 Jun 2018 23:27:29 +1200 Subject: [PATCH] fix: do not ignore cid.options (#20) --- src/util.js | 11 ++++++++--- test/util.spec.js | 19 +++++++++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/src/util.js b/src/util.js index 823d39f..60ad068 100644 --- a/src/util.js +++ b/src/util.js @@ -67,7 +67,9 @@ const deserialize = (binaryBlob, callback) => { * Get the CID of the DAG-Node. * * @param {BitcoinBlock} dagNode - Internal representation of a Bitcoin block - * @param {Object} [options] - Ignored + * @param {Object} [options] - Options to create the CID + * @param {number} [options.version=1] - CID version number + * @param {string} [options.hashAlg='dbl-sha2-256'] - Hashing algorithm * @param {CidCallback} callback - Callback that handles the return value * @returns {void} */ @@ -77,15 +79,18 @@ const cid = (dagNode, options, callback) => { options = {} } options = options || {} + // avoid deadly embrace between resolver and util + const hashAlg = options.hashAlg || require('./resolver').defaultHashAlg + const version = typeof options.version === 'undefined' ? 1 : options.version waterfall([ (cb) => { try { - multihashing(dagNode.toBuffer(true), 'dbl-sha2-256', cb) + multihashing(dagNode.toBuffer(true), hashAlg, cb) } catch (err) { cb(err) } }, - (mh, cb) => cb(null, new CID(1, 'bitcoin-block', mh)) + (mh, cb) => cb(null, new CID(version, 'bitcoin-block', mh)) ], callback) } diff --git a/test/util.spec.js b/test/util.spec.js index e2d6194..71a5a92 100644 --- a/test/util.spec.js +++ b/test/util.spec.js @@ -151,18 +151,18 @@ describe('IPLD format util API cid()', () => { }) }) - it('should encode the CID correctly and ignore all options', (done) => { + it('should encode the CID correctly with options', (done) => { IpldBitcoin.util.deserialize(fixtureBlock, (err, dagNode) => { expect(err).to.not.exist() verifyCid1( dagNode, - { hashAlg: 'unknown' }, - '56203ec2c691d447b2fd0d6a94742345af1f351037dab1ab9e900200000000000000', + { hashAlg: 'sha3-256' }, + '16208fd2802e0304c79c08a1ff2afb706ce64b78f3b94fd1c9142946c2e715589cfb', done) }) }) - it('should encode the CID correctly and ignore undefined options', (done) => { + it('should encode the CID correctly with undefined options', (done) => { IpldBitcoin.util.deserialize(fixtureBlock, (err, dagNode) => { expect(err).to.not.exist() verifyCid1( @@ -172,6 +172,17 @@ describe('IPLD format util API cid()', () => { done) }) }) + + it('should encode the CID correctly with default options specified', (done) => { + IpldBitcoin.util.deserialize(fixtureBlock, (err, dagNode) => { + expect(err).to.not.exist() + verifyCid1( + dagNode, + { version: 1, hashAlg: 'dbl-sha2-256' }, + '56203ec2c691d447b2fd0d6a94742345af1f351037dab1ab9e900200000000000000', + done) + }) + }) }) const verifyBlock = (dagNode, expected) => {