This repository was archived by the owner on Feb 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathid.js
76 lines (65 loc) · 2.44 KB
/
id.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
'use strict'
const pkgversion = require('../../package.json').version
const { Multiaddr } = require('multiaddr')
const withTimeoutOption = require('ipfs-core-utils/src/with-timeout-option')
const uint8ArrayToString = require('uint8arrays/to-string')
const PeerId = require('peer-id')
const { NotStartedError } = require('../errors')
/**
* @param {Object} config
* @param {import('peer-id')} config.peerId
* @param {import('../types').NetworkService} config.network
*/
module.exports = ({ peerId, network }) => {
/**
* @type {import('ipfs-core-types/src/root').API["id"]}
*/
async function id (options = {}) { // eslint-disable-line require-await
if (options.peerId === peerId.toB58String()) {
delete options.peerId
}
const net = network.try()
if (!net) {
if (options.peerId) {
throw new NotStartedError()
}
const idStr = peerId.toB58String()
return {
id: idStr,
publicKey: uint8ArrayToString(peerId.pubKey.bytes, 'base64pad'),
addresses: [],
agentVersion: `js-ipfs/${pkgversion}`,
protocolVersion: '9000',
protocols: []
}
}
const id = options.peerId ? PeerId.createFromB58String(options.peerId.toString()) : peerId
const { libp2p } = net
const publicKey = options.peerId ? libp2p.peerStore.keyBook.get(id) : id.pubKey
const addresses = options.peerId ? libp2p.peerStore.addressBook.getMultiaddrsForPeer(id) : libp2p.multiaddrs
const protocols = options.peerId ? libp2p.peerStore.protoBook.get(id) : Array.from(libp2p.upgrader.protocols.keys())
const agentVersion = uint8ArrayToString(libp2p.peerStore.metadataBook.getValue(id, 'AgentVersion') || new Uint8Array())
const protocolVersion = uint8ArrayToString(libp2p.peerStore.metadataBook.getValue(id, 'ProtocolVersion') || new Uint8Array())
const idStr = id.toB58String()
return {
id: idStr,
publicKey: uint8ArrayToString(publicKey.bytes, 'base64pad'),
addresses: (addresses || [])
.map(ma => {
const str = ma.toString()
// some relay-style transports add our peer id to the ma for us
// so don't double-add
if (str.endsWith(`/p2p/${idStr}`)) {
return str
}
return `${str}/p2p/${idStr}`
})
.sort()
.map(ma => new Multiaddr(ma)),
agentVersion,
protocolVersion,
protocols: (protocols || []).sort()
}
}
return withTimeoutOption(id)
}