@cero-base/cero 2.3.3 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -3,6 +3,7 @@ import HypercoreStorage from 'hypercore-storage'
3
3
  import Corestore from 'corestore'
4
4
  import safetyCatch from 'safety-catch'
5
5
  import c from 'compact-encoding'
6
+ import b4a from 'b4a'
6
7
  import fs from 'fs'
7
8
 
8
9
  import { Identity } from '@cero-base/core/identity'
@@ -28,23 +29,20 @@ export { t, schema } from './lib/spec.js'
28
29
 
29
30
  /**
30
31
  * @typedef {object} CeroOpts
31
- * @property {Identity} [identity] Pre-resolved identity. If absent, derived from `seed` or generated.
32
- * @property {Uint8Array} [seed] 16- or 32-byte seed entropy: `toSeed(phrase)` restores from a phrase.
32
+ * @property {string} [phrase] The identity's BIP-39 phrase, as `cero.phrase(me)` gives it: on a new `dir` it recovers that identity.
33
33
  * @property {12 | 24} [words] Mnemonic length when generating a fresh identity.
34
34
  * @property {string | null} [name] Friendly device name persisted on the identity claim.
35
35
  * @property {boolean} [isMobile] Marks this device as mobile.
36
36
  * @property {Array<{ host: string, port: number }>} [bootstrap] Custom DHT bootstrap nodes.
37
37
  * @property {number[]} [backoffs] Swarm reconnect backoff tiers in ms (testing/tuning).
38
38
  * @property {string} [channel] Optional network-isolation label; only same-channel peers connect.
39
- * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Rooms and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
40
- * @property {{ active?: number, announced?: number, idle?: number }} [presence] How many rooms search, how many only announce, and the idle ms before the rest leave the swarm.
41
- * @property {Uint8Array} [key] Existing database key to recover into, skipping the pointer lookup.
42
- * @property {Uint8Array} [encryptionKey] Pre-existing encryption key.
39
+ * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Handles and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
40
+ * @property {{ active?: number, announced?: number, idle?: number }} [presence] How many handles search, how many only announce, and the idle ms before the rest leave the swarm.
43
41
  * @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
44
42
  * @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
45
43
  * @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
46
44
  * @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
47
- * @property {boolean | { autoStart?: boolean, backend?: object, maxOutbound?: number, maxInbound?: number, pipe?: 'l2cap' | 'gatt' }} [bluetooth] `true` enables nearby (Bluetooth) sync, the radio on. `{ autoStart: false }` leaves it off until `cero.nearby(me, true)`. `backend` injects a bare-bluetooth-shaped backend (tests). `maxOutbound`/`maxInbound` cap concurrent outbound links and inbound sessions. `pipe` picks the data pipe, `'l2cap'` (default, faster) or `'gatt'`; both peers must match. Without a backend on the host, `me.status` reports `nearby: 'unsupported'`.
45
+ * @property {{ on?: boolean, topic?: string, backend?: object | null, maxOutbound?: number, maxInbound?: number, pipe?: 'l2cap' | 'gatt' }} [bluetooth] Bluetooth at start: `on` (off by default) and `topic` (the default one, else the channel's own); the app turns the radio on and off with `cero.nearby`, and nothing is stored. `maxOutbound`/`maxInbound` cap concurrent outbound links and inbound sessions. `pipe` picks the data pipe, `'l2cap'` (default, faster) or `'gatt'`; both peers must match. `backend` injects a bare-bluetooth-shaped backend (tests); with none on the host, `status.nearby` reads `'unsupported'`.
48
46
  */
49
47
 
