Skip to content

Commit

Permalink
Merge pull request #44 from libp2p/feat/cache
Browse files Browse the repository at this point in the history
feat: cache b58 id
  • Loading branch information
daviddias authored Dec 18, 2016
2 parents 5d6a962 + 78d96d0 commit f0d72b7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,20 @@ class PeerId {
assert(privKey.public.bytes.equals(pubKey.bytes), 'inconsistent arguments')
}

this.id = id
this._id = id
this._idB58String = mh.toB58String(this.id)
this._privKey = privKey
this._pubKey = pubKey
}

get id () {
return this._id
}

set id (val) {
throw new Error('Id is immutable')
}

get privKey () {
return this._privKey
}
Expand Down Expand Up @@ -61,7 +70,7 @@ class PeerId {
// of go-ipfs for its config file
toJSON () {
return {
id: mh.toB58String(this.id),
id: this.toB58String(),
privKey: toB64Opt(this.marshalPrivKey()),
pubKey: toB64Opt(this.marshalPubKey())
}
Expand All @@ -77,7 +86,7 @@ class PeerId {
}

toB58String () {
return mh.toB58String(this.id)
return this._idB58String
}
}

Expand Down
11 changes: 11 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ describe('PeerId', () => {
})
})

it('throws on changing the id', (done) => {
PeerId.create((err, id) => {
expect(err).to.not.exist
expect(id.toB58String().length).to.equal(46)
expect(() => {
id.id = new Buffer('hello')
}).to.throw(/immutable/)
done()
})
})

it('recreate an Id from Hex string', () => {
const id = PeerId.createFromHexString(testIdHex)
expect(testIdBytes).to.deep.equal(id.id)
Expand Down

0 comments on commit f0d72b7

Please sign in to comment.