-
Notifications
You must be signed in to change notification settings - Fork 105
/
index.ts
488 lines (423 loc) · 14.7 KB
/
index.ts
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/**
* @packageDocumentation
*
* IPNS operations using a Helia node
*
* @example Getting started
*
* With {@link IPNSRouting} routers:
*
* ```typescript
* import { createHelia } from 'helia'
* import { ipns } from '@helia/ipns'
* import { unixfs } from '@helia/unixfs'
*
* const helia = await createHelia()
* const name = ipns(helia)
*
* // create a public key to publish as an IPNS name
* const keyInfo = await helia.libp2p.services.keychain.createKey('my-key')
* const peerId = await helia.libp2p.services.keychain.exportPeerId(keyInfo.name)
*
* // store some data to publish
* const fs = unixfs(helia)
* const cid = await fs.add(Uint8Array.from([0, 1, 2, 3, 4]))
*
* // publish the name
* await name.publish(peerId, cid)
*
* // resolve the name
* const cid = name.resolve(peerId)
* ```
*
* @example Using custom PubSub router
*
* Additional IPNS routers can be configured - these enable alternative means to
* publish and resolve IPNS names.
*
* One example is the PubSub router - this requires an instance of Helia with
* libp2p PubSub configured.
*
* It works by subscribing to a pubsub topic for each IPNS name that we try to
* resolve. Updated IPNS records are shared on these topics so an update must
* occur before the name is resolvable.
*
* This router is only suitable for networks where IPNS updates are frequent
* and multiple peers are listening on the topic(s), otherwise update messages
* may fail to be published with "Insufficient peers" errors.
*
* ```typescript
* import { createHelia, libp2pDefaults } from 'helia'
* import { ipns } from '@helia/ipns'
* import { pubsub } from '@helia/ipns/routing'
* import { unixfs } from '@helia/unixfs'
* import { gossipsub } from '@chainsafe/libp2p-gossipsub'
*
* const libp2pOptions = libp2pDefaults()
* libp2pOptions.services.pubsub = gossipsub()
*
* const helia = await createHelia({
* libp2p: libp2pOptions
* })
* const name = ipns(helia, {
* routers: [
* pubsub(helia)
* ]
* })
*
* // create a public key to publish as an IPNS name
* const keyInfo = await helia.libp2p.services.keychain.createKey('my-key')
* const peerId = await helia.libp2p.services.keychain.exportPeerId(keyInfo.name)
*
* // store some data to publish
* const fs = unixfs(helia)
* const cid = await fs.add(Uint8Array.from([0, 1, 2, 3, 4]))
*
* // publish the name
* await name.publish(peerId, cid)
*
* // resolve the name
* const cid = name.resolve(peerId)
* ```
*
* @example Using custom DNS over HTTPS resolvers
*
* With default {@link DNSResolver} resolvers:
*
* ```typescript
* import { createHelia } from 'helia'
* import { ipns } from '@helia/ipns'
* import { unixfs } from '@helia/unixfs'
* import { dnsOverHttps } from '@helia/ipns/dns-resolvers'
*
* const helia = await createHelia()
* const name = ipns(helia, {
* resolvers: [
* dnsOverHttps('https://private-dns-server.me/dns-query'),
* ]
* })
*
* const cid = name.resolveDns('some-domain-with-dnslink-entry.com')
* ```
*
* @example Resolving a domain with a dnslink entry
*
* Calling `resolveDns` with the `@helia/ipns` instance:
*
* ```typescript
* // resolve a CID from a TXT record in a DNS zone file, using the default
* // resolver for the current platform eg:
* // > dig _dnslink.ipfs.io TXT
* // ;; ANSWER SECTION:
* // _dnslink.ipfs.io. 60 IN TXT "dnslink=/ipns/website.ipfs.io"
* // > dig _dnslink.website.ipfs.io TXT
* // ;; ANSWER SECTION:
* // _dnslink.website.ipfs.io. 60 IN TXT "dnslink=/ipfs/QmWebsite"
*
* const cid = name.resolveDns('ipfs.io')
*
* console.info(cid)
* // QmWebsite
* ```
*
* @example Using DNS-Over-HTTPS
*
* This example uses the Mozilla provided RFC 1035 DNS over HTTPS service. This
* uses binary DNS records so requires extra dependencies to process the
* response which can increase browser bundle sizes.
*
* If this is a concern, use the DNS-JSON-Over-HTTPS resolver instead.
*
* ```typescript
* // use DNS-Over-HTTPS
* import { dnsOverHttps } from '@helia/ipns/dns-resolvers'
*
* const cid = name.resolveDns('ipfs.io', {
* resolvers: [
* dnsOverHttps('https://mozilla.cloudflare-dns.com/dns-query')
* ]
* })
* ```
*
* @example Using DNS-JSON-Over-HTTPS
*
* DNS-JSON-Over-HTTPS resolvers use the RFC 8427 `application/dns-json` and can
* result in a smaller browser bundle due to the response being plain JSON.
*
* ```typescript
* // use DNS-JSON-Over-HTTPS
* import { dnsJsonOverHttps } from '@helia/ipns/dns-resolvers'
*
* const cid = name.resolveDns('ipfs.io', {
* resolvers: [
* dnsJsonOverHttps('https://mozilla.cloudflare-dns.com/dns-query')
* ]
* })
* ```
*/
import { CodeError } from '@libp2p/interface'
import { logger } from '@libp2p/logger'
import { peerIdFromString } from '@libp2p/peer-id'
import { create, marshal, peerIdToRoutingKey, unmarshal } from 'ipns'
import { ipnsSelector } from 'ipns/selector'
import { ipnsValidator } from 'ipns/validator'
import { CID } from 'multiformats/cid'
import { CustomProgressEvent } from 'progress-events'
import { defaultResolver } from './dns-resolvers/default.js'
import { helia } from './routing/helia.js'
import { localStore, type LocalStore } from './routing/local-store.js'
import type { IPNSRouting, IPNSRoutingEvents } from './routing/index.js'
import type { DNSResponse } from './utils/dns.js'
import type { Routing } from '@helia/interface'
import type { AbortOptions, PeerId } from '@libp2p/interface'
import type { Datastore } from 'interface-datastore'
import type { IPNSRecord } from 'ipns'
import type { ProgressEvent, ProgressOptions } from 'progress-events'
const log = logger('helia:ipns')
const MINUTE = 60 * 1000
const HOUR = 60 * MINUTE
const DEFAULT_LIFETIME_MS = 24 * HOUR
const DEFAULT_REPUBLISH_INTERVAL_MS = 23 * HOUR
export type PublishProgressEvents =
ProgressEvent<'ipns:publish:start'> |
ProgressEvent<'ipns:publish:success', IPNSRecord> |
ProgressEvent<'ipns:publish:error', Error>
export type ResolveProgressEvents =
ProgressEvent<'ipns:resolve:start', unknown> |
ProgressEvent<'ipns:resolve:success', IPNSRecord> |
ProgressEvent<'ipns:resolve:error', Error>
export type RepublishProgressEvents =
ProgressEvent<'ipns:republish:start', unknown> |
ProgressEvent<'ipns:republish:success', IPNSRecord> |
ProgressEvent<'ipns:republish:error', { record: IPNSRecord, err: Error }>
export type ResolveDnsLinkProgressEvents =
ProgressEvent<'dnslink:cache', string> |
ProgressEvent<'dnslink:query', string> |
ProgressEvent<'dnslink:answer', DNSResponse>
export interface PublishOptions extends AbortOptions, ProgressOptions<PublishProgressEvents | IPNSRoutingEvents> {
/**
* Time duration of the record in ms (default: 24hrs)
*/
lifetime?: number
/**
* Only publish to a local datastore (default: false)
*/
offline?: boolean
/**
* By default a IPNS V1 and a V2 signature is added to every record. Pass
* false here to only add a V2 signature. (default: true)
*/
v1Compatible?: boolean
}
export interface ResolveOptions extends AbortOptions, ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents> {
/**
* Do not query the network for the IPNS record (default: false)
*/
offline?: boolean
}
export interface ResolveDnsLinkOptions extends AbortOptions, ProgressOptions<ResolveDnsLinkProgressEvents> {
/**
* Do not use cached DNS entries (default: false)
*/
nocache?: boolean
}
export interface DNSResolver {
(domain: string, options?: ResolveDnsLinkOptions): Promise<string>
}
export interface ResolveDNSOptions extends AbortOptions, ProgressOptions<ResolveProgressEvents | IPNSRoutingEvents | ResolveDnsLinkProgressEvents> {
/**
* Do not query the network for the IPNS record (default: false)
*/
offline?: boolean
/**
* Do not use cached DNS entries (default: false)
*/
nocache?: boolean
/**
* These resolvers will be used to resolve the dnslink entries, if unspecified node will
* fall back to the `dns` module and browsers fall back to querying google/cloudflare DoH
*
* @see https://github.com/ipfs/helia-ipns/pull/55#discussion_r1270096881
*/
resolvers?: DNSResolver[]
}
export interface RepublishOptions extends AbortOptions, ProgressOptions<RepublishProgressEvents | IPNSRoutingEvents> {
/**
* The republish interval in ms (default: 23hrs)
*/
interval?: number
}
export interface IPNS {
/**
* Creates an IPNS record signed by the passed PeerId that will resolve to the passed value
*
* If the value is a PeerId, a recursive IPNS record will be created.
*/
publish(key: PeerId, value: CID | PeerId, options?: PublishOptions): Promise<IPNSRecord>
/**
* Accepts a public key formatted as a libp2p PeerID and resolves the IPNS record
* corresponding to that public key until a value is found
*/
resolve(key: PeerId, options?: ResolveOptions): Promise<CID>
/**
* Resolve a CID from a dns-link style IPNS record
*/
resolveDns(domain: string, options?: ResolveDNSOptions): Promise<CID>
/**
* Periodically republish all IPNS records found in the datastore
*/
republish(options?: RepublishOptions): void
}
export type { IPNSRouting } from './routing/index.js'
export interface IPNSComponents {
datastore: Datastore
routing: Routing
}
class DefaultIPNS implements IPNS {
private readonly routers: IPNSRouting[]
private readonly localStore: LocalStore
private timeout?: ReturnType<typeof setTimeout>
private readonly defaultResolvers: DNSResolver[]
constructor (components: IPNSComponents, routers: IPNSRouting[] = [], resolvers: DNSResolver[] = []) {
this.routers = [
helia(components.routing),
...routers
]
this.localStore = localStore(components.datastore)
this.defaultResolvers = resolvers.length > 0 ? resolvers : [defaultResolver()]
}
async publish (key: PeerId, value: CID | PeerId, options: PublishOptions = {}): Promise<IPNSRecord> {
try {
let sequenceNumber = 1n
const routingKey = peerIdToRoutingKey(key)
if (await this.localStore.has(routingKey, options)) {
// if we have published under this key before, increment the sequence number
const buf = await this.localStore.get(routingKey, options)
const existingRecord = unmarshal(buf)
sequenceNumber = existingRecord.sequence + 1n
}
// create record
const record = await create(key, value, sequenceNumber, options.lifetime ?? DEFAULT_LIFETIME_MS, options)
const marshaledRecord = marshal(record)
await this.localStore.put(routingKey, marshaledRecord, options)
if (options.offline !== true) {
// publish record to routing
await Promise.all(this.routers.map(async r => { await r.put(routingKey, marshaledRecord, options) }))
}
return record
} catch (err: any) {
options.onProgress?.(new CustomProgressEvent<Error>('ipns:publish:error', err))
throw err
}
}
async resolve (key: PeerId, options: ResolveOptions = {}): Promise<CID> {
const routingKey = peerIdToRoutingKey(key)
const record = await this.#findIpnsRecord(routingKey, options)
return this.#resolve(record.value, options)
}
async resolveDns (domain: string, options: ResolveDNSOptions = {}): Promise<CID> {
const resolvers = options.resolvers ?? this.defaultResolvers
const dnslink = await Promise.any(
resolvers.map(async resolver => resolver(domain, options))
)
return this.#resolve(dnslink, options)
}
republish (options: RepublishOptions = {}): void {
if (this.timeout != null) {
throw new Error('Republish is already running')
}
options.signal?.addEventListener('abort', () => {
clearTimeout(this.timeout)
})
async function republish (): Promise<void> {
const startTime = Date.now()
options.onProgress?.(new CustomProgressEvent('ipns:republish:start'))
const finishType = Date.now()
const timeTaken = finishType - startTime
let nextInterval = DEFAULT_REPUBLISH_INTERVAL_MS - timeTaken
if (nextInterval < 0) {
nextInterval = options.interval ?? DEFAULT_REPUBLISH_INTERVAL_MS
}
setTimeout(() => {
republish().catch(err => {
log.error('error republishing', err)
})
}, nextInterval)
}
this.timeout = setTimeout(() => {
republish().catch(err => {
log.error('error republishing', err)
})
}, options.interval ?? DEFAULT_REPUBLISH_INTERVAL_MS)
}
async #resolve (ipfsPath: string, options: ResolveOptions = {}): Promise<CID> {
const parts = ipfsPath.split('/')
if (parts.length === 3) {
const scheme = parts[1]
if (scheme === 'ipns') {
return this.resolve(peerIdFromString(parts[2]), options)
} else if (scheme === 'ipfs') {
return CID.parse(parts[2])
}
}
log.error('invalid ipfs path %s', ipfsPath)
throw new Error('Invalid value')
}
async #findIpnsRecord (routingKey: Uint8Array, options: ResolveOptions = {}): Promise<IPNSRecord> {
let routers = [
this.localStore,
...this.routers
]
if (options.offline === true) {
routers = [
this.localStore
]
}
const records: Uint8Array[] = []
let foundInvalid = 0
await Promise.all(
routers.map(async (router) => {
let record: Uint8Array
try {
record = await router.get(routingKey, {
...options,
validate: false
})
} catch (err: any) {
if (router === this.localStore && err.code === 'ERR_NOT_FOUND') {
log('did not have record locally')
} else {
log.error('error finding IPNS record', err)
}
return
}
try {
await ipnsValidator(routingKey, record)
records.push(record)
} catch (err) {
// we found a record, but the validator rejected it
foundInvalid++
log.error('error finding IPNS record', err)
}
})
)
if (records.length === 0) {
if (foundInvalid > 0) {
throw new CodeError(`${foundInvalid > 1 ? `${foundInvalid} records` : 'Record'} found for routing key ${foundInvalid > 1 ? 'were' : 'was'} invalid`, 'ERR_RECORDS_FAILED_VALIDATION')
}
throw new CodeError('Could not find record for routing key', 'ERR_NOT_FOUND')
}
const record = records[ipnsSelector(routingKey, records)]
await this.localStore.put(routingKey, record, options)
return unmarshal(record)
}
}
export interface IPNSOptions {
routers?: IPNSRouting[]
resolvers?: DNSResolver[]
}
export function ipns (components: IPNSComponents, { routers = [], resolvers = [] }: IPNSOptions = {}): IPNS {
return new DefaultIPNS(components, routers, resolvers)
}
export { ipnsValidator, type IPNSRoutingEvents }
export { ipnsSelector } from 'ipns/selector'