This repository has been archived by the owner on Mar 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 299
/
find-peer.js
49 lines (42 loc) · 1.72 KB
/
find-peer.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
'use strict'
const { Buffer } = require('buffer')
const CID = require('cids')
const multiaddr = require('multiaddr')
const ndjson = require('iterable-ndjson')
const configure = require('../lib/configure')
const toIterable = require('stream-to-it/source')
module.exports = configure(({ ky }) => {
return async function findPeer (peerId, options) {
options = options || {}
const searchParams = new URLSearchParams(options.searchParams)
searchParams.set('arg', `${Buffer.isBuffer(peerId) ? new CID(peerId) : peerId}`)
if (options.verbose != null) searchParams.set('verbose', options.verbose)
const res = await ky.post('dht/findpeer', {
timeout: options.timeout,
signal: options.signal,
headers: options.headers,
searchParams
})
for await (const message of ndjson(toIterable(res.body))) {
// 3 = QueryError
// https://github.com/libp2p/go-libp2p-core/blob/6e566d10f4a5447317a66d64c7459954b969bdab/routing/query.go#L18
// https://github.com/ipfs/go-ipfs/blob/eb11f569b064b960d1aba4b5b8ca155a3bd2cb21/core/commands/dht.go#L388-L389
if (message.Type === 3) {
throw new Error(message.Extra)
}
// 2 = FinalPeer
// https://github.com/libp2p/go-libp2p-core/blob/6e566d10f4a5447317a66d64c7459954b969bdab/routing/query.go#L18
if (message.Type === 2 && message.Responses) {
// There will only be 1:
// https://github.com/ipfs/go-ipfs/blob/eb11f569b064b960d1aba4b5b8ca155a3bd2cb21/core/commands/dht.go#L395-L396
for (const { ID, Addrs } of message.Responses) {
return {
id: ID,
addrs: (Addrs || []).map(a => multiaddr(a))
}
}
}
}
throw new Error('not found')
}
})