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 pathpubsub.js
199 lines (157 loc) · 5.93 KB
/
pubsub.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
/* eslint-env mocha */
'use strict'
const { getDescribe, getIt, expect } = require('../utils/mocha')
const PeerId = require('peer-id')
const { isNode } = require('ipfs-utils/src/env')
const ipns = require('ipns')
const delay = require('delay')
const last = require('it-last')
const waitFor = require('../utils/wait-for')
const { fromString: uint8ArrayFromString } = require('uint8arrays/from-string')
const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
const namespace = '/record/'
const ipfsRef = '/ipfs/QmPFVLPmp9zv5Z5KUqLhe2EivAGccQW2r7M7jhVJGLZoZU'
const daemonsOptions = {
ipfsOptions: {
EXPERIMENTAL: {
ipnsPubsub: true
}
}
}
/**
* @typedef {import('ipfsd-ctl').Factory} Factory
*/
/**
* @param {Factory} factory
* @param {Object} options
*/
module.exports = (factory, options) => {
const describe = getDescribe(options)
const it = getIt(options)
describe('.name.pubsub', () => {
// TODO make this work in the browser and between daemon and in-proc in nodes
if (!isNode) return
let nodes
/** @type {import('ipfs-core-types').IPFS} */
let nodeA
/** @type {import('ipfs-core-types').IPFS} */
let nodeB
/** @type {import('ipfs-core-types/src/root').IDResult} */
let idA
/** @type {import('ipfs-core-types/src/root').IDResult} */
let idB
before(async function () {
this.timeout(120 * 1000)
nodes = await Promise.all([
factory.spawn({ ...daemonsOptions }),
factory.spawn({ ...daemonsOptions })
])
nodeA = nodes[0].api
nodeB = nodes[1].api
const ids = await Promise.all([
nodeA.id(),
nodeB.id()
])
idA = ids[0]
idB = ids[1]
await nodeA.swarm.connect(idB.addresses[0])
})
after(() => factory.clean())
it('should publish and then resolve correctly', async function () {
// @ts-ignore this is mocha
this.timeout(80 * 1000)
let subscribed = false
/**
* @type {import('ipfs-core-types/src/pubsub').MessageHandlerFn}
*/
function checkMessage () {
subscribed = true
}
const alreadySubscribed = () => {
return subscribed === true
}
const keys = ipns.getIdKeys(uint8ArrayFromString(idA.id, 'base58btc'))
const topic = `${namespace}${uint8ArrayToString(keys.routingKey.uint8Array(), 'base64url')}`
await expect(last(nodeB.name.resolve(idA.id)))
.to.eventually.be.rejected()
.with.property('message').that.matches(/not found/)
await waitFor(async () => {
const res = await nodeA.pubsub.peers(topic)
return Boolean(res && res.length)
}, { name: `node A to subscribe to ${topic}` })
await nodeB.pubsub.subscribe(topic, checkMessage)
await nodeA.name.publish(ipfsRef, { resolve: false })
await waitFor(alreadySubscribed)
await delay(1000) // guarantee record is written
const res = await last(nodeB.name.resolve(idA.id))
expect(res).to.equal(ipfsRef)
})
it('should self resolve, publish and then resolve correctly', async function () {
// @ts-ignore this is mocha
this.timeout(6000)
const emptyDirCid = '/ipfs/QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn'
const { path } = await nodeA.add(uint8ArrayFromString('pubsub records'))
const resolvesEmpty = await last(nodeB.name.resolve(idB.id))
expect(resolvesEmpty).to.be.eq(emptyDirCid)
await expect(last(nodeA.name.resolve(idB.id)))
.to.eventually.be.rejected()
.with.property('message').that.matches(/not found/)
const publish = await nodeB.name.publish(path)
expect(publish).to.be.eql({
name: idB.id,
value: `/ipfs/${path}`
})
const resolveB = await last(nodeB.name.resolve(idB.id))
expect(resolveB).to.be.eq(`/ipfs/${path}`)
await delay(1000)
const resolveA = await last(nodeA.name.resolve(idB.id))
expect(resolveA).to.be.eq(`/ipfs/${path}`)
})
it('should handle event on publish correctly', async function () {
// @ts-ignore this is mocha
this.timeout(80 * 1000)
const testAccountName = 'test-account'
/**
* @type {import('ipfs-core-types/src/pubsub').Message}
*/
let publishedMessage
/**
* @type {import('ipfs-core-types/src/pubsub').MessageHandlerFn}
*/
function checkMessage (msg) {
publishedMessage = msg
}
const alreadySubscribed = () => {
return Boolean(publishedMessage)
}
// Create account for publish
const testAccount = await nodeA.key.gen(testAccountName, {
type: 'rsa',
size: 2048,
'ipns-base': 'b58mh'
})
const keys = ipns.getIdKeys(uint8ArrayFromString(testAccount.id, 'base58btc'))
const topic = `${namespace}${uint8ArrayToString(keys.routingKey.uint8Array(), 'base64url')}`
await nodeB.pubsub.subscribe(topic, checkMessage)
await nodeA.name.publish(ipfsRef, { resolve: false, key: testAccountName })
await waitFor(alreadySubscribed)
// @ts-ignore publishedMessage is set in handler
if (!publishedMessage) {
throw new Error('Pubsub handler not invoked')
}
const publishedMessageData = ipns.unmarshal(publishedMessage.data)
if (!publishedMessageData.pubKey) {
throw new Error('No public key found in message data')
}
const messageKey = await PeerId.createFromB58String(publishedMessage.from)
const pubKeyPeerId = await PeerId.createFromPubKey(publishedMessageData.pubKey)
expect(pubKeyPeerId.toB58String()).not.to.equal(messageKey.toB58String())
expect(pubKeyPeerId.toB58String()).to.equal(testAccount.id)
expect(publishedMessage.from).to.equal(idA.id)
expect(messageKey.toB58String()).to.equal(idA.id)
expect(uint8ArrayToString(publishedMessageData.value)).to.equal(ipfsRef)
// Verify the signature
await ipns.validate(pubKeyPeerId.pubKey, publishedMessageData)
})
})
}