-
Notifications
You must be signed in to change notification settings - Fork 44
/
peer-id.spec.js
417 lines (353 loc) · 14.5 KB
/
peer-id.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/* eslint max-nested-callbacks: ["error", 8] */
/* eslint-env mocha */
'use strict'
const { expect } = require('aegir/utils/chai')
const crypto = require('libp2p-crypto')
const { CID } = require('multiformats/cid')
const Digest = require('multiformats/hashes/digest')
const { base16 } = require('multiformats/bases/base16')
const { base36 } = require('multiformats/bases/base36')
const { base58btc } = require('multiformats/bases/base58')
const { identity } = require('multiformats/hashes/identity')
const { fromString: uint8ArrayFromString } = require('uint8arrays/from-string')
const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
const PeerId = require('../src')
const util = require('util')
const DAG_PB_CODE = 0x70
const LIBP2P_KEY_CODE = 0x72
const RAW_CODE = 0x55
const testId = require('./fixtures/sample-id')
const testIdHex = testId.id
const testIdBytes = base16.decode(`f${testId.id}`)
const testIdDigest = Digest.decode(testIdBytes)
const testIdB58String = base58btc.encode(testIdBytes).substring(1)
const testIdB36String = base36.encode(testIdBytes)
const testIdCID = CID.createV1(LIBP2P_KEY_CODE, testIdDigest)
const testIdCIDString = testIdCID.toString()
const goId = require('./fixtures/go-private-key')
// Test options for making PeerId.create faster
// INSECURE, only use when testing
const testOpts = {
bits: 512
}
describe('PeerId', () => {
it('create an id without \'new\'', () => {
expect(PeerId).to.throw(Error)
})
it('create a new id', async () => {
const id = await PeerId.create(testOpts)
expect(id.toB58String().length).to.equal(46)
})
it('can be created for a Secp256k1 key', async () => {
const id = await PeerId.create({ keyType: 'secp256k1', bits: 256 })
const expB58 = base58btc.encode((await identity.digest(id.pubKey.bytes)).bytes).slice(1)
expect(id.toB58String()).to.equal(expB58)
})
it('can get the public key from a Secp256k1 key', async () => {
const original = await PeerId.create({ keyType: 'secp256k1', bits: 256 })
const newId = PeerId.createFromB58String(original.toB58String())
expect(original.pubKey.bytes).to.eql(newId.pubKey.bytes)
})
it('isPeerId', async () => {
const id = await PeerId.create(testOpts)
expect(PeerId.isPeerId(id)).to.equal(true)
expect(PeerId.isPeerId('aaa')).to.equal(false)
expect(PeerId.isPeerId(uint8ArrayFromString('batatas'))).to.equal(false)
})
it('throws on changing the id', async () => {
const id = await PeerId.create(testOpts)
expect(id.toB58String().length).to.equal(46)
expect(() => {
// @ts-ignore
id.id = uint8ArrayFromString('hello')
}).to.throw(/immutable/)
})
it('recreate from Hex string', () => {
const id = PeerId.createFromHexString(testIdHex)
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from a Uint8Array', () => {
const id = PeerId.createFromBytes(testIdBytes)
expect(testId.id).to.equal(id.toHexString())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from a B58 String', () => {
const id = PeerId.createFromB58String(testIdB58String)
expect(testIdB58String).to.equal(id.toB58String())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from CID object', () => {
const id = PeerId.createFromCID(testIdCID)
expect(testIdCIDString).to.equal(id.toString())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from Base58 String (CIDv0)', () => {
const id = PeerId.createFromCID(CID.parse(testIdB58String))
expect(testIdCIDString).to.equal(id.toString())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from Base36 String', () => {
const id = PeerId.parse(testIdB36String)
expect(testIdCIDString).to.equal(id.toString())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from CIDv1 Base32 (libp2p-key multicodec)', () => {
const cid = CID.createV1(LIBP2P_KEY_CODE, testIdDigest)
const id = PeerId.createFromCID(cid)
expect(cid.toString()).to.equal(id.toString())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from CIDv1 Base32 (dag-pb multicodec)', () => {
const cid = CID.createV1(DAG_PB_CODE, testIdDigest)
const id = PeerId.createFromCID(cid)
// toString should return CID with multicodec set to libp2p-key
expect(CID.parse(id.toString()).code).to.equal(LIBP2P_KEY_CODE)
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from CID Uint8Array', () => {
const id = PeerId.createFromBytes(testIdCID.bytes)
expect(testIdCIDString).to.equal(id.toString())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('throws on invalid CID multicodec', () => {
// only libp2p and dag-pb are supported
const invalidCID = CID.createV1(RAW_CODE, testIdDigest)
expect(() => {
PeerId.createFromCID(invalidCID)
}).to.throw(/invalid/i)
})
it('throws on invalid multihash value', () => {
// using function code 0x50 that does not represent valid hash function
// https://github.com/multiformats/js-multihash/blob/b85999d5768bf06f1b0f16b926ef2cb6d9c14265/src/constants.js#L345
const invalidMultihash = uint8ArrayToString(Uint8Array.from([0x50, 0x1, 0x0]), 'base58btc')
expect(() => {
PeerId.createFromB58String(invalidMultihash)
}).to.throw(/invalid/i)
})
it('throws on invalid CID object', () => {
const invalidCID = {}
expect(() => {
// @ts-expect-error invalid cid is invalid type
PeerId.createFromCID(invalidCID)
}).to.throw(/invalid/i)
})
it('recreate from a Public Key', async () => {
const id = await PeerId.createFromPubKey(testId.pubKey)
expect(testIdB58String).to.equal(id.toB58String())
expect(testIdBytes).to.deep.equal(id.toBytes())
})
it('recreate from a Private Key', async () => {
const id = await PeerId.createFromPrivKey(testId.privKey)
expect(testIdB58String).to.equal(id.toB58String())
const encoded = uint8ArrayFromString(testId.privKey, 'base64pad')
const id2 = await PeerId.createFromPrivKey(encoded)
expect(testIdB58String).to.equal(id2.toB58String())
expect(id.marshalPubKey()).to.deep.equal(id2.marshalPubKey())
})
it('recreate from Protobuf', async () => {
const id = await PeerId.createFromProtobuf(testId.marshaled)
expect(testIdB58String).to.equal(id.toB58String())
const encoded = uint8ArrayFromString(testId.privKey, 'base64pad')
const id2 = await PeerId.createFromPrivKey(encoded)
expect(testIdB58String).to.equal(id2.toB58String())
expect(id.marshalPubKey()).to.deep.equal(id2.marshalPubKey())
expect(uint8ArrayToString(id.marshal(), 'base16')).to.deep.equal(testId.marshaled)
})
it('recreate from embedded ed25519 key', async () => {
const key = '12D3KooWRm8J3iL796zPFi2EtGGtUJn58AG67gcqzMFHZnnsTzqD'
const id = await PeerId.parse(key)
expect(id.toB58String()).to.equal(key)
const expB58 = base58btc.encode((await identity.digest(id.pubKey.bytes)).bytes).slice(1)
expect(id.toB58String()).to.equal(expB58)
})
it('recreate from embedded secp256k1 key', async () => {
const key = '16Uiu2HAm5qw8UyXP2RLxQUx5KvtSN8DsTKz8quRGqGNC3SYiaB8E'
const id = await PeerId.parse(key)
expect(id.toB58String()).to.equal(key)
const expB58 = base58btc.encode((await identity.digest(id.pubKey.bytes)).bytes).slice(1)
expect(id.toB58String()).to.equal(expB58)
})
it('recreate from string key', async () => {
const key = 'QmRsooYQasV5f5r834NSpdUtmejdQcpxXkK6qsozZWEihC'
const id = await PeerId.parse(key)
expect(id.toB58String()).to.equal(key)
})
it('can be created from a Secp256k1 public key', async () => {
const privKey = await crypto.keys.generateKeyPair('secp256k1', 256)
const id = await PeerId.createFromPubKey(privKey.public.bytes)
const expB58 = base58btc.encode((await identity.digest(id.pubKey.bytes)).bytes).slice(1)
expect(id.toB58String()).to.equal(expB58)
})
it('can be created from a Secp256k1 private key', async () => {
const privKey = await crypto.keys.generateKeyPair('secp256k1', 256)
const id = await PeerId.createFromPrivKey(privKey.bytes)
const expB58 = base58btc.encode((await identity.digest(id.pubKey.bytes)).bytes).slice(1)
expect(id.toB58String()).to.equal(expB58)
})
it('Compare generated ID with one created from PubKey', async () => {
const id1 = await PeerId.create(testOpts)
const id2 = await PeerId.createFromPubKey(id1.marshalPubKey())
expect(id1.id).to.be.eql(id2.id)
})
it('Works with default options', async function () {
this.timeout(10000)
const id = await PeerId.create()
expect(id.toB58String().length).to.equal(46)
})
it('Non-default # of bits', async function () {
this.timeout(1000 * 60)
const shortId = await PeerId.create(testOpts)
const longId = await PeerId.create({ bits: 1024 })
expect(shortId.privKey.bytes.length).is.below(longId.privKey.bytes.length)
})
it('Pretty printing', async () => {
const id1 = await PeerId.create(testOpts)
const json = id1.toJSON()
const id2 = await PeerId.createFromPrivKey(json.privKey || 'invalid, should not happen')
expect(id1.toPrint()).to.be.eql(id2.toPrint())
expect(id1.toPrint()).to.equal('<peer.ID ' + id1.toB58String().substr(2, 6) + '>')
})
it('toBytes', () => {
const id = PeerId.createFromHexString(testIdHex)
expect(uint8ArrayToString(id.toBytes(), 'base16')).to.equal(uint8ArrayToString(testIdBytes, 'base16'))
})
it('isEqual', async () => {
const ids = await Promise.all([
PeerId.create(testOpts),
PeerId.create(testOpts)
])
expect(ids[0].isEqual(ids[0])).to.equal(true)
expect(ids[0].isEqual(ids[1])).to.equal(false)
expect(ids[0].isEqual(ids[0].id)).to.equal(true)
expect(ids[0].isEqual(ids[1].id)).to.equal(false)
})
it('equals', async () => {
const ids = await Promise.all([
PeerId.create(testOpts),
PeerId.create(testOpts)
])
expect(ids[0].equals(ids[0])).to.equal(true)
expect(ids[0].equals(ids[1])).to.equal(false)
expect(ids[0].equals(ids[0].id)).to.equal(true)
expect(ids[0].equals(ids[1].id)).to.equal(false)
})
describe('hasInlinePublicKey', () => {
it('returns true if uses a key type with inline public key', async () => {
const peerId = await PeerId.create({ keyType: 'secp256k1' })
expect(peerId.hasInlinePublicKey()).to.equal(true)
})
it('returns false if uses a key type with no inline public key', async () => {
const peerId = await PeerId.create({ keyType: 'RSA' })
expect(peerId.hasInlinePublicKey()).to.equal(false)
})
})
describe('fromJSON', () => {
it('full node', async () => {
const id = await PeerId.create(testOpts)
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)
})
it('only id', async () => {
const key = await crypto.keys.generateKeyPair('RSA', 1024)
const digest = await key.public.hash()
const id = PeerId.createFromBytes(digest)
expect(id.privKey).to.not.exist()
expect(id.pubKey).to.not.exist()
const other = await PeerId.createFromJSON(id.toJSON())
expect(id.toB58String()).to.equal(other.toB58String())
})
it('go interop', async () => {
const id = await PeerId.createFromJSON(goId)
const digest = await id.privKey.public.hash()
expect(base58btc.encode(digest).slice(1)).to.eql(goId.id)
})
})
it('set privKey (valid)', async () => {
const peerId = await PeerId.create(testOpts)
// @ts-ignore
peerId.privKey = peerId._privKey
expect(peerId.isValid()).to.equal(true)
})
it('set pubKey (valid)', async () => {
const peerId = await PeerId.create(testOpts)
// @ts-ignore
peerId.pubKey = peerId._pubKey
expect(peerId.isValid()).to.equal(true)
})
it('set privKey (invalid)', async () => {
const peerId = await PeerId.create(testOpts)
// @ts-ignore
peerId.privKey = uint8ArrayFromString('bufff')
expect(peerId.isValid()).to.equal(false)
})
it('set pubKey (invalid)', async () => {
const peerId = await PeerId.create(testOpts)
// @ts-ignore
peerId.pubKey = uint8ArrayFromString('bufff')
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'),
{}, null, false, undefined, true, 1, 0,
uint8ArrayFromString(''), 'aGVsbG93b3JsZA==', 'helloworld', ''
]
const fncs = ['createFromPubKey', 'createFromPrivKey', 'createFromJSON', 'createFromProtobuf']
for (const gb of garbage) {
for (const fn of fncs) {
it(`${fn} (${util.inspect(gb)})`, async () => {
try {
// @ts-expect-error cannot use a string to index PeerId
await PeerId[fn](gb)
} catch (err) {
expect(err).to.exist()
}
})
}
}
})
describe('throws on inconsistent data', () => {
/** @type {crypto.keys.supportedKeys.rsa.RsaPrivateKey} */
let k1
/** @type {crypto.keys.supportedKeys.rsa.RsaPrivateKey} */
let k2
/** @type {crypto.keys.supportedKeys.rsa.RsaPrivateKey} */
let k3
before(async () => {
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 () => {
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 () => {
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', () => {
// @ts-expect-error incorrect constructor arg type
expect(() => new PeerId('hello world')).to.throw(/invalid id/)
})
})
})