50
48
  /**
@@ -58,6 +56,10 @@ export { t, schema } from './lib/spec.js'
58
56
  async function start(dir, spec, opts = {}) {
59
57
  if (typeof dir !== 'string' || !dir) throw CeroError.INVALID('dir must be a non-empty string')
60
58
  if (!spec) throw CeroError.REQUIRED('spec')
59
+ const bt = opts.bluetooth ?? {}
60
+ if (typeof bt !== 'object') {
61
+ throw CeroError.INVALID('bluetooth takes { on, topic, pipe, maxOutbound, maxInbound }')
62
+ }
61
63
 
62
64
  const storage = new HypercoreStorage(`${dir}/main`)
63
65
  let store = null
@@ -82,17 +84,14 @@ async function start(dir, spec, opts = {}) {
82
84
  session.on('conflict', () => onerror(CeroError.CONFLICT(`fork on core ${session.id}`)))
83
85
  })
84
86
 
85
- if (spec.local && spec.meta?.local) {
86
- local = new Local(null, spec, { store, storageKey: opts.storageKey })
87
- await local.ready()
88
- }
87
+ local = new Local(null, spec, { store, storageKey: opts.storageKey })
88
+ await local.ready()
89
89
 
90
- const { identity, fresh, seed } = await resolveIdentity(opts, local)
91
- const device = local ? (await local.store.get('keypair')).data : null
90
+ const device = (await local.store.get('keypair')).data
92
91
  const done = !!device && !device.setup
92
+ const { identity, fresh, seed } = await resolveIdentity(opts, local, done)
93
93
  // cero creates only an identity it minted, in this launch or in the killed one it resumes
94
- const creating =
95
- !done && !opts.key && !opts.seed && !opts.identity && (fresh || device?.setup === 'create')
94
+ const creating = !done && !opts.phrase && (fresh || device?.setup === 'create')
96
95
  const recovering = !done && !creating
97
96
  const setup = done ? null : creating ? 'create' : 'recover'
98
97
  const keyPair =
@@ -100,20 +99,18 @@ async function start(dir, spec, opts = {}) {
100
99
  ? { publicKey: device.publicKey, secretKey: device.secretKey }
101
100
  : Identity.randomKeyPair()
102
101
  // the key before the seed: a seed stored without its create would read as one to recover
103
- if (local && !done && device?.setup !== setup) {
102
+ if (!done && device?.setup !== setup) {
104
103
  await local.store.set('keypair', { ...keyPair, setup })
105
104
  }
106
- if (local && seed) await local.store.set('master', { seed })
105
+ if (seed) await local.store.set('master', { seed })
107
106
  const timeout = opts.recoveryTimeout || TIMEOUT
108
107
 
109
108
  // a storage remembers its channel; reopening under another would silently rejoin the global network
110
- if (local) {
111
- const stored = (await local.store.get('environment')).data?.channel ?? null
112
- const wanted = opts.channel ?? null
113
- if (stored == null && wanted != null) {
114
- await local.store.set('environment', { channel: wanted })
115
- } else if (stored != null && stored !== wanted) throw CeroError.CHANNEL_MISMATCH()
116
- }
109
+ const stored = (await local.store.get('environment')).data?.channel ?? null
110
+ const wanted = opts.channel ?? null
111
+ if (stored == null && wanted != null) {
112
+ await local.store.set('environment', { channel: wanted })
113
+ } else if (stored != null && stored !== wanted) throw CeroError.CHANNEL_MISMATCH()
117
114
 
118
115
  network = new Network({
119
116
  bootstrap: opts.bootstrap,
@@ -126,20 +123,8 @@ async function start(dir, spec, opts = {}) {
126
123
  })
127
124
  await network.ready()
128
125
  // the radio before the pointer read: a phrase recovers from a device in range, no internet
129
- if (opts.bluetooth) {
130
- const bt = opts.bluetooth === true ? {} : opts.bluetooth
131
- bluetooth = new Bluetooth(network, {
132
- identity,
133
- keyPair,
134
- // an omitted backend lazy-loads bare-bluetooth, null disables it
135
- backend: bt.backend,
136
- autoStart: bt.autoStart !== false,
137
- maxOutbound: bt.maxOutbound,
138
- maxInbound: bt.maxInbound,
139
- pipe: bt.pipe
140
- })
141
- await bluetooth.ready()
142
- }
126
+ bluetooth = new Bluetooth(network, { ...bt, identity, keyPair })
127
+ await bluetooth.ready()
143
128
  discovery = network.join(identity.topic)
144
129
  // a fresh identity has no peers yet, flushing the announce would only delay onboarding
145
130
  if (!fresh) await Promise.race([discovery.flush(), new Promise((r) => setTimeout(r, FLUSH))])
@@ -154,7 +139,7 @@ async function start(dir, spec, opts = {}) {
154
139
  await pointer.ready()
155
140
  network.attach(pointer)
156
141
 
157
- const key = opts.key || (recovering ? await readPointer(pointer, timeout) : undefined)
142
+ const key = recovering ? await readPointer(pointer, timeout) : undefined
158
143
 
159
144
  me = new Handle({
160
145
  storage,
@@ -167,10 +152,8 @@ async function start(dir, spec, opts = {}) {
167
152
  opts,
168
153
  dir,
169
154
  key,
170
- encryptionKey: opts.encryptionKey,
171
155
  keyPair,
172
156
  bluetooth,
173
- pair: false,
174
157
  bootstrap: done
175
158
  ? null
176
159
  : { name: opts.name || null, isMobile: opts.isMobile === true, recovering, timeout }
@@ -179,16 +162,13 @@ async function start(dir, spec, opts = {}) {
179
162
  const setups = Promise.all(me.extensions.map(async (ext) => ext.setup?.(me)))
180
163
  setups.catch(() => {}) // a failed setup surfaces below, once the root can close
181
164
  await me.ready()
182
- me.once('close', () => {
183
- network.detach(pointer)
184
- pointer.close().catch(safetyCatch)
185
- })
165
+ me.once('close', () => pointer.close().catch(safetyCatch))
186
166
 
187
167
  if (!done) {
188
168
  if (creating && pointer.length === 0) {
189
169
  await pointer.append(c.encode(c.fixed32, me.store.key))
190
170
  }
191
- if (local) await local.store.set('keypair', { setup: null })
171
+ await local.store.set('keypair', { setup: null })
192
172
  }
193
173
 
194
174
  for (const off of await setups) {
@@ -213,46 +193,31 @@ async function start(dir, spec, opts = {}) {
213
193
  }
214
194
 
215
195
  /**
216
- * Restore a cero instance from a seed.
196
+ * Restore a cero instance from a recovery phrase.
217
197
  *
218
198
  * @param {Context} me The root to restore.
219
- * @param {Uint8Array} seed The identity's seed: `toSeed(phrase)` from a phrase.
199
+ * @param {string} phrase The identity's BIP-39 phrase, as `cero.phrase(me)` gives it.
220
200
  * @returns {Promise<Handle>} Freshly restored root handle.
221
201
  */
