Skip to content

Commit

Permalink
fix: remove toString side effect that breaks deep equals (#142)
Browse files Browse the repository at this point in the history
Makes the cached string cid property non-enumerable so deep equals
still works even after a peer id has been stringifed.

Fixes #141
  • Loading branch information
achingbrain committed Mar 29, 2021
1 parent 5468ee0 commit eeb5330
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,11 @@ class PeerId {
toString () {
if (!this._idCIDString) {
const cid = new CID(1, 'libp2p-key', this.id, 'base32')
this._idCIDString = cid.toBaseEncodedString('base32')

Object.defineProperty(this, '_idCIDString', {
value: cid.toBaseEncodedString('base32'),
enumerable: false
})
}
return this._idCIDString
}
Expand Down
12 changes: 12 additions & 0 deletions test/peer-id.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,18 @@ describe('PeerId', () => {
expect(peerId.isValid()).to.equal(false)
})

it('keys are equal after one is stringified', async () => {
const peerId = await PeerId.create(testOpts)
const peerId1 = PeerId.createFromB58String(peerId.toB58String())
const peerId2 = PeerId.createFromB58String(peerId.toB58String())

expect(peerId1).to.deep.equal(peerId2)

peerId1.toString()

expect(peerId1).to.deep.equal(peerId2)
})

describe('returns error via cb instead of crashing', () => {
const garbage = [
uint8ArrayFromString('00010203040506070809', 'base16'),
Expand Down

0 comments on commit eeb5330

Please sign in to comment.