Skip to content

Commit

Permalink
fix: CID.parse(base36) (#307)
Browse files Browse the repository at this point in the history
This aims to support base36 out of the box, without having to specify
the 'base' parameter explicitly.

Rationale is that base36 is used across ecosystem for PeerIDs that have
to be represented in base36 to fit in a single DNS label (due to limit
of 63 characters).
  • Loading branch information
lidel authored Sep 12, 2024
1 parent 2189443 commit 892f198
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/cid.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { base32 } from './bases/base32.js'
import { base36 } from './bases/base36.js'
import { base58btc } from './bases/base58.js'
import { coerce } from './bytes.js'
import * as Digest from './hashes/digest.js'
Expand Down Expand Up @@ -402,10 +403,14 @@ function parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg
const decoder = base ?? base32
return [base32.prefix as Prefix, decoder.decode(source)]
}
case base36.prefix: {
const decoder = base ?? base36
return [base36.prefix as Prefix, decoder.decode(source)]
}
default: {
if (base == null) {
throw Error(
'To parse non base32 or base58btc encoded CID multibase decoder must be provided'
'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'
)
}
return [source[0] as Prefix, base.decode(source)]
Expand Down
13 changes: 11 additions & 2 deletions test/test-cid.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { assert } from 'aegir/chai'
import OLDCID from 'cids'
import { base32 } from '../src/bases/base32.js'
import { base36 } from '../src/bases/base36.js'
import { base58btc } from '../src/bases/base58.js'
import { base64 } from '../src/bases/base64.js'
import { fromHex, toHex, equals } from '../src/bytes.js'
Expand Down Expand Up @@ -568,7 +569,15 @@ describe('CID', () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)

const parsed = CID.parse(cid.toString())
const parsed = CID.parse(cid.toString(base32))
digestsame(cid, parsed)
})

it('parse 36 encoded CIDv1', async () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)

const parsed = CID.parse(cid.toString(base36))
digestsame(cid, parsed)
})

Expand All @@ -592,7 +601,7 @@ describe('CID', () => {
const hash = await sha256.digest(textEncoder.encode('abc'))
const cid = CID.create(1, 112, hash)
const msg =
'To parse non base32 or base58btc encoded CID multibase decoder must be provided'
'To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided'

assert.throws(() => CID.parse(cid.toString(base64)), msg)
})
Expand Down

0 comments on commit 892f198

Please sign in to comment.