222
- export async function restore(me, seed) {
202
+ export async function restore(me, phrase) {
223
203
  if (!me?._dir) throw CeroError.INVALID('me must be a cero instance')
224
- // no seed would mint a fresh identity and wipe this one
225
- if (!seed) throw CeroError.REQUIRED('seed')
204
+ if (!phrase) throw CeroError.REQUIRED('phrase')
226
205
 
227
- const current = await Identity.create({ seed })
206
+ const current = await Identity.create({ seed: Identity.toSeed(phrase) })
228
207
  if (current.id === me.identity.id) return me
229
208
 
230
209
  // everything carries over except the identity, the channel above all
231
- const {
232
- _dir: dir,
233
- spec,
234
- _opts: { identity, key, keyPair, ...opts }
235
- } = me
210
+ const { _dir: dir, spec, _opts: opts } = me
236
211
 
237
212
  await me.close()
238
213
  await fs.promises.rm(`${dir}/main`, { recursive: true, force: true })
239
214
 
240
- return start(dir, spec, { ...opts, seed })
241
- }
242
-
243
- /**
244
- * The seed a BIP-39 phrase writes out, for `cero(dir, spec, { seed })` and `restore(me, seed)`.
245
- *
246
- * @param {string} phrase
247
- * @returns {Uint8Array}
248
- */
249
- export function toSeed(phrase) {
250
- return Identity.toSeed(phrase)
215
+ return start(dir, spec, { ...opts, phrase })
251
216
  }
252
217
 
253
218
  // the facade: cero.put and import { put } are the same function
254
- /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore, toSeed: typeof toSeed }} */
255
- export const cero = Object.assign(start, verbs, { t, schema, peek, restore, toSeed })
219
+ /** @type {typeof start & typeof verbs & { t: typeof t, schema: typeof schema, peek: typeof peek, restore: typeof restore }} */
220
+ export const cero = Object.assign(start, verbs, { t, schema, peek, restore })
256
221
 
