From 0e94b5531c98b4bde87eef9ee7b76e06f8a4f6a7 Mon Sep 17 00:00:00 2001 From: Oli Evans Date: Thu, 4 Apr 2019 10:00:07 +0100 Subject: [PATCH] chore: validate and test CIDv0 invariants Adds tests for - base other than 'base32btc' for CIDv0 - codec other than 'dag-pb' for CIDv0 License: MIT Signed-off-by: Oli Evans --- src/cid-util.js | 9 +++++++++ test/index.spec.js | 14 +++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/cid-util.js b/src/cid-util.js index 4f5c2db..8adfdd7 100644 --- a/src/cid-util.js +++ b/src/cid-util.js @@ -24,6 +24,15 @@ var CIDUtil = { return 'codec must be string' } + if (other.version === 0) { + if (other.codec !== 'dag-pb') { + return `codec must be 'dag-pb' for CIDv0` + } + if (other.multibaseName !== 'base58btc') { + return `multibaseName must be 'base58btc' for CIDv0` + } + } + if (!Buffer.isBuffer(other.multihash)) { return 'multihash must be a Buffer' } diff --git a/test/index.spec.js b/test/index.spec.js index 58e47b5..5d2c46d 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -66,7 +66,19 @@ describe('CID', () => { ).to.throw() }) - it('throws on trying to base encode CIDv0 in other base than base58 ', () => { + it('throws on trying to create a CIDv0 with a codec other than dag-pb', () => { + expect( + () => new CID(0, 'dag-cbor', hash) + ).to.throw(`codec must be 'dag-pb' for CIDv0`) + }) + + it('throws on trying to create a CIDv0 with a base other than base58btc', () => { + expect( + () => new CID(0, 'dag-pb', hash, 'base32') + ).to.throw(`multibaseName must be 'base58btc' for CIDv0`) + }) + + it('throws on trying to base encode CIDv0 in other base than base58btc', () => { const mhStr = 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n' const cid = new CID(mhStr) expect(() => cid.toBaseEncodedString('base16')).to.throw()