Skip to content

Commit c3463c7

Browse files
hacdiasjacobheun
authored andcommitted
feat: async await (#87)
BREAKING CHANGE: API refactored to use async/await
1 parent bbabd74 commit c3463c7

File tree

5 files changed

+201
-337
lines changed

5 files changed

+201
-337
lines changed

README.md

+18-8
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
- [API](#api)
2929
- [Create](#create)
3030
- [`new PeerId(id[, privKey, pubKey])`](#new-peeridid-privkey-pubkey)
31-
- [`create([opts], callback)`](#createopts-callback)
31+
- [`create([opts])`](#createopts)
3232
- [Import](#import)
3333
- [`createFromHexString(str)`](#createfromhexstringstr)
3434
- [`createFromBytes(buf)`](#createfrombytesbuf)
@@ -57,11 +57,10 @@ The public key is a base64 encoded string of a protobuf containing an RSA DER bu
5757
```JavaScript
5858
const PeerId = require('peer-id')
5959

60-
PeerId.create({ bits: 1024 }, (err, id) => {
61-
if (err) { throw err }
62-
console.log(JSON.stringify(id.toJSON(), null, 2))
63-
})
60+
const id = await PeerId.create({ bits: 1024 })
61+
console.log(JSON.stringify(id.toJSON(), null, 2))
6462
```
63+
6564
```bash
6665
{
6766
"id": "Qma9T5YraSnpRDZqRR4krcSJabThc8nwZuJV3LercPHufi",
@@ -124,47 +123,58 @@ const PeerId = require('peer-id')
124123

125124
The key format is detailed in [libp2p-crypto](https://github.com/libp2p/js-libp2p-crypto).
126125

127-
### `create([opts], callback)`
126+
### `create([opts])`
128127

129128
Generates a new Peer ID, complete with public/private keypair.
130129

131130
- `opts: Object`: Default: `{bits: 2048}`
132-
- `callback: Function`
133131

134-
Calls back `callback` with `err, id`.
132+
Returns `Promise<PeerId>`.
135133

136134
## Import
137135

138136
### `createFromHexString(str)`
139137

140138
Creates a Peer ID from hex string representing the key's multihash.
141139

140+
Returns `PeerId.
141+
142142
### `createFromBytes(buf)`
143143

144144
Creates a Peer ID from a buffer representing the key's multihash.
145145

146+
Returns `PeerId`.
147+
146148
### `createFromB58String(str)`
147149

148150
Creates a Peer ID from a Base58 string representing the key's multihash.
149151

152+
Returns `PeerId`.
153+
150154
### `createFromPubKey(pubKey)`
151155

152156
- `publicKey: Buffer`
153157

154158
Creates a Peer ID from a buffer containing a public key.
155159

160+
Returns `Promise<PeerId>`.
161+
156162
### `createFromPrivKey(privKey)`
157163

158164
- `privKey: Buffer`
159165

160166
Creates a Peer ID from a buffer containing a private key.
161167

168+
Returns `Promise<PeerId>`.
169+
162170
### `createFromJSON(obj)`
163171

164172
- `obj.id: String` - The multihash encoded in `base58`
165173
- `obj.pubKey: String` - The public key in protobuf format, encoded in `base64`
166174
- `obj.privKey: String` - The private key in protobuf format, encoded in `base64`
167175

176+
Returns `Promise<PeerId>`.
177+
168178
## Export
169179

170180
### `toHexString()`

package.json

+3-4
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,14 @@
3434
},
3535
"homepage": "https://github.com/libp2p/js-peer-id",
3636
"devDependencies": {
37-
"aegir": "^18.2.2",
38-
"bundlesize": "~0.17.1",
37+
"aegir": "^19.0.5",
38+
"bundlesize": "~0.18.0",
3939
"chai": "^4.2.0",
4040
"dirty-chai": "^2.0.1"
4141
},
4242
"dependencies": {
43-
"async": "^2.6.2",
4443
"class-is": "^1.1.0",
45-
"libp2p-crypto": "~0.16.1",
44+
"libp2p-crypto": "~0.17.0",
4645
"multihashes": "~0.4.14"
4746
},
4847
"repository": {

src/bin.js

+5-6
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44

55
const PeerId = require('./index.js')
66

7-
PeerId.create((err, id) => {
8-
if (err) {
9-
throw err
10-
}
7+
async function main () {
8+
const id = await PeerId.create()
9+
console.log(JSON.stringify(id.toJSON(), null, 2)) // eslint-disable-line no-console
10+
}
1111

12-
console.log(JSON.stringify(id.toJSON(), null, 2))
13-
})
12+
main()

src/index.js

+57-123
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
const mh = require('multihashes')
88
const cryptoKeys = require('libp2p-crypto/src/keys')
99
const assert = require('assert')
10-
const waterfall = require('async/waterfall')
1110
const withIs = require('class-is')
1211

1312
class PeerId {
@@ -119,176 +118,111 @@ class PeerId {
119118
/*
120119
* Check if this PeerId instance is valid (privKey -> pubKey -> Id)
121120
*/
122-
isValid (callback) {
123-
// TODO Needs better checking
124-
if (this.privKey &&
121+
isValid () {
122+
// TODO: needs better checking
123+
return Boolean(this.privKey &&
125124
this.privKey.public &&
126125
this.privKey.public.bytes &&
127126
Buffer.isBuffer(this.pubKey.bytes) &&
128-
this.privKey.public.bytes.equals(this.pubKey.bytes)) {
129-
callback()
130-
} else {
131-
callback(new Error('Keys not match'))
132-
}
127+
this.privKey.public.bytes.equals(this.pubKey.bytes))
133128
}
134129
}
135130

136-
const PeerIdWithIs = withIs(PeerId, { className: 'PeerId', symbolName: '@libp2p/js-peer-id/PeerId' })
131+
const PeerIdWithIs = withIs(PeerId, {
132+
className: 'PeerId',
133+
symbolName: '@libp2p/js-peer-id/PeerId'
134+
})
137135

138136
exports = module.exports = PeerIdWithIs
139137

140138
// generation
141-
exports.create = function (opts, callback) {
142-
if (typeof opts === 'function') {
143-
callback = opts
144-
opts = {}
145-
}
139+
exports.create = async (opts) => {
146140
opts = opts || {}
147141
opts.bits = opts.bits || 2048
148142

149-
waterfall([
150-
(cb) => cryptoKeys.generateKeyPair('RSA', opts.bits, cb),
151-
(privKey, cb) => privKey.public.hash((err, digest) => {
152-
cb(err, digest, privKey)
153-
})
154-
], (err, digest, privKey) => {
155-
if (err) {
156-
return callback(err)
157-
}
143+
const key = await cryptoKeys.generateKeyPair('RSA', opts.bits)
144+
const digest = await key.public.hash()
158145

159-
callback(null, new PeerIdWithIs(digest, privKey))
160-
})
146+
return new PeerIdWithIs(digest, key)
161147
}
162148

163-
exports.createFromHexString = function (str) {
149+
exports.createFromHexString = (str) => {
164150
return new PeerIdWithIs(mh.fromHexString(str))
165151
}
166152

167-
exports.createFromBytes = function (buf) {
153+
exports.createFromBytes = (buf) => {
168154
return new PeerIdWithIs(buf)
169155
}
170156

171-
exports.createFromB58String = function (str) {
157+
exports.createFromB58String = (str) => {
172158
return new PeerIdWithIs(mh.fromB58String(str))
173159
}
174160

175161
// Public Key input will be a buffer
176-
exports.createFromPubKey = function (key, callback) {
177-
if (typeof callback !== 'function') {
178-
throw new Error('callback is required')
179-
}
180-
181-
let pubKey
182-
183-
try {
184-
let buf = key
185-
if (typeof buf === 'string') {
186-
buf = Buffer.from(key, 'base64')
187-
}
188-
189-
if (!Buffer.isBuffer(buf)) throw new Error('Supplied key is neither a base64 string nor a buffer')
162+
exports.createFromPubKey = async (key) => {
163+
let buf = key
190164

191-
pubKey = cryptoKeys.unmarshalPublicKey(buf)
192-
} catch (err) {
193-
return callback(err)
165+
if (typeof buf === 'string') {
166+
buf = Buffer.from(key, 'base64')
194167
}
195168

196-
pubKey.hash((err, digest) => {
197-
if (err) {
198-
return callback(err)
199-
}
169+
if (!Buffer.isBuffer(buf)) {
170+
throw new Error('Supplied key is neither a base64 string nor a buffer')
171+
}
200172

201-
callback(null, new PeerIdWithIs(digest, null, pubKey))
202-
})
173+
const pubKey = await cryptoKeys.unmarshalPublicKey(buf)
174+
const digest = await pubKey.hash()
175+
return new PeerIdWithIs(digest, null, pubKey)
203176
}
204177

205178
// Private key input will be a string
206-
exports.createFromPrivKey = function (key, callback) {
207-
if (typeof callback !== 'function') {
208-
throw new Error('callback is required')
209-
}
210-
179+
exports.createFromPrivKey = async (key) => {
211180
let buf = key
212181

213-
try {
214-
if (typeof buf === 'string') {
215-
buf = Buffer.from(key, 'base64')
216-
}
182+
if (typeof buf === 'string') {
183+
buf = Buffer.from(key, 'base64')
184+
}
217185

218-
if (!Buffer.isBuffer(buf)) throw new Error('Supplied key is neither a base64 string nor a buffer')
219-
} catch (err) {
220-
return callback(err)
186+
if (!Buffer.isBuffer(buf)) {
187+
throw new Error('Supplied key is neither a base64 string nor a buffer')
221188
}
222189

223-
waterfall([
224-
(cb) => cryptoKeys.unmarshalPrivateKey(buf, cb),
225-
(privKey, cb) => privKey.public.hash((err, digest) => {
226-
cb(err, digest, privKey)
227-
})
228-
], (err, digest, privKey) => {
229-
if (err) {
230-
return callback(err)
231-
}
190+
const privKey = await cryptoKeys.unmarshalPrivateKey(buf)
191+
const digest = await privKey.public.hash()
232192

233-
callback(null, new PeerIdWithIs(digest, privKey, privKey.public))
234-
})
193+
return new PeerIdWithIs(digest, privKey, privKey.public)
235194
}
236195

237-
exports.createFromJSON = function (obj, callback) {
238-
if (typeof callback !== 'function') {
239-
throw new Error('callback is required')
196+
exports.createFromJSON = async (obj) => {
197+
let id = mh.fromB58String(obj.id)
198+
let rawPrivKey = obj.privKey && Buffer.from(obj.privKey, 'base64')
199+
let rawPubKey = obj.pubKey && Buffer.from(obj.pubKey, 'base64')
200+
let pub = rawPubKey && await cryptoKeys.unmarshalPublicKey(rawPubKey)
201+
202+
if (!rawPrivKey) {
203+
return new PeerIdWithIs(id, null, pub)
240204
}
241205

242-
let id
243-
let rawPrivKey
244-
let rawPubKey
245-
let pub
246-
247-
try {
248-
id = mh.fromB58String(obj.id)
249-
rawPrivKey = obj.privKey && Buffer.from(obj.privKey, 'base64')
250-
rawPubKey = obj.pubKey && Buffer.from(obj.pubKey, 'base64')
251-
pub = rawPubKey && cryptoKeys.unmarshalPublicKey(rawPubKey)
252-
} catch (err) {
253-
return callback(err)
206+
const privKey = await cryptoKeys.unmarshalPrivateKey(rawPrivKey)
207+
const privDigest = await privKey.public.hash()
208+
let pubDigest
209+
210+
if (pub) {
211+
pubDigest = await pub.hash()
254212
}
255213

256-
if (rawPrivKey) {
257-
waterfall([
258-
(cb) => cryptoKeys.unmarshalPrivateKey(rawPrivKey, cb),
259-
(priv, cb) => priv.public.hash((err, digest) => {
260-
cb(err, digest, priv)
261-
}),
262-
(privDigest, priv, cb) => {
263-
if (pub) {
264-
pub.hash((err, pubDigest) => {
265-
cb(err, privDigest, priv, pubDigest)
266-
})
267-
} else {
268-
cb(null, privDigest, priv)
269-
}
270-
}
271-
], (err, privDigest, priv, pubDigest) => {
272-
if (err) {
273-
return callback(err)
274-
}
275-
276-
if (pub && !privDigest.equals(pubDigest)) {
277-
return callback(new Error('Public and private key do not match'))
278-
}
279-
280-
if (id && !privDigest.equals(id)) {
281-
return callback(new Error('Id and private key do not match'))
282-
}
283-
284-
callback(null, new PeerIdWithIs(id, priv, pub))
285-
})
286-
} else {
287-
callback(null, new PeerIdWithIs(id, null, pub))
214+
if (pub && !privDigest.equals(pubDigest)) {
215+
throw new Error('Public and private key do not match')
288216
}
217+
218+
if (id && !privDigest.equals(id)) {
219+
throw new Error('Id and private key do not match')
220+
}
221+
222+
return new PeerIdWithIs(id, privKey, pub)
289223
}
290224

291-
exports.isPeerId = function (peerId) {
225+
exports.isPeerId = (peerId) => {
292226
return Boolean(typeof peerId === 'object' &&
293227
peerId._id &&
294228
peerId._idB58String)

0 commit comments

Comments
 (0)