257
222
  function pointerManifest(store, identity) {
258
223
  return { version: store.manifestVersion, signers: [{ publicKey: identity.publicKey }] }
@@ -267,11 +232,13 @@ async function readPointer(pointer, timeout) {
267
232
  }
268
233
 
269
234
  // `seed` is the one to store: supplied or minted, null when already stored
270
- async function resolveIdentity(opts, local) {
271
- if (opts.identity) return { identity: opts.identity, fresh: false, seed: null }
272
-
273
- const provided = opts.seed
274
- const stored = !provided && local && (await local.store.get('master')).data?.seed
235
+ async function resolveIdentity(opts, local, done) {
236
+ const provided = opts.phrase ? Identity.toSeed(opts.phrase) : null
237
+ const stored = (await local.store.get('master')).data?.seed
238
+ // another identity comes in only through restore, which wipes this one first
239
+ if (done && provided && !b4a.equals(provided, stored)) {
240
+ throw CeroError.INVALID('dir holds another identity: switch with cero.restore')
241
+ }
275
242
  const identity = await Identity.create({ seed: provided || stored || null, words: opts.words })
276
- return { identity, fresh: !provided && !stored, seed: stored ? null : identity.seed }
243
+ return { identity, fresh: !provided && !stored, seed: stored && !provided ? null : identity.seed }
277
244
  }
@@ -1,12 +1,13 @@
1
1
  import ReadyResource from 'ready-resource'
2
2
  import BluetoothSwarm from 'ble-swarm'
3
+ import Protomux from 'protomux'
4
+ import c from 'compact-encoding'
3
5
  import crypto from 'hypercore-crypto'
4
- import safetyCatch from 'safety-catch'
5
6
  import b4a from 'b4a'
6
7
  import hid from 'hypercore-id-encoding'
7
8
 
8
9
  import { Identity } from '@cero-base/core/identity'
9
- import { Invite } from '@cero-base/core/invite'
10
+ import { CeroError } from '@cero-base/core/errors'
10
11
 
11
12
  // what a person signs to claim one of its devices: the key that device links with
12
13
  const DEVICE = b4a.from('cero/device')
@@ -24,25 +25,34 @@ export class Bluetooth extends ReadyResource {
24
25
  * @param {import('@cero-base/core/identity').Identity} opts.identity Signs this device's key for the peers it links with.
25
26
  * @param {import('@cero-base/core/identity').KeyPair} opts.keyPair This device's writer keypair.
26
27
  * @param {object | null} [opts.backend] Injected bare-bluetooth-shaped backend (tests); omitted → ble-swarm loads its own, null/false → unsupported.
27
- * @param {boolean} [opts.autoStart] Start on open (from `cero({ bluetooth: true })`).
28
+ * @param {boolean} [opts.on] The radio at open; off unless `true`. Nothing is stored.
29
+ * @param {string} [opts.topic] The default topic; without one, the channel's own.
28
30
  * @param {number} [opts.maxOutbound] Max concurrent outbound links; gossip covers the rest.
29
31
  * @param {number} [opts.maxInbound] Max concurrent inbound sessions; newcomers past this are refused.
30
32
  * @param {'l2cap' | 'gatt'} [opts.pipe] Data pipe — 'l2cap' (default, faster) or 'gatt'. Both peers must match.
31
33
  */
32
- constructor(network, { identity, keyPair, backend, autoStart, maxOutbound, maxInbound, pipe }) {
34
+ constructor(network, opts) {
35
+ const { identity, keyPair, backend, on = false, topic, maxOutbound, maxInbound, pipe } = opts
36
+ if (typeof on !== 'boolean') throw CeroError.INVALID('on is true or false')
37
+ checkTopic(topic)
33
38
  super()
34
39
  /** @private */
35
- this._network = network
40
+ this._on = on
41
+ // what this device tells its links, signed, and what each link told, by its key
36
42
  /** @private */
37
- this._autoStart = autoStart === true
38
- /** @type {{ hex: string, count: number, timer: ReturnType<typeof setTimeout> | null } | null} active invite rendezvous (single topic — one at a time) */
39
- this._announce = null
43
+ this._info = null
40
44
  /** @private */
41
- this._restorePending = false
42
-
43
- // one mesh topic per channel, or a global one when channelless; strangers still sync nothing
45
+ this._heard = new Map()
46
+ /** @private */
47
+ this._senders = new Set()
48
+ // the link each peer's info came over: a newer one replaces it, and only the current one forgets
49
+ /** @private */
50
+ this._links = new Map()
51
+ // the channel's own topic, or a global one when channelless; strangers still sync nothing
44
52
  /** @private */
45
- this._topic = crypto.hash(b4a.from(network.channel || 'cero-ble'))
53
+ this._base = crypto.hash(b4a.from(network.channel || 'cero-ble'))
54
+ /** @private */
55
+ this._topic = topicOf(this._base, topic)
46
56
  /** @private */
47
57
  this._id = identity.id
48
58
  /** @private */
@@ -59,17 +69,8 @@ export class Bluetooth extends ReadyResource {
59
69
  maxOutbound,
60
70
  maxInbound
61
71
  })
62
- this.swarm.on('update', () => {
63
- // retune to the mesh only once the pairing link's initial replication drained
64
- if (this._restorePending && this.swarm.peers.size === 0) {
65
- this._restorePending = false
66
- this.swarm.setTopic(this._topic).catch(safetyCatch)
67
- }
68
- this.emit('update')
69
- })
70
- this.swarm.on('connection', (conn) => {
71
- network.inject(conn)
72
- })
72
+ this.swarm.on('update', () => this.emit('update'))
73
+ this.swarm.on('connection', (conn) => this._attach(network.inject(conn)))
73
74
  }
74
75
 
75
76
  /** @returns {'unsupported'|'unauthorized'|'off'|'waiting'|'starting'|'on'} */
@@ -84,12 +85,33 @@ export class Bluetooth extends ReadyResource {
84
85
 
85
86
  /** @private */
86
87
  async _open() {
87
- if (this._autoStart) await this.start()
88
+ if (this._on) await this.start()
89
+ }
90
+
91
+ /**
92
+ * Turn the radio on or off, on `opts.topic` or else the default topic. A new topic drops the
93
+ * links on the old one.
94
+ *
95
+ * @param {boolean} on
96
+ * @param {{ topic?: string }} [opts]
97
+ * @returns {Promise<void>}
98
+ */
99
+ async set(on, opts = {}) {
100
+ if (typeof on !== 'boolean') {
101
+ throw CeroError.INVALID('nearby takes true or false, then { topic }')
102
+ }
103
+ if (!opts || typeof opts !== 'object' || Object.keys(opts).some((k) => k !== 'topic')) {
104
+ throw CeroError.INVALID('nearby takes { topic } after true or false')
105
+ }
106
+ checkTopic(opts.topic)
107
+ const topic = opts.topic === undefined ? this._topic : topicOf(this._base, opts.topic)
108
+ if (!on) await this.stop()
109
+ await this.swarm.setTopic(topic)
110
+ if (on) await this.start()
88
111
  }
89
112
 
90
113
  /** @private */
91
114
  async _close() {
92
- this._clearAnnounce()
93
115
  await this.swarm.destroy()
94
116
  }
95
117
 
@@ -99,7 +121,13 @@ export class Bluetooth extends ReadyResource {
99
121
  * @param {{ name: string | null, isMobile: boolean }} info
100
122
  */
101
123
  tell({ name, isMobile }) {
102
- this._network.setInfo({ id: this._id, proof: this._proof, name, isMobile })
124
+ this._say({ id: this._id, proof: this._proof, name, isMobile })
125
+ }
126
+
127
+ /** @private */
128
+ _say(info) {
129
+ this._info = info
130
+ for (const send of this._senders) send()
103
131
  }
104
132
 
105
133
  /**
@@ -110,7 +138,7 @@ export class Bluetooth extends ReadyResource {
110
138
  * @returns {{ id: string, name: string | null, isMobile: boolean } | null}
111
139
  */
112
140
  told(hex) {
113
- const info = this._network.getInfo(hex)
141
+ const info = this._heard.get(hex)
114
142
  if (!signed(info, b4a.from(hex, 'hex'))) return null
115
143
  const name = typeof info.name === 'string' ? info.name : null
116
144
  return {
@@ -131,57 +159,12 @@ export class Bluetooth extends ReadyResource {
131
159
  }
132
160
 
133
161
  /**
134
- * Stop advertising/scanning and drop links; open invite rendezvous end with the radio.
162
+ * Stop advertising/scanning and drop links.
135
163
  *
136
164
  * @returns {Promise<void>}
137
165
  */
138
166
  async stop() {
139
- this._clearAnnounce()
140
167
  await this.swarm.stop()
141
- // while stopped setTopic sticks; a start() + announce() during the await wins
142
- if (!this._announce) await this.swarm.setTopic(this._topic)
143
- }
144
-
145
- /**
146
- * Offline join rendezvous: retune the radio to the invite-derived topic so holder and
147
- * joiner find each other with zero DHT.
148
- *
149
- * @param {string} invite Z32 invite string.
150
- * @returns {() => void}
151
- */
152
- announce(invite) {
153
- if (!this.swarm.supported) return () => {}
154
- if (this.state !== 'on' && this.state !== 'waiting' && this.state !== 'starting') {
155
- return () => {}
156
- }
157
- let parsed
158
- try {
159
- parsed = Invite.parse(invite)
160
- } catch {
161
- return () => {}
162
- }
163
-
164
- const hex = b4a.toHex(parsed.discoveryKey)
165
- if (this._announce && this._announce.hex !== hex) this._stopAnnounce()
166
- if (!this._announce) {
167
- const entry = { hex, count: 0, timer: null }
168
- const { expires } = parsed
169
- if (expires > 0) {
170
- entry.timer = setTimeout(() => this._stopAnnounce(), Math.max(0, expires - Date.now()))
171
- }
172
- this._announce = entry
173
- this._restorePending = false
174
- this.swarm.setTopic(parsed.discoveryKey).catch(safetyCatch)
175
- }
176
- const entry = this._announce
177
- entry.count++
178
-
179
- let stopped = false
180
- return () => {
181
- if (stopped) return
182
- stopped = true
183
- if (this._announce === entry && --entry.count <= 0) this._stopAnnounce()
184
- }
185
168
  }
186
169
 
187
170
  /**
@@ -202,23 +185,52 @@ export class Bluetooth extends ReadyResource {
202
185
  await this.swarm.resume()
203
186
  }
204
187
 
188
+ // silent until needed: bytes on a link at open trip hyperswarm's duplicate guard
205
189
  /** @private */
206
- _stopAnnounce() {
207
- this._clearAnnounce()
208
- if (this.swarm.peers.size > 0) this._restorePending = true
209
- else this.swarm.setTopic(this._topic).catch(safetyCatch)
190
+ _attach(conn) {
191
+ const mux = Protomux.from(conn)
192
+ const hex = b4a.toHex(conn.remotePublicKey)
193
+ let message = null
194
+ const send = () => {
195
+ if (!message) {
196
+ const channel = mux.createChannel({ protocol: 'cero/info' })
197
+ if (channel === null) return
198
+ message = channel.addMessage({
199
+ encoding: c.json,
200
+ onmessage: (info) => {
201
+ if (!info || typeof info !== 'object') return
202
+ this._heard.set(hex, info)
203
+ this.emit('update')
204
+ }
205
+ })
206
+ channel.open()
207
+ }
208
+ if (this._info) message.send(this._info)
209
+ }
210
+ mux.pair({ protocol: 'cero/info' }, send)
211
+ this._senders.add(send)
212
+ this._links.set(hex, conn)
213
+ conn.on('close', () => {
214
+ this._senders.delete(send)
215
+ if (this._links.get(hex) !== conn) return
216
+ this._links.delete(hex)
217
+ if (this._heard.delete(hex)) this.emit('update')
218
+ })
219
+ if (this._info) send()
210
220
  }
221
+ }
211
222
 
212
- /** @private */
213
- _clearAnnounce() {
214
- const e = this._announce
215
- if (!e) return
216
- if (e.timer) clearTimeout(e.timer)
217
- this._announce = null
218
- this._restorePending = false
223
+ function checkTopic(topic) {
224
+ if (topic !== undefined && (typeof topic !== 'string' || !topic)) {
225
+ throw CeroError.INVALID('topic is a non-empty string')
219
226
  }
220
227
  }
221
228
 
229
+ // the channel bounds every topic: the same topic on another channel is another topic
230
+ function topicOf(base, topic) {
231
+ return topic === undefined ? base : crypto.hash([base, b4a.from(topic)])
232
+ }
233
+
222
234
  function signed(info, key) {
223
235
  if (typeof info?.id !== 'string' || typeof info.proof !== 'string') return false
224
236
  try {