@cero-base/core 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/README.md +18 -18
- package/package.json +7 -7
- package/src/blobs/index.js +11 -15
- package/src/database/dispatch.js +12 -17
- package/src/database/encryption.js +29 -37
- package/src/database/envelope.js +10 -6
- package/src/database/index.js +63 -51
- package/src/database/rotation.js +1 -1
- package/src/lib/constants.js +3 -5
- package/src/lib/utils.js +8 -9
- package/src/mailbox/index.js +2 -2
- package/src/network/index.js +35 -138
- package/src/network/presence.js +1 -1
- package/src/pairing/index.js +61 -40
- package/src/pairing/response.js +8 -0
- package/src/storage/index.js +4 -1
- package/types/blobs/index.d.ts +6 -14
- package/types/database/encryption.d.ts +6 -8
- package/types/database/envelope.d.ts +3 -4
- package/types/database/index.d.ts +13 -11
- package/types/lib/constants.d.ts +1 -3
- package/types/lib/utils.d.ts +0 -2
- package/types/mailbox/index.d.ts +1 -1
- package/types/network/index.d.ts +22 -56
- package/types/pairing/index.d.ts +31 -12
- package/types/pairing/response.d.ts +14 -0
- package/src/pairing/request.js +0 -94
- package/types/pairing/request.d.ts +0 -93
package/src/database/index.js
CHANGED
|
@@ -14,13 +14,14 @@ import {
|
|
|
14
14
|
ACTION,
|
|
15
15
|
QUERY_RESERVED,
|
|
16
16
|
RANK,
|
|
17
|
-
ADMIN
|
|
17
|
+
ADMIN,
|
|
18
|
+
WRITE
|
|
18
19
|
} from '../lib/constants.js'
|
|
19
20
|
import { genId } from '../lib/ids.js'
|
|
20
21
|
import {
|
|
21
22
|
subscribe,
|
|
22
23
|
admission,
|
|
23
|
-
|
|
24
|
+
can,
|
|
24
25
|
filter,
|
|
25
26
|
checkFields,
|
|
26
27
|
checkRequired,
|
|
@@ -39,10 +40,10 @@ import { keyPair } from '../mailbox/inbox.js'
|
|
|
39
40
|
* @typedef {object} DatabaseOpts
|
|
40
41
|
* @property {import('corestore')} store Corestore (or compatible) used to materialize the autobee.
|
|
41
42
|
* @property {import('../identity/index.js').Identity} identity Long-lived member identity used to sign writer changes.
|
|
42
|
-
* @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication.
|
|
43
|
+
* @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication; `store` is its store or a session of it.
|
|
43
44
|
* @property {{ database: object, dispatch: { Router: new () => object, encode: (name: string, value: unknown) => Uint8Array, decode: (buf: Uint8Array) => { name: string, value: unknown } }, meta?: { ns?: string, version?: number, refs?: Record<string, { kind?: string, verb?: string }> } }} spec Generated hyperdb + hyperdispatch spec.
|
|
44
45
|
* @property {string} [namespace] Corestore namespace; defaults to `cero`.
|
|
45
|
-
* @property {Uint8Array
|
|
46
|
+
* @property {Uint8Array} encryptionKey Encrypts it; a join hands it out, so never the identity's on a database you pair.
|
|
46
47
|
* @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
|
|
47
48
|
* @property {Uint8Array | null} [key] Existing autobee key to reopen.
|
|
48
49
|
* @property {boolean} [pinned] Always search and announce, outside the network's presence budget. The root.
|
|
@@ -86,6 +87,11 @@ export class Database extends ReadyResource {
|
|
|
86
87
|
if (!opts.spec || !opts.spec.database || !opts.spec.dispatch) {
|
|
87
88
|
throw CeroError.INVALID('spec must have database + dispatch')
|
|
88
89
|
}
|
|
90
|
+
if (!opts.encryptionKey) throw CeroError.REQUIRED('encryptionKey')
|
|
91
|
+
// a network replicates its own store only: a database in another would never leave the device
|
|
92
|
+
if (opts.network && !opts.network.replicates(opts.store)) {
|
|
93
|
+
throw CeroError.INVALID("store must be the network's store or a session of it")
|
|
94
|
+
}
|
|
89
95
|
|
|
90
96
|
/** @type {import('corestore')} */
|
|
91
97
|
this.store = opts.store
|
|
@@ -99,7 +105,7 @@ export class Database extends ReadyResource {
|
|
|
99
105
|
/** @type {number | null} */
|
|
100
106
|
this.behind = null
|
|
101
107
|
this.namespace = opts.namespace || NAMESPACE
|
|
102
|
-
this.encryptionKey = opts.encryptionKey
|
|
108
|
+
this.encryptionKey = opts.encryptionKey
|
|
103
109
|
this.keyring = new Keyring()
|
|
104
110
|
if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
|
|
105
111
|
/** @private */
|
|
@@ -116,7 +122,7 @@ export class Database extends ReadyResource {
|
|
|
116
122
|
this._onerror = opts.onerror || ((err) => console.error(err))
|
|
117
123
|
// a join is sealed to the address the encryption key owns: every member opens it, no one else
|
|
118
124
|
/** @private */
|
|
119
|
-
this._room =
|
|
125
|
+
this._room = keyPair(this.encryptionKey)
|
|
120
126
|
this.bee = null
|
|
121
127
|
this.dispatcher = null
|
|
122
128
|
/** @private */
|
|
@@ -209,7 +215,7 @@ export class Database extends ReadyResource {
|
|
|
209
215
|
// without a listener autobee escalates apply/view errors to a process crash
|
|
210
216
|
this.bee.on('error', this._onerror)
|
|
211
217
|
|
|
212
|
-
// with no mirror to hold the
|
|
218
|
+
// with no mirror to hold the database, every member holds it: any member serves a joiner, offline
|
|
213
219
|
if (this.network && !this.network.mirrors.length) {
|
|
214
220
|
this.bee.on('move-to', () => this._holdRoom().catch(safetyCatch))
|
|
215
221
|
this._holdRoom().catch(safetyCatch)
|
|
@@ -231,8 +237,6 @@ export class Database extends ReadyResource {
|
|
|
231
237
|
for (const { range } of held) range.destroy()
|
|
232
238
|
await Promise.allSettled(held.map(({ core }) => core.close()))
|
|
233
239
|
if (this.bee) {
|
|
234
|
-
// detach first, else the closed bee replicates into every new connection
|
|
235
|
-
if (this.network) this.network.detach(this.bee)
|
|
236
240
|
await this.bee.close()
|
|
237
241
|
this.bee = null
|
|
238
242
|
}
|
|
@@ -285,6 +289,7 @@ export class Database extends ReadyResource {
|
|
|
285
289
|
*/
|
|
286
290
|
async put(name, row) {
|
|
287
291
|
const ref = this._prepare(name, row)
|
|
292
|
+
if (ref.kind === SINGLE) throw CeroError.INVALID(`${name} is a single: write it with set`)
|
|
288
293
|
const was = row.id ? (await this.get(name, row.id)).data : null
|
|
289
294
|
const stored = stamp({ ...row, id: row.id || genId() }, was?.createdAt)
|
|
290
295
|
checkRequired(name, this.refs[name], stored)
|
|
@@ -492,7 +497,6 @@ export class Database extends ReadyResource {
|
|
|
492
497
|
async bootstrap({ name, isMobile, recovering = false, timeout = 30000 } = {}) {
|
|
493
498
|
this.guard()
|
|
494
499
|
const ts = Date.now()
|
|
495
|
-
const writer = this._admission(this.writerKey, ts)
|
|
496
500
|
const device = [
|
|
497
501
|
'set-device',
|
|
498
502
|
{
|
|
@@ -504,10 +508,7 @@ export class Database extends ReadyResource {
|
|
|
504
508
|
}
|
|
505
509
|
]
|
|
506
510
|
if (recovering) {
|
|
507
|
-
await this.
|
|
508
|
-
await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
|
|
509
|
-
timeout
|
|
510
|
-
})
|
|
511
|
+
await this.claim({ timeout })
|
|
511
512
|
await this.write([device])
|
|
512
513
|
} else {
|
|
513
514
|
// one batch: a writer is never on the log without its member row
|
|
@@ -519,28 +520,30 @@ export class Database extends ReadyResource {
|
|
|
519
520
|
createdAt: ts,
|
|
520
521
|
updatedAt: ts
|
|
521
522
|
}
|
|
523
|
+
const writer = this._admission(this.writerKey, ts)
|
|
522
524
|
await this.write([['add-writer', writer], ['add-member', member], device])
|
|
523
525
|
}
|
|
524
526
|
return { id: this.writerKey, writer: this.keyPair }
|
|
525
527
|
}
|
|
526
528
|
|
|
527
529
|
/**
|
|
528
|
-
*
|
|
529
|
-
* the
|
|
530
|
+
* Seat this device's writer where its identity is a member: wait for the member row, append
|
|
531
|
+
* the add-writer the identity signs from this device's own core, and resolve once it writes.
|
|
532
|
+
* A member whose role cannot write takes no seat.
|
|
530
533
|
*
|
|
534
|
+
* @param {{ timeout?: number }} [opts]
|
|
531
535
|
* @returns {Promise<void>}
|
|
532
536
|
*/
|
|
533
|
-
async claim() {
|
|
537
|
+
async claim({ timeout = 30000 } = {}) {
|
|
534
538
|
this.guard()
|
|
535
539
|
if (this.bee.writable) return
|
|
536
|
-
const
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
})
|
|
543
|
-
await this._optimistic(op)
|
|
540
|
+
const { role } = await this._member(timeout)
|
|
541
|
+
if (!can(role, WRITE)) return
|
|
542
|
+
const op = this.spec.dispatch.encode(`@${this.ns}/add-writer`, this._admission(this.writerKey))
|
|
543
|
+
// from a core not yet admitted: apply verifies the identity's signature and seats it
|
|
544
|
+
await this.bee.append(wrap(this.version, op), { optimistic: true })
|
|
545
|
+
await this.bee.update()
|
|
546
|
+
await this.whenWritable({ timeout })
|
|
544
547
|
}
|
|
545
548
|
|
|
546
549
|
/**
|
|
@@ -673,7 +676,6 @@ export class Database extends ReadyResource {
|
|
|
673
676
|
if (this.behind === null || this.behind > this.version) return false
|
|
674
677
|
await this.bee.local.setUserData('autobee/head', null)
|
|
675
678
|
await this.bee.local.setUserData('cero/behind', null)
|
|
676
|
-
if (this.network) this.network.detach(this.bee)
|
|
677
679
|
await this.bee.close()
|
|
678
680
|
this.behind = null
|
|
679
681
|
return true
|
|
@@ -704,12 +706,17 @@ export class Database extends ReadyResource {
|
|
|
704
706
|
async _apply(nodes, view, host) {
|
|
705
707
|
const ready = []
|
|
706
708
|
for (const node of nodes) {
|
|
707
|
-
const
|
|
708
|
-
|
|
709
|
-
|
|
709
|
+
const op = unwrap(node.value)
|
|
710
|
+
// bytes with no envelope, or a cut one, are no op: skipped and surfaced like any node that does not decode
|
|
711
|
+
if (!op) {
|
|
712
|
+
this._onerror(CeroError.INVALID('an op with no envelope'))
|
|
710
713
|
continue
|
|
711
714
|
}
|
|
712
|
-
|
|
715
|
+
if (op.version > this.version) {
|
|
716
|
+
this._onfuture(op.version)
|
|
717
|
+
continue
|
|
718
|
+
}
|
|
719
|
+
ready.push({ ...node, value: op.body })
|
|
713
720
|
}
|
|
714
721
|
const result = await this.dispatcher.apply(ready, view, host)
|
|
715
722
|
this._notify(ready)
|
|
@@ -733,7 +740,7 @@ export class Database extends ReadyResource {
|
|
|
733
740
|
this._presence ??= this.network.presence.add(discoveryKey, { pinned: this.pinned })
|
|
734
741
|
}
|
|
735
742
|
|
|
736
|
-
// every writer the
|
|
743
|
+
// every writer the database ever had and every core its views read; only the system bee, an autobee
|
|
737
744
|
// internal, lists all the writers
|
|
738
745
|
/** @private */
|
|
739
746
|
async _holdRoom() {
|
|
@@ -743,7 +750,7 @@ export class Database extends ReadyResource {
|
|
|
743
750
|
for await (const writer of bee.system.list()) this._hold(writer.key, writer.length)
|
|
744
751
|
}
|
|
745
752
|
|
|
746
|
-
// a view live, a writer only as far as the
|
|
753
|
+
// a view live, a writer only as far as the database applied it: past that a stranger could grow a
|
|
747
754
|
// core every member pulls. Inactive, so a new connection stays silent: the range only asks peers
|
|
748
755
|
// already replicating the core
|
|
749
756
|
/** @private */
|
|
@@ -830,7 +837,9 @@ export class Database extends ReadyResource {
|
|
|
830
837
|
const ref = this._prepare(name, row)
|
|
831
838
|
const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
|
|
832
839
|
if (!upsert && !existing) return null
|
|
833
|
-
|
|
840
|
+
// a single is one record with no fields of Cero's
|
|
841
|
+
const merged = { ...existing, ...row }
|
|
842
|
+
const stored = ref.kind === SINGLE ? merged : stamp(merged, existing?.createdAt)
|
|
834
843
|
checkRequired(name, this.refs[name], stored)
|
|
835
844
|
if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
|
|
836
845
|
const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
|
|
@@ -937,25 +946,28 @@ export class Database extends ReadyResource {
|
|
|
937
946
|
return (await view.find(path, bounds).toArray()).length
|
|
938
947
|
}
|
|
939
948
|
|
|
940
|
-
//
|
|
941
|
-
/** @private */
|
|
942
|
-
async _optimistic(op, opts) {
|
|
943
|
-
await this.bee.append(wrap(this.version, op), { optimistic: true })
|
|
944
|
-
await this.bee.update()
|
|
945
|
-
if (!this.bee.writable) await this.whenWritable(opts)
|
|
946
|
-
}
|
|
947
|
-
|
|
948
|
-
// the genesis device row is the first write of every database, so any device row means backfilled
|
|
949
|
+
// this identity's member row, looked up again on every update until one lands it
|
|
949
950
|
/** @private */
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
951
|
+
_member(timeout) {
|
|
952
|
+
return new Promise((resolve, reject) => {
|
|
953
|
+
const done = (err, member) => {
|
|
954
|
+
clearTimeout(timer)
|
|
955
|
+
this.off('update', check)
|
|
956
|
+
this.off('close', onclose)
|
|
957
|
+
if (err) reject(err)
|
|
958
|
+
else resolve(member)
|
|
959
|
+
}
|
|
960
|
+
const check = () =>
|
|
961
|
+
this.get('members', this.identity.id).then(({ data }) => data && done(null, data), done)
|
|
962
|
+
const onclose = () => done(CeroError.CLOSED('Database'))
|
|
963
|
+
const timer =
|
|
964
|
+
timeout > 0
|
|
965
|
+
? setTimeout(() => done(CeroError.TIMEOUT('waiting for the member row')), timeout)
|
|
966
|
+
: null
|
|
967
|
+
this.on('update', check)
|
|
968
|
+
this.once('close', onclose)
|
|
969
|
+
check()
|
|
970
|
+
})
|
|
959
971
|
}
|
|
960
972
|
|
|
961
973
|
// the add-writer row for `writer`, appended by this device and signed by the identity
|
package/src/database/rotation.js
CHANGED
|
@@ -207,7 +207,7 @@ export class Rotation {
|
|
|
207
207
|
if (!can(me?.role, REMOVE)) return
|
|
208
208
|
|
|
209
209
|
const rows = await this._epochs()
|
|
210
|
-
// a
|
|
210
|
+
// a database still on its creation key re-keys at its first removal
|
|
211
211
|
if (!rows.length) {
|
|
212
212
|
if (await db.view.findOne(`@${db.ns}/removals`, {})) await this._heal('first removal')
|
|
213
213
|
return
|
package/src/lib/constants.js
CHANGED
|
@@ -14,18 +14,16 @@ export const ADMIN = 'admin'
|
|
|
14
14
|
export const MEMBER = 'member'
|
|
15
15
|
export const READER = 'reader'
|
|
16
16
|
|
|
17
|
-
export const READ = 'read'
|
|
18
17
|
export const WRITE = 'write'
|
|
19
|
-
export const DELETE = 'delete'
|
|
20
18
|
export const INVITE = 'invite'
|
|
21
19
|
export const REMOVE = 'remove'
|
|
22
20
|
export const ASSIGN = 'assign'
|
|
23
21
|
|
|
24
22
|
export const ROLE_PERMS = {
|
|
25
23
|
[OWNER]: ['*'],
|
|
26
|
-
[ADMIN]: [
|
|
27
|
-
[MEMBER]: [
|
|
28
|
-
[READER]: [
|
|
24
|
+
[ADMIN]: [WRITE, INVITE, REMOVE, ASSIGN],
|
|
25
|
+
[MEMBER]: [WRITE, INVITE],
|
|
26
|
+
[READER]: []
|
|
29
27
|
}
|
|
30
28
|
|
|
31
29
|
export const RANK = { [OWNER]: 3, [ADMIN]: 2, [MEMBER]: 1, [READER]: 0 }
|
package/src/lib/utils.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import b4a from 'b4a'
|
|
2
2
|
import { Readable } from 'streamx'
|
|
3
3
|
|
|
4
|
-
import { ROLE_PERMS, RANK, QUERY_RESERVED } from './constants.js'
|
|
4
|
+
import { ROLE_PERMS, RANK, QUERY_RESERVED, WRITE, INVITE, ASSIGN, REMOVE } from './constants.js'
|
|
5
5
|
import { CeroError } from './errors.js'
|
|
6
6
|
|
|
7
7
|
// can() callers need the capability names, and constants.js is not public
|
|
8
8
|
export { WRITE, INVITE, ASSIGN, REMOVE } from './constants.js'
|
|
9
9
|
|
|
10
|
-
|
|
10
|
+
const PERMS = new Set([WRITE, INVITE, ASSIGN, REMOVE])
|
|
11
|
+
|
|
12
|
+
// binding the db key makes an admission unreplayable across databases
|
|
11
13
|
const ADD_WRITER_TAG = b4a.from('cero/add-writer')
|
|
12
|
-
const CLAIM_WRITER_TAG = b4a.from('cero/claim-writer')
|
|
13
14
|
const JOIN_TAG = b4a.from('cero/join')
|
|
14
15
|
|
|
15
16
|
// fields the write path stamps itself, always allowed
|
|
@@ -20,12 +21,7 @@ export function admission(dbKey, writer, appender) {
|
|
|
20
21
|
return b4a.concat([ADD_WRITER_TAG, dbKey, writer, appender])
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
|
|
24
|
-
export function ownership(dbKey, writer) {
|
|
25
|
-
return b4a.concat([CLAIM_WRITER_TAG, dbKey, writer])
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// what a joiner's identity signs: this room, this invite, this writer, where the keys go
|
|
24
|
+
// what a joiner's identity signs: this database, this invite, this writer, where the keys go
|
|
29
25
|
/** @type {(dbKey: Uint8Array, invite: Uint8Array, writer: Uint8Array, reply: Uint8Array) => Uint8Array} */
|
|
30
26
|
export function joining(dbKey, invite, writer, reply) {
|
|
31
27
|
return b4a.concat([JOIN_TAG, dbKey, invite, writer, reply])
|
|
@@ -39,6 +35,9 @@ export function joining(dbKey, invite, writer, reply) {
|
|
|
39
35
|
* @returns {boolean}
|
|
40
36
|
*/
|
|
41
37
|
export function can(role, perm) {
|
|
38
|
+
if (!PERMS.has(perm)) {
|
|
39
|
+
throw CeroError.INVALID(`'${perm}' is not a permission: write, invite, assign or remove`)
|
|
40
|
+
}
|
|
42
41
|
const perms = ROLE_PERMS[role]
|
|
43
42
|
return !!perms && (perms.includes('*') || perms.includes(perm))
|
|
44
43
|
}
|
package/src/mailbox/index.js
CHANGED
|
@@ -34,7 +34,7 @@ import { CeroError } from '../lib/errors.js'
|
|
|
34
34
|
*/
|
|
35
35
|
export class Mailbox extends ReadyResource {
|
|
36
36
|
/**
|
|
37
|
-
* @param {import('../network/index.js').Network} network
|
|
37
|
+
* @param {import('../network/index.js').Network} network Messages travel as cores in its store.
|
|
38
38
|
* @param {MailboxOpts} [opts]
|
|
39
39
|
*/
|
|
40
40
|
constructor(
|
|
@@ -42,7 +42,7 @@ export class Mailbox extends ReadyResource {
|
|
|
42
42
|
{ inbox = memory(), outbox = memory(), onerror = (err) => console.error(err) } = {}
|
|
43
43
|
) {
|
|
44
44
|
super()
|
|
45
|
-
if (!network
|
|
45
|
+
if (!network) throw CeroError.REQUIRED('network')
|
|
46
46
|
this.network = network
|
|
47
47
|
this.inbox = inbox
|
|
48
48
|
this.outbox = outbox
|
package/src/network/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import NoiseSecretStream from '@hyperswarm/secret-stream'
|
|
2
2
|
import Autobee from 'autobee'
|
|
3
3
|
import BlindPeering from 'blind-peering'
|
|
4
|
-
import Protomux from 'protomux'
|
|
5
4
|
import ProtomuxWakeup from 'protomux-wakeup'
|
|
6
5
|
import ReadyResource from 'ready-resource'
|
|
7
6
|
import safetyCatch from 'safety-catch'
|
|
@@ -10,7 +9,6 @@ import { hash } from 'hypercore-crypto'
|
|
|
10
9
|
import HyperDHT from 'hyperdht'
|
|
11
10
|
import Hyperswarm from 'hyperswarm'
|
|
12
11
|
import b4a from 'b4a'
|
|
13
|
-
import c from 'compact-encoding'
|
|
14
12
|
|
|
15
13
|
import { ACTIVE, PASSIVE } from '../lib/constants.js'
|
|
16
14
|
import { CeroError } from '../lib/errors.js'
|
|
@@ -34,20 +32,18 @@ export function channelTopic(topic, channel) {
|
|
|
34
32
|
* @property {Uint8Array[]} [relayThrough] Relay public keys to tunnel through.
|
|
35
33
|
* @property {number[]} [backoffs] Reconnect backoff tiers in ms; the default escalates to ~10min, far too slow for local nets.
|
|
36
34
|
* @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
|
|
37
|
-
* @property {import('corestore')}
|
|
38
|
-
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached
|
|
35
|
+
* @property {import('corestore')} store Corestore; every connection replicates it, so every core it holds rides every peer.
|
|
36
|
+
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached database/blob core is mirrored through them for offline sync.
|
|
39
37
|
* @property {(err: Error) => void} [onerror] Background-task error handler.
|
|
40
38
|
* @property {{ active?: number, announced?: number, idle?: number }} [presence] Swarm budget for attached databases: how many search, how many only announce, and the idle ms before the rest leave.
|
|
41
|
-
*
|
|
42
|
-
* @typedef {{ replicate: (stream: import('@hyperswarm/secret-stream')) => unknown }} Replicable
|
|
43
39
|
*/
|
|
44
40
|
|
|
45
41
|
/**
|
|
46
|
-
* Hyperswarm peer
|
|
47
|
-
*
|
|
42
|
+
* Hyperswarm peer discovery plus a shared wakeup channel. Every connection, swarm or injected,
|
|
43
|
+
* replicates the store.
|
|
48
44
|
*/
|
|
49
45
|
export class Network extends ReadyResource {
|
|
50
|
-
/** @param {NetworkOpts}
|
|
46
|
+
/** @param {NetworkOpts} opts */
|
|
51
47
|
constructor({
|
|
52
48
|
identity,
|
|
53
49
|
bootstrap,
|
|
@@ -61,14 +57,15 @@ export class Network extends ReadyResource {
|
|
|
61
57
|
onerror = (err) => console.error(err)
|
|
62
58
|
} = {}) {
|
|
63
59
|
super()
|
|
60
|
+
if (!store) throw CeroError.REQUIRED('store')
|
|
64
61
|
this.identity = identity || null
|
|
65
62
|
this.bootstrap = bootstrap || null
|
|
66
63
|
this.firewall = firewall || null
|
|
67
64
|
this.relayThrough = relayThrough || null
|
|
68
65
|
this.backoffs = backoffs || null
|
|
69
66
|
this.channel = channel || null
|
|
70
|
-
/** @type {import('corestore')
|
|
71
|
-
this.store = store
|
|
67
|
+
/** @type {import('corestore')} */
|
|
68
|
+
this.store = store
|
|
72
69
|
/** @type {Uint8Array[]} */
|
|
73
70
|
this.mirrors = (mirrors || []).map((k) => (typeof k === 'string' ? decodeKey(k) : k))
|
|
74
71
|
|
|
@@ -78,14 +75,6 @@ export class Network extends ReadyResource {
|
|
|
78
75
|
this.wakeup = new ProtomuxWakeup()
|
|
79
76
|
this.presence = new Presence(this, presence)
|
|
80
77
|
|
|
81
|
-
this.info = null
|
|
82
|
-
/** @private */
|
|
83
|
-
this._peerInfo = new Map()
|
|
84
|
-
/** @private */
|
|
85
|
-
this._infoSenders = new Set()
|
|
86
|
-
|
|
87
|
-
/** @private */
|
|
88
|
-
this._replicateables = new Set()
|
|
89
78
|
/** @private */
|
|
90
79
|
this._discoveries = new Set()
|
|
91
80
|
/** @private */
|
|
@@ -149,17 +138,10 @@ export class Network extends ReadyResource {
|
|
|
149
138
|
}
|
|
150
139
|
dropIfSilent(stream)
|
|
151
140
|
stream.on('close', () => this._lose(stream.remotePublicKey))
|
|
152
|
-
this.
|
|
153
|
-
for (const r of this._replicateables) replicateInto(r, stream)
|
|
154
|
-
this.emit('connection', stream, info)
|
|
141
|
+
this._add(stream, info)
|
|
155
142
|
})
|
|
156
143
|
|
|
157
|
-
if (this.
|
|
158
|
-
// mailbox cores live in the store: every connection replicates it, so a listener can fetch them
|
|
159
|
-
const store = this.store
|
|
160
|
-
this._replicateables.add({ store, replicate: (stream) => store.replicate(stream) })
|
|
161
|
-
if (this.mirrors.length) this.peering()
|
|
162
|
-
}
|
|
144
|
+
if (this.mirrors.length) this.peering()
|
|
163
145
|
}
|
|
164
146
|
|
|
165
147
|
/** @private */
|
|
@@ -233,13 +215,17 @@ export class Network extends ReadyResource {
|
|
|
233
215
|
conn.on('close', () => this._injected.delete(conn))
|
|
234
216
|
conn.on('error', safetyCatch) // a dropped radio link must not crash the host
|
|
235
217
|
|
|
236
|
-
this.
|
|
237
|
-
this._attachInfo(conn)
|
|
238
|
-
for (const r of this._replicateables) replicateInto(r, conn)
|
|
239
|
-
this.emit('connection', conn, { injected: true })
|
|
218
|
+
this._add(conn, { injected: true })
|
|
240
219
|
return conn
|
|
241
220
|
}
|
|
242
221
|
|
|
222
|
+
/** @private */
|
|
223
|
+
_add(conn, info) {
|
|
224
|
+
this.wakeup.addStream(conn)
|
|
225
|
+
this.store.replicate(conn)
|
|
226
|
+
this.emit('connection', conn, info)
|
|
227
|
+
}
|
|
228
|
+
|
|
243
229
|
/**
|
|
244
230
|
* The blind-peering client, built on first use: a mailbox post names mirrors this network
|
|
245
231
|
* may not have been given.
|
|
@@ -248,7 +234,6 @@ export class Network extends ReadyResource {
|
|
|
248
234
|
*/
|
|
249
235
|
peering() {
|
|
250
236
|
if (this.closing || this.closed) throw CeroError.CLOSED('Network')
|
|
251
|
-
if (!this.store) throw CeroError.REQUIRED('store')
|
|
252
237
|
if (!this._blindPeering) {
|
|
253
238
|
this._blindPeering = new BlindPeering(this.swarm.dht, this.store, {
|
|
254
239
|
blindPeers: this.mirrors.map((key) => ({ key })),
|
|
@@ -259,28 +244,6 @@ export class Network extends ReadyResource {
|
|
|
259
244
|
return this._blindPeering
|
|
260
245
|
}
|
|
261
246
|
|
|
262
|
-
/**
|
|
263
|
-
* Declare this peer's self-reported info ({ name, ... }) to the peers of injected streams.
|
|
264
|
-
*
|
|
265
|
-
* @param {object | null} info
|
|
266
|
-
*/
|
|
267
|
-
setInfo(info) {
|
|
268
|
-
this.info = info || null
|
|
269
|
-
if (!this.info) return
|
|
270
|
-
for (const send of this._infoSenders) send()
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
/**
|
|
274
|
-
* Info a connected peer declared about itself, or null.
|
|
275
|
-
*
|
|
276
|
-
* @param {Uint8Array | string} key Peer public key (bytes or hex).
|
|
277
|
-
* @returns {object | null}
|
|
278
|
-
*/
|
|
279
|
-
getInfo(key) {
|
|
280
|
-
const hex = typeof key === 'string' ? key : b4a.toHex(key)
|
|
281
|
-
return this._peerInfo.get(hex) ?? null
|
|
282
|
-
}
|
|
283
|
-
|
|
284
247
|
/**
|
|
285
248
|
* Wait for pending DHT announces and lookups to settle, bounded by timeout.
|
|
286
249
|
*
|
|
@@ -343,21 +306,27 @@ export class Network extends ReadyResource {
|
|
|
343
306
|
}
|
|
344
307
|
|
|
345
308
|
/**
|
|
346
|
-
*
|
|
347
|
-
* It is replicated on every current and future swarm connection.
|
|
309
|
+
* Whether `store` replicates on this network's connections: the network's store or a session of it.
|
|
348
310
|
*
|
|
349
|
-
* @param {
|
|
311
|
+
* @param {import('corestore')} store
|
|
312
|
+
* @returns {boolean}
|
|
313
|
+
*/
|
|
314
|
+
replicates(store) {
|
|
315
|
+
return (store.root || store) === (this.store.root || this.store)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Keep a core or an autobee on the mirrors, so it stays reachable while its writers are
|
|
320
|
+
* offline. It rides the connections already, from the store; a mirror drops it once it closes.
|
|
321
|
+
*
|
|
322
|
+
* @param {import('hypercore') | import('autobee')} core
|
|
350
323
|
* @returns {void}
|
|
351
324
|
*/
|
|
352
325
|
attach(core) {
|
|
353
326
|
if (!core) throw CeroError.REQUIRED('core')
|
|
354
|
-
this.
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
if (this._blindPeering) {
|
|
358
|
-
if (Autobee.isAutobee(core)) core.ready().then(() => this._mirror(core), this._onerror)
|
|
359
|
-
else this._blindPeering.addCoreBackground(core)
|
|
360
|
-
}
|
|
327
|
+
if (!this._blindPeering) return
|
|
328
|
+
if (Autobee.isAutobee(core)) core.ready().then(() => this._mirror(core), this._onerror)
|
|
329
|
+
else this._blindPeering.addCoreBackground(core)
|
|
361
330
|
}
|
|
362
331
|
|
|
363
332
|
/** @private */
|
|
@@ -367,7 +336,7 @@ export class Network extends ReadyResource {
|
|
|
367
336
|
peering.addAutobaseBackground(bee)
|
|
368
337
|
// the bootstrap core leaves the writer set after the local swap, but joiners boot from it
|
|
369
338
|
peering.addCoreBackground(bee.bootstrap, { referrer: bee.key })
|
|
370
|
-
// autobee links views only through a trusted head, which a fresh
|
|
339
|
+
// autobee links views only through a trusted head, which a fresh database's first nodes lack
|
|
371
340
|
const views = bee.views().map((v) => this.store.get({ key: v.key }))
|
|
372
341
|
for (const view of views) peering.addCoreBackground(view, { referrer: bee.key })
|
|
373
342
|
bee.once('close', () => {
|
|
@@ -375,32 +344,6 @@ export class Network extends ReadyResource {
|
|
|
375
344
|
})
|
|
376
345
|
}
|
|
377
346
|
|
|
378
|
-
/**
|
|
379
|
-
* Unregister a previously attached resource. New connections will no
|
|
380
|
-
* longer replicate it (existing replication streams continue).
|
|
381
|
-
*
|
|
382
|
-
* @param {Replicable} core
|
|
383
|
-
* @returns {void}
|
|
384
|
-
*/
|
|
385
|
-
detach(core) {
|
|
386
|
-
if (!core) throw CeroError.REQUIRED('core')
|
|
387
|
-
this._replicateables.delete(core)
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
/**
|
|
391
|
-
* Replicate a one-off resource onto every current swarm connection
|
|
392
|
-
* without registering it as a long-lived attachment.
|
|
393
|
-
*
|
|
394
|
-
* @param {Replicable} target
|
|
395
|
-
* @returns {void}
|
|
396
|
-
*/
|
|
397
|
-
replicate(target) {
|
|
398
|
-
if (!target || typeof target.replicate !== 'function') {
|
|
399
|
-
throw CeroError.INVALID('target must be an object with a replicate(stream) method')
|
|
400
|
-
}
|
|
401
|
-
for (const stream of this.connections) replicateInto(target, stream)
|
|
402
|
-
}
|
|
403
|
-
|
|
404
347
|
// hyperswarm stops redialing a peer after a few failed tries and looks it up again only every 10 min
|
|
405
348
|
/** @private */
|
|
406
349
|
_lose(key) {
|
|
@@ -423,34 +366,6 @@ export class Network extends ReadyResource {
|
|
|
423
366
|
}, RELOOKUPS[i])
|
|
424
367
|
this._relookup.unref()
|
|
425
368
|
}
|
|
426
|
-
|
|
427
|
-
// injected streams only: bytes on a fresh swarm connection trip hyperswarm's duplicate guard
|
|
428
|
-
/** @private */
|
|
429
|
-
_attachInfo(conn) {
|
|
430
|
-
const mux = Protomux.from(conn)
|
|
431
|
-
let message = null
|
|
432
|
-
const send = () => {
|
|
433
|
-
if (!message) {
|
|
434
|
-
const channel = mux.createChannel({ protocol: 'cero/info' })
|
|
435
|
-
if (channel === null) return
|
|
436
|
-
message = channel.addMessage({
|
|
437
|
-
encoding: c.json,
|
|
438
|
-
onmessage: (info) => {
|
|
439
|
-
if (!info || typeof info !== 'object') return
|
|
440
|
-
const hex = b4a.toHex(conn.remotePublicKey)
|
|
441
|
-
this._peerInfo.set(hex, info)
|
|
442
|
-
this.emit('peer-info', hex, info)
|
|
443
|
-
}
|
|
444
|
-
})
|
|
445
|
-
channel.open()
|
|
446
|
-
}
|
|
447
|
-
if (this.info) message.send(this.info)
|
|
448
|
-
}
|
|
449
|
-
mux.pair({ protocol: 'cero/info' }, send)
|
|
450
|
-
this._infoSenders.add(send)
|
|
451
|
-
conn.on('close', () => this._infoSenders.delete(send))
|
|
452
|
-
if (this.info) send()
|
|
453
|
-
}
|
|
454
369
|
}
|
|
455
370
|
|
|
456
371
|
function dropIfSilent(conn) {
|
|
@@ -461,24 +376,6 @@ function dropIfSilent(conn) {
|
|
|
461
376
|
conn.once('close', () => clearTimeout(timer))
|
|
462
377
|
}
|
|
463
378
|
|
|
464
|
-
// corestore replication is store-wide: replicate each root once per connection
|
|
465
|
-
const replicatedRoots = new WeakMap()
|
|
466
|
-
|
|
467
|
-
function replicateInto(core, stream) {
|
|
468
|
-
const root = core.store ? core.store.root || core.store : null
|
|
469
|
-
if (root) {
|
|
470
|
-
let seen = replicatedRoots.get(stream)
|
|
471
|
-
if (!seen) replicatedRoots.set(stream, (seen = new WeakSet()))
|
|
472
|
-
if (seen.has(root)) return
|
|
473
|
-
seen.add(root)
|
|
474
|
-
}
|
|
475
|
-
try {
|
|
476
|
-
core.replicate(stream)
|
|
477
|
-
} catch (err) {
|
|
478
|
-
safetyCatch(err)
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
|
|
482
379
|
function isTopic(x) {
|
|
483
380
|
return b4a.isBuffer(x) && x.length === 32
|
|
484
381
|
}
|
package/src/network/presence.js
CHANGED
|
@@ -102,7 +102,7 @@ export class Presence {
|
|
|
102
102
|
this.entries.clear()
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
-
// up at once, down after idle: a
|
|
105
|
+
// up at once, down after idle: a database at the edge of the budget must not churn the DHT
|
|
106
106
|
/** @private */
|
|
107
107
|
_want(e, mode) {
|
|
108
108
|
const current = e.discovery ? e.discovery.mode : null
|