diff --git a/.travis.yml b/.travis.yml index 5102ee5..b6370b2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,10 +4,10 @@ language: node_js matrix: include: - - node_js: 6 - env: CXX=g++-4.8 - node_js: 8 env: CXX=g++-4.8 + - node_js: 10 + env: CXX=g++-4.8 # - node_js: stable # env: CXX=g++-4.8 diff --git a/README.md b/README.md index 5aecb4b..972f2a5 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ - [API](#api) - [Create](#create) - [`new PeerId(id[, privKey, pubKey])`](#new-peeridid-privkey-pubkey) - - [`create([opts], callback)`](#createopts-callback) + - [`create([opts])`](#createopts) - [Import](#import) - [`createFromHexString(str)`](#createfromhexstringstr) - [`createFromBytes(buf)`](#createfrombytesbuf) @@ -57,11 +57,10 @@ The public key is a base64 encoded string of a protobuf containing an RSA DER bu ```JavaScript const PeerId = require('peer-id') -PeerId.create({ bits: 1024 }, (err, id) => { - if (err) { throw err } - console.log(JSON.stringify(id.toJSON(), null, 2)) -}) +const id = await PeerId.create({ bits: 1024 }) +console.log(JSON.stringify(id.toJSON(), null, 2)) ``` + ```bash { "id": "Qma9T5YraSnpRDZqRR4krcSJabThc8nwZuJV3LercPHufi", @@ -124,14 +123,13 @@ const PeerId = require('peer-id') The key format is detailed in [libp2p-crypto](https://github.com/libp2p/js-libp2p-crypto). -### `create([opts], callback)` +### `create([opts])` Generates a new Peer ID, complete with public/private keypair. - `opts: Object`: Default: `{bits: 2048}` -- `callback: Function` -Calls back `callback` with `err, id`. +Returns `Promise`. ## Import @@ -139,32 +137,44 @@ Calls back `callback` with `err, id`. Creates a Peer ID from hex string representing the key's multihash. +Returns `Promise`. + ### `createFromBytes(buf)` Creates a Peer ID from a buffer representing the key's multihash. +Returns `Promise`. + ### `createFromB58String(str)` Creates a Peer ID from a Base58 string representing the key's multihash. +Returns `Promise`. + ### `createFromPubKey(pubKey)` - `publicKey: Buffer` Creates a Peer ID from a buffer containing a public key. +Returns `Promise`. + ### `createFromPrivKey(privKey)` - `privKey: Buffer` Creates a Peer ID from a buffer containing a private key. +Returns `Promise`. + ### `createFromJSON(obj)` - `obj.id: String` - The multihash encoded in `base58` - `obj.pubKey: String` - The public key in protobuf format, encoded in `base64` - `obj.privKey: String` - The private key in protobuf format, encoded in `base64` +Returns `Promise`. + ## Export ### `toHexString()` diff --git a/appveyor.yml b/appveyor.yml index 046bf91..8ab0d6c 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,8 +3,8 @@ version: "{build}" environment: matrix: - - nodejs_version: "6" - nodejs_version: "8" + - nodejs_version: "10" matrix: fast_finish: true diff --git a/src/bin.js b/src/bin.js index 9388e68..11e9b87 100755 --- a/src/bin.js +++ b/src/bin.js @@ -4,10 +4,9 @@ const PeerId = require('./index.js') -PeerId.create((err, id) => { - if (err) { - throw err - } +async function main () { + const id = await PeerId.create() + console.log(JSON.stringify(id.toJSON(), null, 1)) +} - console.log(JSON.stringify(id.toJSON(), null, 2)) -}) +main() diff --git a/src/index.js b/src/index.js index 9a1fb07..8be37a1 100644 --- a/src/index.js +++ b/src/index.js @@ -54,14 +54,14 @@ class PeerId { } // Return the protobuf version of the public key, matching go ipfs formatting - async marshalPubKey () { + marshalPubKey () { if (this.pubKey) { return crypto.keys.marshalPublicKey(this.pubKey) } } // Return the protobuf version of the private key, matching go ipfs formatting - async marshalPrivKey () { + marshalPrivKey () { if (this.privKey) { return crypto.keys.marshalPrivateKey(this.privKey) } @@ -84,11 +84,11 @@ class PeerId { // return the jsonified version of the key, matching the formatting // of go-ipfs for its config file - async toJSON () { + toJSON () { return { id: this.toB58String(), - privKey: toB64Opt(await this.marshalPrivKey()), - pubKey: toB64Opt(await this.marshalPubKey()) + privKey: toB64Opt(this.marshalPrivKey()), + pubKey: toB64Opt(this.marshalPubKey()) } } @@ -118,7 +118,7 @@ class PeerId { /* * Check if this PeerId instance is valid (privKey -> pubKey -> Id) */ - async isValid () { + isValid () { // TODO Needs better checking if (this.privKey && this.privKey.public && @@ -132,12 +132,15 @@ class PeerId { } } -const PeerIdWithIs = withIs(PeerId, { className: 'PeerId', symbolName: '@libp2p/js-peer-id/PeerId' }) +const PeerIdWithIs = withIs(PeerId, { + className: 'PeerId', + symbolName: '@libp2p/js-peer-id/PeerId' +}) exports = module.exports = PeerIdWithIs // generation -exports.create = async function (opts) { +exports.create = async (opts) => { opts = opts || {} opts.bits = opts.bits || 2048 @@ -147,20 +150,20 @@ exports.create = async function (opts) { return new PeerIdWithIs(digest, key) } -exports.createFromHexString = function (str) { +exports.createFromHexString = async (str) => { return new PeerIdWithIs(mh.fromHexString(str)) } -exports.createFromBytes = function (buf) { +exports.createFromBytes = async (buf) => { return new PeerIdWithIs(buf) } -exports.createFromB58String = function (str) { +exports.createFromB58String = async (str) => { return new PeerIdWithIs(mh.fromB58String(str)) } // Public Key input will be a buffer -exports.createFromPubKey = async function (key) { +exports.createFromPubKey = async (key) => { let buf = key if (typeof buf === 'string') { @@ -177,7 +180,7 @@ exports.createFromPubKey = async function (key) { } // Private key input will be a string -exports.createFromPrivKey = async function (key) { +exports.createFromPrivKey = async (key) => { let buf = key if (typeof buf === 'string') { @@ -194,7 +197,7 @@ exports.createFromPrivKey = async function (key) { return new PeerIdWithIs(digest, privKey, privKey.public) } -exports.createFromJSON = async function (obj) { +exports.createFromJSON = async (obj) => { let id = mh.fromB58String(obj.id) let rawPrivKey = obj.privKey && Buffer.from(obj.privKey, 'base64') let rawPubKey = obj.pubKey && Buffer.from(obj.pubKey, 'base64') @@ -223,7 +226,7 @@ exports.createFromJSON = async function (obj) { return new PeerIdWithIs(id, privKey, pub) } -exports.isPeerId = function (peerId) { +exports.isPeerId = (peerId) => { return Boolean(typeof peerId === 'object' && peerId._id && peerId._idB58String) diff --git a/test/peer-id.spec.js b/test/peer-id.spec.js index 376937c..349908b 100644 --- a/test/peer-id.spec.js +++ b/test/peer-id.spec.js @@ -51,18 +51,18 @@ describe('PeerId', () => { }).to.throw(/immutable/) }) - it('recreate an Id from Hex string', () => { - const id = PeerId.createFromHexString(testIdHex) + it('recreate an Id from Hex string', async () => { + const id = await PeerId.createFromHexString(testIdHex) expect(testIdBytes).to.deep.equal(id.id) }) - it('Recreate an Id from a Buffer', () => { - const id = PeerId.createFromBytes(testIdBytes) + it('Recreate an Id from a Buffer', async () => { + const id = await PeerId.createFromBytes(testIdBytes) expect(testId.id).to.equal(id.toHexString()) }) - it('Recreate a B58 String', () => { - const id = PeerId.createFromB58String(testIdB58String) + it('Recreate a B58 String', async () => { + const id = await PeerId.createFromB58String(testIdB58String) expect(testIdB58String).to.equal(id.toB58String()) }) @@ -77,12 +77,12 @@ describe('PeerId', () => { const encoded = Buffer.from(testId.privKey, 'base64') const id2 = await PeerId.createFromPrivKey(encoded) expect(testIdB58String).to.equal(id2.toB58String()) - expect(await id.marshalPubKey()).to.deep.equal(await id2.marshalPubKey()) + expect(id.marshalPubKey()).to.deep.equal(id2.marshalPubKey()) }) it('Compare generated ID with one created from PubKey', async () => { const id1 = await PeerId.create(testOpts) - const id2 = await PeerId.createFromPubKey(await id1.marshalPubKey()) + const id2 = await PeerId.createFromPubKey(id1.marshalPubKey()) expect(id1.id).to.be.eql(id2.id) }) @@ -99,13 +99,13 @@ describe('PeerId', () => { it('Pretty printing', async () => { const id1 = await PeerId.create(testOpts) - const id2 = await PeerId.createFromPrivKey((await id1.toJSON()).privKey) + const id2 = await PeerId.createFromPrivKey((id1.toJSON()).privKey) expect(id1.toPrint()).to.be.eql(id2.toPrint()) expect(id1.toPrint()).to.equal('') }) - it('toBytes', () => { - const id = PeerId.createFromHexString(testIdHex) + it('toBytes', async () => { + const id = await PeerId.createFromHexString(testIdHex) expect(id.toBytes().toString('hex')).to.equal(testIdBytes.toString('hex')) }) @@ -124,7 +124,7 @@ describe('PeerId', () => { describe('fromJSON', () => { it('full node', async () => { const id = await PeerId.create(testOpts) - const other = await PeerId.createFromJSON(await id.toJSON()) + const other = await PeerId.createFromJSON(id.toJSON()) expect(id.toB58String()).to.equal(other.toB58String()) expect(id.privKey.bytes).to.eql(other.privKey.bytes) expect(id.pubKey.bytes).to.eql(other.pubKey.bytes) @@ -133,10 +133,10 @@ describe('PeerId', () => { it('only id', async () => { const key = await crypto.keys.generateKeyPair('RSA', 1024) const digest = await key.public.hash() - const id = PeerId.createFromBytes(digest) + const id = await PeerId.createFromBytes(digest) expect(id.privKey).to.not.exist() expect(id.pubKey).to.not.exist() - const other = await PeerId.createFromJSON(await id.toJSON()) + const other = await PeerId.createFromJSON(id.toJSON()) expect(id.toB58String()).to.equal(other.toB58String()) }) @@ -150,49 +150,57 @@ describe('PeerId', () => { it('set privKey (valid)', async () => { const peerId = await PeerId.create(testOpts) peerId.privKey = peerId._privKey - await peerId.isValid() + expect(peerId.isValid()).to.equal(true) }) it('set pubKey (valid)', async () => { const peerId = await PeerId.create(testOpts) peerId.pubKey = peerId._pubKey - await peerId.isValid() + expect(peerId.isValid()).to.equal(true) }) it('set privKey (invalid)', async () => { const peerId = await PeerId.create(testOpts) peerId.privKey = Buffer.from('bufff') - await expect(peerId.isValid()).to.be.rejected - }) - /* + try { + peerId.isValid() + } catch (err) { + expect(err).to.exist() + } + }) it('set pubKey (invalid)', async () => { const peerId = await PeerId.create(testOpts) - peerId.pubKey = Buffer.from('buffff') - peerId.isValid((err) => { - expect(err).to.exist() - done() - }) - }) + peerId.pubKey = Buffer.from('bufff') + + try { + peerId.isValid() + } catch (err) { + expect(err).to.exist() + } }) describe('returns error via cb instead of crashing', () => { - const garbage = [Buffer.from('00010203040506070809', 'hex'), {}, null, false, undefined, true, 1, 0, Buffer.from(''), 'aGVsbG93b3JsZA==', 'helloworld', ''] + const garbage = [ + Buffer.from('00010203040506070809', 'hex'), + {}, null, false, undefined, true, 1, 0, + Buffer.from(''), 'aGVsbG93b3JsZA==', 'helloworld', '' + ] const fncs = ['createFromPubKey', 'createFromPrivKey', 'createFromJSON'] - garbage.forEach(garbage => { - fncs.forEach(fnc => { - it(fnc + '(' + util.inspect(garbage) + ')', cb => { - PeerId[fnc](garbage, (err, res) => { + for (const gb of garbage) { + for (const fn of fncs) { + it(`${fn} (${util.inspect(gb)})`, async () => { + try { + await PeerId[fn](gb) + } catch (err) { expect(err).to.exist() - expect(res).to.not.exist() - cb() - }) + } }) - }) - }) + } + } }) describe('throws on inconsistent data', () => { @@ -201,41 +209,33 @@ describe('PeerId', () => { let k3 before(async () => { - parallel([ - (cb) => crypto.keys.generateKeyPair('RSA', 512, cb), - (cb) => crypto.keys.generateKeyPair('RSA', 512, cb), - (cb) => crypto.keys.generateKeyPair('RSA', 512, cb) - ], (err, keys) => { - expect(err).to.not.exist() - - k1 = keys[0] - k2 = keys[1] - k3 = keys[2] - done() - }) + const keys = await Promise.all([ + crypto.keys.generateKeyPair('RSA', 512), + crypto.keys.generateKeyPair('RSA', 512), + crypto.keys.generateKeyPair('RSA', 512) + ]) + + k1 = keys[0] + k2 = keys[1] + k3 = keys[2] }) it('missmatch private - public key', async () => { - k1.public.hash((err, digest) => { - expect(err).to.not.exist() - expect(() => new PeerId(digest, k1, k2.public)) - .to.throw(/inconsistent arguments/) - done() - }) + const digest = await k1.public.hash() + expect(() => { + new PeerId(digest, k1, k2.public) // eslint-disable-line no-new + }).to.throw(/inconsistent arguments/) }) it('missmatch id - private - public key', async () => { - k1.public.hash((err, digest) => { - expect(err).to.not.exist() - expect(() => new PeerId(digest, k1, k3.public)) - .to.throw(/inconsistent arguments/) - done() - }) + const digest = await k1.public.hash() + expect(() => { + new PeerId(digest, k1, k3.public) // eslint-disable-line no-new + }).to.throw(/inconsistent arguments/) }) it('invalid id', () => { expect(() => new PeerId('hello world')).to.throw(/invalid id/) }) }) - */ })