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

Commit c888183

Browse files
Alan Shawvmx
authored andcommitted
fix: create new CID from old CID
When creating a CID from another CID instance that was created by and old version of this module (< 0.7) the `multibaseName` property would become `undefined` and cause an error to be thrown when calling `toString`. This PR ensures an appropriate `multibaseName` is picked in the edge case that this happens. License: MIT Signed-off-by: Alan Shaw <alan.shaw@protocol.ai>
1 parent 47f03c1 commit c888183

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/index.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,14 @@ class CID {
6060
* new CID(<cid>)
6161
*/
6262
constructor (version, codec, multihash, multibaseName) {
63-
if (module.exports.isCID(version)) {
63+
if (_CID.isCID(version)) {
6464
// version is an exising CID instance
6565
const cid = version
6666
this.version = cid.version
6767
this.codec = cid.codec
6868
this.multihash = Buffer.from(cid.multihash)
69-
this.multibaseName = cid.multibaseName
69+
// Default guard for when a CID < 0.7 is passed with no multibaseName
70+
this.multibaseName = cid.multibaseName || (cid.version === 0 ? 'base58btc' : 'base32')
7071
return
7172
}
7273

test/index.spec.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,18 @@ describe('CID', () => {
9191
const str = buffer.toString('hex')
9292
expect(str).to.equals('1220ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad')
9393
})
94+
95+
it('should construct from an old CID without a multibaseName', () => {
96+
const cidStr = 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'
97+
98+
const oldCid = new CID(cidStr)
99+
delete oldCid.multibaseName // Fake it
100+
101+
const newCid = new CID(oldCid)
102+
103+
expect(newCid.multibaseName).to.equal('base58btc')
104+
expect(newCid.toString()).to.equal(cidStr)
105+
})
94106
})
95107

96108
describe('v1', () => {
@@ -177,6 +189,18 @@ describe('CID', () => {
177189
'Codec `this-codec-doesnt-exist` not found'
178190
)
179191
})
192+
193+
it('should construct from an old CID without a multibaseName', () => {
194+
const cidStr = 'bafybeidskjjd4zmr7oh6ku6wp72vvbxyibcli2r6if3ocdcy7jjjusvl2u'
195+
196+
const oldCid = new CID(cidStr)
197+
delete oldCid.multibaseName // Fake it
198+
199+
const newCid = new CID(oldCid)
200+
201+
expect(newCid.multibaseName).to.equal('base32')
202+
expect(newCid.toString()).to.equal(cidStr)
203+
})
180204
})
181205

182206
describe('.toString', () => {

0 commit comments

Comments
 (0)