@peer2peer/cli 0.0.0-stage → 0.1.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/LICENSE +201 -0
- package/README.md +366 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +363 -0
- package/dist/app.js +1177 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +56 -0
- package/dist/circle-ops.d.ts +402 -0
- package/dist/circle-ops.js +1725 -0
- package/dist/cli.d.ts +611 -0
- package/dist/cli.js +1650 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +112 -0
- package/dist/config.js +243 -0
- package/dist/doctor.d.ts +99 -0
- package/dist/doctor.js +817 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +32 -0
- package/dist/ext-host.js +259 -0
- package/dist/extensions.d.ts +386 -0
- package/dist/extensions.js +395 -0
- package/dist/features.d.ts +91 -0
- package/dist/features.js +164 -0
- package/dist/format.d.ts +57 -0
- package/dist/format.js +248 -0
- package/dist/identity.d.ts +236 -0
- package/dist/identity.js +751 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +258 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/join-answers.d.ts +49 -0
- package/dist/join-answers.js +149 -0
- package/dist/outbox.d.ts +109 -0
- package/dist/outbox.js +337 -0
- package/dist/pretty.d.ts +100 -0
- package/dist/pretty.js +256 -0
- package/dist/procstart.d.ts +1 -0
- package/dist/procstart.js +66 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +78 -0
- package/dist/projects.d.ts +240 -0
- package/dist/projects.js +699 -0
- package/dist/prompt/picker.d.ts +64 -0
- package/dist/prompt/picker.js +152 -0
- package/dist/prompt/tty.d.ts +29 -0
- package/dist/prompt/tty.js +122 -0
- package/dist/readonly.d.ts +20 -0
- package/dist/readonly.js +50 -0
- package/dist/receipts.d.ts +99 -0
- package/dist/receipts.js +180 -0
- package/dist/relay-client.d.ts +277 -0
- package/dist/relay-client.js +873 -0
- package/dist/relay-info.d.ts +24 -0
- package/dist/relay-info.js +53 -0
- package/dist/rotation.d.ts +402 -0
- package/dist/rotation.js +2054 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.js +74 -0
- package/dist/sessions.d.ts +340 -0
- package/dist/sessions.js +1152 -0
- package/dist/shortcode.d.ts +149 -0
- package/dist/shortcode.js +465 -0
- package/dist/social.d.ts +139 -0
- package/dist/social.js +485 -0
- package/dist/state.d.ts +483 -0
- package/dist/state.js +217 -0
- package/dist/stdin.d.ts +17 -0
- package/dist/stdin.js +46 -0
- package/dist/sync.d.ts +77 -0
- package/dist/sync.js +375 -0
- package/dist/transient.d.ts +1 -0
- package/dist/transient.js +28 -0
- package/dist/trust.d.ts +37 -0
- package/dist/trust.js +134 -0
- package/dist/tty-confirm.d.ts +2 -0
- package/dist/tty-confirm.js +53 -0
- package/dist/tui/command.d.ts +20 -0
- package/dist/tui/command.js +70 -0
- package/dist/tui/frame.d.ts +43 -0
- package/dist/tui/frame.js +111 -0
- package/dist/tui/model.d.ts +215 -0
- package/dist/tui/model.js +255 -0
- package/dist/tui/sanitize.d.ts +13 -0
- package/dist/tui/sanitize.js +151 -0
- package/dist/tui/terminal.d.ts +88 -0
- package/dist/tui/terminal.js +354 -0
- package/dist/tui/tui.d.ts +71 -0
- package/dist/tui/tui.js +571 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +356 -0
- package/dist/unknown-kinds.d.ts +12 -0
- package/dist/unknown-kinds.js +66 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +5 -0
- package/dist/want-pow.d.ts +12 -0
- package/dist/want-pow.js +46 -0
- package/dist/watch.d.ts +35 -0
- package/dist/watch.js +325 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
|
@@ -0,0 +1,1725 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Circles (docs/protocol.md §3.3 and draft 3 additions P2).
|
|
4
|
+
//
|
|
5
|
+
// - Only the owner's identity key signs versions; this device does so when
|
|
6
|
+
// it holds `ik` and the head names its user as owner. Admins send
|
|
7
|
+
// proposals (`circle` envelopes, `ops`), which the owner's client applies.
|
|
8
|
+
// - The owner sends every new version, with the membership statements it
|
|
9
|
+
// holds, to every member and to its own devices (`distribute`).
|
|
10
|
+
// - Joining confirms first (§3.3 "confirm before joining"): the client asks
|
|
11
|
+
// the owner, and one other member it can reach, for the head (`want`),
|
|
12
|
+
// and refuses on any conflict. With no other member to ask, the owner's
|
|
13
|
+
// answer is enough; otherwise an unconfirmed join needs the user's say.
|
|
14
|
+
// - Open circles (P2): the owner's client applies joins automatically under
|
|
15
|
+
// `policy: "open"` (at most 20 an hour), holds the rest.
|
|
16
|
+
//
|
|
17
|
+
// Readings chosen here:
|
|
18
|
+
// - CLI circle links append `~<b64u(hint)>` to the spec link, where the hint
|
|
19
|
+
// is `{doc, join}`: the owner's identity document and current join
|
|
20
|
+
// statement. A stranger needs them to reach the owner at all (the head
|
|
21
|
+
// names only the owner's userId, and `circle` envelopes need a cap). A
|
|
22
|
+
// plain spec link still works when the owner is already reachable.
|
|
23
|
+
// - A stranger's `want` carries an answer cap (§3.3, draft 3 amendment), so
|
|
24
|
+
// the answer goes as ordinary `circle` bundles, chunked like any other:
|
|
25
|
+
// a long chain no longer has to fit one first-contact envelope. Answers to
|
|
26
|
+
// non-members are rate-limited per asker and in bytes overall
|
|
27
|
+
// (admitStrangerAnswer). An older client's want without a cap still gets
|
|
28
|
+
// the single `contact` circle invite `{circle, chain}` when it fits.
|
|
29
|
+
// - Transfer consent (`p2p-circle-accept+jws`) travels to the owner in a
|
|
30
|
+
// `circle` envelope's `ops`; core ignores it there, the CLI stores it.
|
|
31
|
+
import { ANSWER_CAP_MAX_TTL_SEC, applyCircleBundle, applyOwnerProposals, b64uDecode, b64uEncode, CircleChain, circleDisplayName, circleInviteLink, circlePolicy, confirmJoin, createCap, createCircle, createCircleTransferAccept, createMembershipStatement, createNextCircleVersion, createProposal, decideOpenJoinFor, joinCapTtlFor, openCircleCapActions, outgoingCircleBundle, decodeTyped, freshnessLookup, jwsHash, liveFriendshipsV3, loadCircle, nextMembershipN, parseCircleInviteLink, parseCircleVersion, pickConfirmers, recordOwnJoin, recordOwnLeave, standsInCircle, storeOfferedCircle, TYP3, verifyMembershipStatement, verifyCap, P2PError, MAX_CHAIN_IN_BUNDLE, nowSec, } from "@peer2peer/core/v3";
|
|
32
|
+
import { randomBytes } from "node:crypto";
|
|
33
|
+
import { App, capPeek, joinCapOf } from "./app.js";
|
|
34
|
+
import { guardForeignRelays } from "./social.js";
|
|
35
|
+
import { CliError } from "./errors.js";
|
|
36
|
+
import { fromOf, makeEvent } from "./inbound.js";
|
|
37
|
+
import { dropHeld, hold, withHeldId } from "./social.js";
|
|
38
|
+
import { chunkBody, exportCircle, sendSync, SYNC_CHUNK_BYTES } from "./sync.js";
|
|
39
|
+
import { addToAnswer, ANSWERS_PER_HOUR, dropAnswers, readAnswer } from "./join-answers.js";
|
|
40
|
+
import { checkWantPow, solveWantPow, WANT_POW_WINDOW_SEC } from "./want-pow.js";
|
|
41
|
+
import { circleHeld, onRotationJoin } from "./rotation.js";
|
|
42
|
+
const CIRCLE_SID = { sid: "~circle" };
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
// Lookup and links
|
|
45
|
+
export async function resolveCircle(app, input) {
|
|
46
|
+
const direct = await loadCircle(app.store, input);
|
|
47
|
+
if (direct)
|
|
48
|
+
return direct;
|
|
49
|
+
const hits = [];
|
|
50
|
+
for (const r of await app.store.listCircles()) {
|
|
51
|
+
const c = await loadCircle(app.store, r.cid);
|
|
52
|
+
if (c && (circleDisplayName(c.chain.head) === input || r.cid.startsWith(input)))
|
|
53
|
+
hits.push(c);
|
|
54
|
+
}
|
|
55
|
+
if (hits.length === 1)
|
|
56
|
+
return hits[0];
|
|
57
|
+
if (hits.length > 1)
|
|
58
|
+
throw new CliError("ambiguous", `more than one circle matches ${input}`, { candidates: hits.map((h) => h.record.cid) });
|
|
59
|
+
throw new CliError("not_found", `no circle ${input} here (see \`p2p circle ls\`)`);
|
|
60
|
+
}
|
|
61
|
+
export function encodeCircleLink(head, hint, web = false) {
|
|
62
|
+
const base = circleInviteLink(head, { web });
|
|
63
|
+
if (!hint || (!hint.doc && !hint.join))
|
|
64
|
+
return base;
|
|
65
|
+
return `${base}~${b64uEncode(new TextEncoder().encode(JSON.stringify(hint)))}`;
|
|
66
|
+
}
|
|
67
|
+
export function parseCircleLink(link) {
|
|
68
|
+
const s = link.trim();
|
|
69
|
+
const i = s.indexOf("~");
|
|
70
|
+
const head = parseCircleInviteLink(i >= 0 ? s.slice(0, i) : s);
|
|
71
|
+
if (i < 0)
|
|
72
|
+
return { head };
|
|
73
|
+
let hint;
|
|
74
|
+
try {
|
|
75
|
+
const v = JSON.parse(new TextDecoder().decode(b64uDecode(s.slice(i + 1))));
|
|
76
|
+
hint = {
|
|
77
|
+
...(typeof v.doc === "string" ? { doc: v.doc } : {}),
|
|
78
|
+
...(typeof v.join === "string" ? { join: v.join } : {}),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new CliError("usage", "the circle link's owner hint is damaged");
|
|
83
|
+
}
|
|
84
|
+
return { head, hint };
|
|
85
|
+
}
|
|
86
|
+
async function ownerHint(app, c) {
|
|
87
|
+
const owner = c.chain.head.owner;
|
|
88
|
+
const v = await app.view(owner);
|
|
89
|
+
const join = c.book[owner]?.op === "join" ? c.book[owner].jws : undefined;
|
|
90
|
+
return { ...(v ? { doc: v.head.jws } : {}), ...(join ? { join } : {}) };
|
|
91
|
+
}
|
|
92
|
+
export async function circleLink(app, cidOrName) {
|
|
93
|
+
const c = await resolveCircle(app, cidOrName);
|
|
94
|
+
const hint = await ownerHint(app, c);
|
|
95
|
+
return {
|
|
96
|
+
cid: c.record.cid,
|
|
97
|
+
link: encodeCircleLink(c.chain.head.jws, hint),
|
|
98
|
+
web: encodeCircleLink(c.chain.head.jws, hint, true),
|
|
99
|
+
policy: circlePolicy(c.chain.head),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
// Own membership
|
|
104
|
+
async function chainOpts(app) {
|
|
105
|
+
return { ...app.signerCtx(), self: app.userId, identityFreshness: await freshnessLookup(app.store) };
|
|
106
|
+
}
|
|
107
|
+
/** Signs and records our own join (§3.3), with a fresh co-member cap. */
|
|
108
|
+
export async function signOwnJoin(app, cid, at) {
|
|
109
|
+
const rec = await app.store.getCircle(cid);
|
|
110
|
+
const policy = rec ? circlePolicy(CircleChain.fromStored(rec.chain).head) : "invite";
|
|
111
|
+
const cap = createCap(app.device, app.keys.cert, { purpose: "join", relays: app.relays, ttlSec: joinCapTtlFor(policy) });
|
|
112
|
+
const jws = createMembershipStatement(app.signer(), { cid, n: nextMembershipN(rec?.myN), op: "join", at, cap });
|
|
113
|
+
const v = await verifyMembershipStatement(jws, app.signerCtx());
|
|
114
|
+
await recordJoin(app, v);
|
|
115
|
+
await app.recordIssued(cap);
|
|
116
|
+
return v;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Re-signs our join in `cid` (n+1, a fresh co-member cap on our current
|
|
120
|
+
* relays) and sends it to the members and our other devices (review L5).
|
|
121
|
+
*/
|
|
122
|
+
export async function resignJoin(app, cid) {
|
|
123
|
+
const c = await loadCircle(app.store, cid);
|
|
124
|
+
if (!c || !c.record.joinedByMe || c.book[app.userId]?.op !== "join")
|
|
125
|
+
return false;
|
|
126
|
+
await signOwnJoin(app, cid, c.chain.head.hash);
|
|
127
|
+
const mine = (await loadCircle(app.store, cid)).book[app.userId].jws;
|
|
128
|
+
for (const m of c.chain.head.members) {
|
|
129
|
+
// Never to someone we blocked: the block re-keyed our join so their copy stops working (R3-L1).
|
|
130
|
+
if (m === app.userId || (await app.store.isBlocked(m)))
|
|
131
|
+
continue;
|
|
132
|
+
await deliverCircle(app, m, { joins: [mine] }, memberCaps(c, m)).catch(() => undefined);
|
|
133
|
+
}
|
|
134
|
+
const exp = await exportCircle(app, cid);
|
|
135
|
+
if (exp)
|
|
136
|
+
await sendSync(app, { circles: [exp] });
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
/** Thin wrapper: the core hardening PR changes recordOwnJoin's signature (adds `self`). */
|
|
140
|
+
export async function recordJoin(app, v) {
|
|
141
|
+
await recordOwnJoin(app.store, app.userId, v);
|
|
142
|
+
}
|
|
143
|
+
async function summary(app, c) {
|
|
144
|
+
const h = c.chain.head;
|
|
145
|
+
const blocks = new Set((await app.store.listBlocks()).map((b) => b.userId));
|
|
146
|
+
const ctx = { viewer: app.userId, joinedByMe: c.record.joinedByMe, isBlocked: (u) => blocks.has(u) };
|
|
147
|
+
const role = h.owner === app.userId ? "owner" : h.admins.includes(app.userId) ? "admin" : h.members.includes(app.userId) ? "member" : c.record.joinedByMe ? "invited" : "former";
|
|
148
|
+
return {
|
|
149
|
+
cid: c.record.cid,
|
|
150
|
+
name: circleDisplayName(h),
|
|
151
|
+
ver: h.ver,
|
|
152
|
+
policy: circlePolicy(h),
|
|
153
|
+
owner: h.owner,
|
|
154
|
+
ownerAddress: await app.addressOf(h.owner),
|
|
155
|
+
role: c.record.joinedByMe || role === "owner" ? role : h.members.includes(app.userId) ? "invited" : "former",
|
|
156
|
+
joined: c.record.joinedByMe,
|
|
157
|
+
members: h.members.length,
|
|
158
|
+
standing: h.members.filter((m) => standsInCircle(m, c.chain, c.book, ctx)).length,
|
|
159
|
+
...(c.chain.frozen ? { frozen: c.chain.frozen.reason } : {}),
|
|
160
|
+
isDefault: app.self?.defaultCircle === c.record.cid,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
export async function createCircleCmd(app, name, opts) {
|
|
164
|
+
const ik = app.requireKeyholder("Founding a circle");
|
|
165
|
+
if (name.trim() === "" || [...name].length > 128)
|
|
166
|
+
throw new CliError("usage", "a circle name is 1–128 characters");
|
|
167
|
+
const v1 = createCircle(ik, { name, ...(opts.open ? { policy: "open" } : {}) });
|
|
168
|
+
const chain = await storeOfferedCircle(app.store, [v1]);
|
|
169
|
+
await signOwnJoin(app, chain.cid, chain.head.hash);
|
|
170
|
+
await app.connect({ allowNone: true });
|
|
171
|
+
const exp = await exportCircle(app, chain.cid);
|
|
172
|
+
if (exp)
|
|
173
|
+
await sendSync(app, { circles: [exp] });
|
|
174
|
+
const c = (await loadCircle(app.store, chain.cid));
|
|
175
|
+
const s = await summary(app, c);
|
|
176
|
+
return opts.open ? { ...s, link: (await circleLink(app, chain.cid)).link } : s;
|
|
177
|
+
}
|
|
178
|
+
export async function listCircles(app) {
|
|
179
|
+
const out = [];
|
|
180
|
+
for (const r of await app.store.listCircles()) {
|
|
181
|
+
const c = await loadCircle(app.store, r.cid);
|
|
182
|
+
if (c)
|
|
183
|
+
out.push(await summary(app, c));
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
export async function circleMembers(app, cidOrName) {
|
|
188
|
+
const c = await resolveCircle(app, cidOrName);
|
|
189
|
+
const h = c.chain.head;
|
|
190
|
+
const blocks = new Set((await app.store.listBlocks()).map((b) => b.userId));
|
|
191
|
+
const ctx = { viewer: app.userId, joinedByMe: c.record.joinedByMe, isBlocked: (u) => blocks.has(u) };
|
|
192
|
+
const members = [];
|
|
193
|
+
for (const m of h.members) {
|
|
194
|
+
members.push({
|
|
195
|
+
userId: m,
|
|
196
|
+
address: await app.addressOf(m),
|
|
197
|
+
owner: m === h.owner,
|
|
198
|
+
admin: h.admins.includes(m),
|
|
199
|
+
stands: standsInCircle(m, c.chain, c.book, ctx),
|
|
200
|
+
statement: c.book[m]?.op ?? null,
|
|
201
|
+
self: m === app.userId,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return { circle: await summary(app, c), founder: h.founder, members };
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Sets (or with undefined unsets) the default circle. `byJoin`: a code join set it because there was
|
|
208
|
+
* none, so sessions already running don't move into it (sessions.ts getSession); the user's own
|
|
209
|
+
* `circle default` clears that, and sessions follow it again.
|
|
210
|
+
*/
|
|
211
|
+
export async function setDefaultCircle(app, cidOrName, opts = {}) {
|
|
212
|
+
let cid;
|
|
213
|
+
if (cidOrName !== undefined) {
|
|
214
|
+
const c = await resolveCircle(app, cidOrName);
|
|
215
|
+
if (!c.record.joinedByMe)
|
|
216
|
+
throw new CliError("usage", "join the circle first");
|
|
217
|
+
cid = c.record.cid;
|
|
218
|
+
}
|
|
219
|
+
await app.updateSelf((s) => {
|
|
220
|
+
const { defaultFromJoin: _was, ...rest } = s;
|
|
221
|
+
return { ...rest, defaultCircle: cid, ...(opts.byJoin && cid ? { defaultFromJoin: cid } : {}) };
|
|
222
|
+
});
|
|
223
|
+
await sendSync(app, { defaultCircle: cid ?? null, ...(opts.byJoin && cid ? { defaultFromJoin: cid } : {}) }).catch(() => 0);
|
|
224
|
+
return { defaultCircle: cid ?? null };
|
|
225
|
+
}
|
|
226
|
+
// ---------------------------------------------------------------------------
|
|
227
|
+
// Owner: publishing and distribution
|
|
228
|
+
/** Signs the owner's next version, applies it here, and sends it out. */
|
|
229
|
+
export async function ownerPublish(app, cid, p, opts = {}) {
|
|
230
|
+
const ik = app.requireKeyholder("Signing a circle version");
|
|
231
|
+
const c = await loadCircle(app.store, cid);
|
|
232
|
+
if (!c)
|
|
233
|
+
throw new CliError("not_found", `circle ${cid} is not held`);
|
|
234
|
+
if (c.chain.head.owner !== app.userId)
|
|
235
|
+
throw new CliError("not_owner", "only the circle's owner signs versions; admins propose");
|
|
236
|
+
const v = createNextCircleVersion(ik, c.chain.head, p);
|
|
237
|
+
const res = await applyCircleBundle(app.store, { circles: [v], joins: [], ops: [] }, await chainOpts(app));
|
|
238
|
+
const r = res.versions[cid]?.[0];
|
|
239
|
+
if (!r || (r.status !== "accepted" && r.status !== "replaced"))
|
|
240
|
+
throw new CliError("internal", `own circle version not accepted (${r?.status} ${r?.reason ?? ""})`);
|
|
241
|
+
const removed = c.chain.head.members.filter((m) => !(p.members ?? c.chain.head.members).includes(m));
|
|
242
|
+
await distribute(app, cid, [...removed, ...(opts.alsoTo ?? [])]);
|
|
243
|
+
// Members-only relays that follow this circle admit (and cut off) by its head: tell them now.
|
|
244
|
+
await app.pushCircleToRelays(cid);
|
|
245
|
+
return (await loadCircle(app.store, cid)).chain.head;
|
|
246
|
+
}
|
|
247
|
+
/** Sends the chain and every statement held to every member (and `extra`), and to our own devices. */
|
|
248
|
+
export async function distribute(app, cid, extra = []) {
|
|
249
|
+
const c = await loadCircle(app.store, cid);
|
|
250
|
+
if (!c)
|
|
251
|
+
return { delivered: [], failed: [] };
|
|
252
|
+
const out = await outgoingCircleBundle(app.store, cid);
|
|
253
|
+
const bundle = { circles: out?.circles ?? [], joins: out?.joins ?? [], ops: [] };
|
|
254
|
+
const recipients = [...new Set([...c.chain.head.members, ...extra])].filter((u) => u !== app.userId);
|
|
255
|
+
const delivered = [];
|
|
256
|
+
const failed = [];
|
|
257
|
+
const parts = chunkBody(bundle);
|
|
258
|
+
// R3-L1: our own join statement (and so our co-member cap) never goes to someone we blocked:
|
|
259
|
+
// a block re-keys it. Other members can still pass it on; reach is relay-level only, and our
|
|
260
|
+
// client drops whatever a blocked user sends.
|
|
261
|
+
const mine = c.book[app.userId]?.jws;
|
|
262
|
+
const blocked = new Set((await app.store.listBlocks()).map((b) => b.userId));
|
|
263
|
+
for (const u of recipients) {
|
|
264
|
+
let ok = false;
|
|
265
|
+
for (const part of parts) {
|
|
266
|
+
try {
|
|
267
|
+
const joins = (part.joins ?? []).filter((j) => !(blocked.has(u) && j === mine));
|
|
268
|
+
const d = await app.deliver(u, "circle", { own: app.userId, ...CIRCLE_SID }, { circles: part.circles ?? [], joins, ops: [] }, { extraCaps: memberCaps(c, u) });
|
|
269
|
+
ok = ok || d.relays.length > 0;
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// no cap for them yet (an invitee who hasn't joined), or unreachable
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
(ok ? delivered : failed).push(u);
|
|
276
|
+
}
|
|
277
|
+
// §3.3: the owner's own devices receive every version too.
|
|
278
|
+
const view = await app.view(app.userId);
|
|
279
|
+
if (view && view.devices.some((d) => d !== app.did)) {
|
|
280
|
+
for (const part of parts) {
|
|
281
|
+
await app.deliver(app.userId, "circle", { own: app.userId, ...CIRCLE_SID }, { circles: part.circles ?? [], joins: part.joins ?? [], ops: [] }).catch(() => undefined);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { delivered, failed };
|
|
285
|
+
}
|
|
286
|
+
export async function deliverCircle(app, to, body, extraCaps = []) {
|
|
287
|
+
return app.deliver(to, "circle", { own: app.userId, ...CIRCLE_SID }, { circles: body.circles ?? [], joins: body.joins ?? [], ops: body.ops ?? [] }, { extraCaps });
|
|
288
|
+
}
|
|
289
|
+
// ---------------------------------------------------------------------------
|
|
290
|
+
// Invites and links
|
|
291
|
+
export async function inviteToCircle(app, cidOrName, who) {
|
|
292
|
+
await app.connectAndDrain();
|
|
293
|
+
const c = await resolveCircle(app, cidOrName);
|
|
294
|
+
const cid = c.record.cid;
|
|
295
|
+
const u = await app.resolveUser(who);
|
|
296
|
+
const h = c.chain.head;
|
|
297
|
+
let added = false;
|
|
298
|
+
if (h.owner === app.userId) {
|
|
299
|
+
if (!h.members.includes(u)) {
|
|
300
|
+
await ownerPublish(app, cid, { members: [...h.members, u] });
|
|
301
|
+
added = true;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
else if (h.admins.includes(app.userId)) {
|
|
305
|
+
const p = createProposal(app.signer(), { cid, base: h.ver, op: "add", target: u });
|
|
306
|
+
await deliverCircle(app, h.owner, { ops: [p] }, ownerCaps(c));
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
throw new CliError("not_admin", "only the owner or an admin can invite to this circle; share `p2p circle invite <cid> --link` instead");
|
|
310
|
+
}
|
|
311
|
+
const cur = (await loadCircle(app.store, cid));
|
|
312
|
+
const ob = await outgoingCircleBundle(app.store, cid);
|
|
313
|
+
const versions = ob?.circles ?? cur.chain.versionsFrom(1);
|
|
314
|
+
const statements = ob?.joins ?? [];
|
|
315
|
+
const caps = await app.capsFor(u, "circle");
|
|
316
|
+
let delivered;
|
|
317
|
+
if (caps.size > 0) {
|
|
318
|
+
delivered = await deliverCircle(app, u, { circles: versions, joins: statements });
|
|
319
|
+
}
|
|
320
|
+
else {
|
|
321
|
+
if (!(await app.viewFor(u)))
|
|
322
|
+
throw new CliError("unknown_user", `can't find ${who}'s identity document on your relays; send them a link instead`);
|
|
323
|
+
delivered = await app.deliver(u, "contact", { own: app.userId, sid: "~contact" }, { circle: cur.chain.head.jws, chain: versions.slice(0, -1) });
|
|
324
|
+
}
|
|
325
|
+
if (delivered.relays.length === 0)
|
|
326
|
+
throw new CliError("undelivered", "the circle invite was delivered via 0 relays", { delivered });
|
|
327
|
+
return { cid, invited: u, address: await app.addressOf(u), added, delivered };
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* P4: adds `u`, who just redeemed one of our short codes for `cid`. The owner
|
|
331
|
+
* (on a key-holding device) publishes the next version at once, which
|
|
332
|
+
* distribution delivers to `u` too; an admin proposes the add to the owner
|
|
333
|
+
* and sends `u` the circle as it stands. Never drains (it runs while
|
|
334
|
+
* envelopes are being handled).
|
|
335
|
+
*/
|
|
336
|
+
export async function addMemberViaCode(app, cid, u) {
|
|
337
|
+
const c = await loadCircle(app.store, cid);
|
|
338
|
+
if (!c)
|
|
339
|
+
return { status: "failed", reason: "circle not held here" };
|
|
340
|
+
const h = c.chain.head;
|
|
341
|
+
const name = circleDisplayName(h);
|
|
342
|
+
// Already a member: not the code's doing, so `p2p remove` leaves it.
|
|
343
|
+
if (h.members.includes(u))
|
|
344
|
+
return { status: "already", name };
|
|
345
|
+
if (h.owner === app.userId && app.isKeyholder) {
|
|
346
|
+
await ownerPublish(app, cid, { members: [...h.members, u] });
|
|
347
|
+
return { status: "added", name };
|
|
348
|
+
}
|
|
349
|
+
if (!h.admins.includes(app.userId)) {
|
|
350
|
+
return { status: "failed", name, reason: h.owner === app.userId ? "this device doesn't hold your identity key: add them from one that does (p2p circle invite)" : "you are no longer an admin of the circle" };
|
|
351
|
+
}
|
|
352
|
+
const p = createProposal(app.signer(), { cid, base: h.ver, op: "add", target: u });
|
|
353
|
+
await deliverCircle(app, h.owner, { ops: [p] }, ownerCaps(c));
|
|
354
|
+
const ob = await outgoingCircleBundle(app.store, cid);
|
|
355
|
+
await deliverCircle(app, u, { circles: ob?.circles ?? c.chain.versionsFrom(1), joins: ob?.joins ?? [] });
|
|
356
|
+
return { status: "proposed", name };
|
|
357
|
+
}
|
|
358
|
+
/** P4 `p2p remove`: takes `u` out of a circle we own (or proposes it as an admin). */
|
|
359
|
+
export async function removeMember(app, cid, u) {
|
|
360
|
+
const c = await loadCircle(app.store, cid);
|
|
361
|
+
if (!c)
|
|
362
|
+
return "not-member";
|
|
363
|
+
const h = c.chain.head;
|
|
364
|
+
if (!h.members.includes(u))
|
|
365
|
+
return "not-member";
|
|
366
|
+
if (u === h.owner)
|
|
367
|
+
return "not-allowed";
|
|
368
|
+
if (h.owner === app.userId && app.isKeyholder) {
|
|
369
|
+
await ownerPublish(app, cid, { members: h.members.filter((m) => m !== u), admins: h.admins.filter((m) => m !== u) });
|
|
370
|
+
return "removed";
|
|
371
|
+
}
|
|
372
|
+
if (!h.admins.includes(app.userId))
|
|
373
|
+
return "not-allowed";
|
|
374
|
+
const p = createProposal(app.signer(), { cid, base: h.ver, op: "remove", target: u });
|
|
375
|
+
await deliverCircle(app, h.owner, { ops: [p] }, ownerCaps(c));
|
|
376
|
+
return "proposed";
|
|
377
|
+
}
|
|
378
|
+
function ownerCaps(c) {
|
|
379
|
+
return memberCaps(c, c.chain.head.owner);
|
|
380
|
+
}
|
|
381
|
+
/** The co-member cap from `u`'s current join statement, for paths where we may no longer stand (leave, removal). */
|
|
382
|
+
export function memberCaps(c, u) {
|
|
383
|
+
const s = c.book[u];
|
|
384
|
+
const cap = s?.op === "join" ? joinCapOf(s.jws) : undefined;
|
|
385
|
+
return cap ? [cap] : [];
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Stores a confirmer's answer for a pending join; true when it matched one. An answer can span
|
|
389
|
+
* several envelopes (a chunked bundle, each marked `part` i of n): versions accumulate, the parts
|
|
390
|
+
* received are recorded so the join knows when the answer is whole, and a part carrying only
|
|
391
|
+
* statements names its circle with `cid`.
|
|
392
|
+
*/
|
|
393
|
+
export async function recordJoinAnswer(app, from, versions, joins, opts = {}) {
|
|
394
|
+
let cid = opts.cid;
|
|
395
|
+
for (const v of cid ? [] : versions) {
|
|
396
|
+
try {
|
|
397
|
+
cid = parseCircleVersion(v).cid;
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
// skip
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (!cid)
|
|
405
|
+
return false;
|
|
406
|
+
// A read, not an update: the joins index is rewritten only the first time a confirmer answers.
|
|
407
|
+
const p = (await app.state.get("joins"))?.[cid];
|
|
408
|
+
if (!p)
|
|
409
|
+
return false;
|
|
410
|
+
// review L1: only the members we asked (and the inviter) answer; anyone else's chain is ignored.
|
|
411
|
+
if (!p.asked.includes(from) && p.inviter !== from)
|
|
412
|
+
return false;
|
|
413
|
+
let offered;
|
|
414
|
+
try {
|
|
415
|
+
offered = parseCircleVersion(p.head);
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
return false;
|
|
419
|
+
}
|
|
420
|
+
if (!(p.answerFrom ?? []).includes(from)) {
|
|
421
|
+
await app.state.update("joins", (cur = {}) => {
|
|
422
|
+
const q = cur[cid];
|
|
423
|
+
if (!q || (q.answerFrom ?? []).includes(from))
|
|
424
|
+
return { result: undefined };
|
|
425
|
+
return { next: { ...cur, [cid]: { ...q, answerFrom: [...(q.answerFrom ?? []), from] } }, result: undefined };
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
await addToAnswer(app, cid, from, { offeredVer: offered.ver, members: offered.members.length }, versions, joins, opts.part);
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
/** Each confirmer's answer so far for a pending join (older state's `answers` included). */
|
|
432
|
+
async function pendingAnswers(app, p) {
|
|
433
|
+
const out = {};
|
|
434
|
+
if (!p)
|
|
435
|
+
return out;
|
|
436
|
+
for (const [from, vs] of Object.entries(p.answers ?? {}))
|
|
437
|
+
out[from] = { versions: vs, joins: [] };
|
|
438
|
+
for (const from of p.answerFrom ?? []) {
|
|
439
|
+
const d = await readAnswer(app, p.cid, from);
|
|
440
|
+
if (!d)
|
|
441
|
+
continue;
|
|
442
|
+
const prev = out[from];
|
|
443
|
+
out[from] = { versions: prev ? [...new Set([...prev.versions, ...d.versions])] : d.versions, joins: d.joins, parts: d.parts };
|
|
444
|
+
}
|
|
445
|
+
return out;
|
|
446
|
+
}
|
|
447
|
+
async function knownUsers(app) {
|
|
448
|
+
const s = new Set();
|
|
449
|
+
for (const f of await liveFriendshipsV3(app.store, app.signerCtx()))
|
|
450
|
+
s.add(f.inviter === app.userId ? f.invitee : f.inviter);
|
|
451
|
+
for (const r of await app.store.listCircles()) {
|
|
452
|
+
if (!r.joinedByMe)
|
|
453
|
+
continue;
|
|
454
|
+
for (const m of CircleChain.fromStored(r.chain).head.members)
|
|
455
|
+
s.add(m);
|
|
456
|
+
}
|
|
457
|
+
s.delete(app.userId);
|
|
458
|
+
return s;
|
|
459
|
+
}
|
|
460
|
+
/** The highest version `n` such that `versions` hold every version of their circle from 1 to `n` (0: none). */
|
|
461
|
+
export function contiguousTop(versions) {
|
|
462
|
+
const vers = new Set();
|
|
463
|
+
let cid;
|
|
464
|
+
for (const v of versions ?? []) {
|
|
465
|
+
try {
|
|
466
|
+
const p = parseCircleVersion(v);
|
|
467
|
+
if (cid !== undefined && p.cid !== cid)
|
|
468
|
+
continue;
|
|
469
|
+
cid = p.cid;
|
|
470
|
+
vers.add(p.ver);
|
|
471
|
+
}
|
|
472
|
+
catch {
|
|
473
|
+
// skip
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
let n = 0;
|
|
477
|
+
while (vers.has(n + 1))
|
|
478
|
+
n++;
|
|
479
|
+
return n;
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Whether a confirmer's answer is whole (§3.3): it holds every version from 1 up to the offered
|
|
483
|
+
* head's `ver` (a prefix of the chain confirms nothing), and, when it came in marked parts, every
|
|
484
|
+
* part of one answer that reached that far arrived, statements included. An unmarked answer (one
|
|
485
|
+
* envelope, or an older member) counts once its versions reach the offered head.
|
|
486
|
+
*/
|
|
487
|
+
export function answerComplete(versions, parts, offeredVer) {
|
|
488
|
+
if (contiguousTop(versions) < offeredVer)
|
|
489
|
+
return false;
|
|
490
|
+
const recs = Object.values(parts ?? {});
|
|
491
|
+
if (recs.length === 0)
|
|
492
|
+
return true;
|
|
493
|
+
// A whole answer that reached the offered head, or a whole one carrying no versions: the
|
|
494
|
+
// member's answer to a want from past its head (the joiner held every version already and asked
|
|
495
|
+
// for the rest, which is the statements).
|
|
496
|
+
return recs.some((r) => r.got.length >= r.n && (r.top >= offeredVer || r.top === 0));
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* The `want` asking `u` for a circle's history. Unless `u` is a friend (who holds our friend
|
|
500
|
+
* cap), it carries an answer cap for `u` (§3.3, draft 3 amendment: sub `u`, kinds ["*"], a day at
|
|
501
|
+
* most), so the answer can come as ordinary `circle` bundles in as many envelopes as it needs.
|
|
502
|
+
* Recorded as issued, so a block revokes it.
|
|
503
|
+
*/
|
|
504
|
+
async function wantFor(app, cid, u, fromVer) {
|
|
505
|
+
const friend = (await liveFriendshipsV3(app.store, app.signerCtx(), (f) => [f.inviter, f.invitee].includes(u))).some((f) => f.inviter === u || f.invitee === u);
|
|
506
|
+
if (friend)
|
|
507
|
+
return { want: { cid, fromVer } };
|
|
508
|
+
const cap = createCap(app.device, app.keys.cert, { purpose: "answer", sub: u, relays: app.relays, ttlSec: ANSWER_CAP_MAX_TTL_SEC });
|
|
509
|
+
const issued = await app.recordIssued(cap);
|
|
510
|
+
// L1: our other devices know of it too (so a block there revokes it), and the join revokes it when done.
|
|
511
|
+
await app.state.update("joins", (cur = {}) => {
|
|
512
|
+
const p = cur[cid];
|
|
513
|
+
return p ? { next: { ...cur, [cid]: { ...p, answerCaps: [...(p.answerCaps ?? []), issued.capid] } }, result: undefined } : { result: undefined };
|
|
514
|
+
});
|
|
515
|
+
await sendSync(app, { capsIssued: [issued] }).catch(() => undefined);
|
|
516
|
+
// Re-review N3: work, so the member's reserved budget for non-members can't be drained by throwaway identities.
|
|
517
|
+
return { want: { cid, fromVer }, cap, pow: solveWantPow(app.userId, u, cid, fromVer, nowSec()) };
|
|
518
|
+
}
|
|
519
|
+
/** Lists `u` as asked for a pending join, asked at `at` (ms; 0: due to be asked again). */
|
|
520
|
+
async function markAsked(app, cid, u, at) {
|
|
521
|
+
await app.state.update("joins", (cur = {}) => {
|
|
522
|
+
const p = cur[cid];
|
|
523
|
+
return p ? { next: { ...cur, [cid]: { ...p, asked: [...new Set([...p.asked, u])], askedAtBy: { ...p.askedAtBy, [u]: at } } }, result: undefined } : { result: undefined };
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
/** How old an unanswered request for a circle's history is before a join asks again. */
|
|
527
|
+
export const JOIN_REASK_MS = 60_000;
|
|
528
|
+
export async function joinCircle(app, input, opts = {}) {
|
|
529
|
+
const offeredHead = parseCircleVersion(input.head);
|
|
530
|
+
// Re-review N1: no chain longer than a bundle may carry is ever bootstrapped.
|
|
531
|
+
if (offeredHead.ver > MAX_CHAIN_IN_BUNDLE)
|
|
532
|
+
throw new CliError("join_conflict", `the offered circle claims ${offeredHead.ver} versions, more than ${MAX_CHAIN_IN_BUNDLE} can be bootstrapped`);
|
|
533
|
+
const cid = offeredHead.cid;
|
|
534
|
+
const base = {
|
|
535
|
+
cid,
|
|
536
|
+
name: circleDisplayName(offeredHead),
|
|
537
|
+
owner: offeredHead.owner,
|
|
538
|
+
ownerAddress: await app.addressOf(offeredHead.owner),
|
|
539
|
+
founder: offeredHead.founder,
|
|
540
|
+
...(input.inviter ? { inviter: input.inviter } : {}),
|
|
541
|
+
ownershipChanged: offeredHead.owner !== offeredHead.founder,
|
|
542
|
+
policy: circlePolicy(offeredHead),
|
|
543
|
+
};
|
|
544
|
+
const held = await app.store.getCircle(cid);
|
|
545
|
+
if (held?.joinedByMe)
|
|
546
|
+
return { ...base, status: "already", asked: [], answered: [] };
|
|
547
|
+
await app.connect();
|
|
548
|
+
// The owner hint (CLI circle links): its document and join cap let us reach the owner.
|
|
549
|
+
const extraOwnerCaps = [];
|
|
550
|
+
if (input.hint?.join) {
|
|
551
|
+
const cap = joinCapOf(input.hint.join);
|
|
552
|
+
if (cap)
|
|
553
|
+
extraOwnerCaps.push(cap);
|
|
554
|
+
}
|
|
555
|
+
if (input.hint?.doc)
|
|
556
|
+
await app.refreshIdentity(offeredHead.owner, App.relaysOf(input.hint.doc), { force: true });
|
|
557
|
+
await app.state.update("joins", (cur = {}) => {
|
|
558
|
+
const p = cur[cid] ?? { cid, head: input.head, joins: [], asked: [], askedAt: Date.now() };
|
|
559
|
+
if (input.inviter)
|
|
560
|
+
p.inviter = input.inviter;
|
|
561
|
+
if (input.hint)
|
|
562
|
+
p.hint = input.hint;
|
|
563
|
+
if (input.joins)
|
|
564
|
+
p.joins = [...new Set([...p.joins, ...input.joins])];
|
|
565
|
+
return { next: { ...cur, [cid]: p }, result: undefined };
|
|
566
|
+
});
|
|
567
|
+
// The inviter's chain is its answer, stored like any other (bounded the same way).
|
|
568
|
+
if (input.chain && input.inviter)
|
|
569
|
+
await recordJoinAnswer(app, input.inviter, [...input.chain, input.head], []);
|
|
570
|
+
await app.pool.drain(app.tun.drainQuietMs, app.tun.drainMaxMs);
|
|
571
|
+
const pickFrom = { ...offeredHead, jws: input.head, hash: jwsHash(input.head), signer: offeredHead.owner, isTransfer: false };
|
|
572
|
+
const conf = pickConfirmers(pickFrom, { inviter: input.inviter ?? "", self: app.userId, known: await knownUsers(app) });
|
|
573
|
+
const confirmers = [conf.owner, ...(conf.other ? [conf.other] : [])].filter((u) => u !== app.userId);
|
|
574
|
+
let pending = (await app.state.get("joins"))?.[cid];
|
|
575
|
+
const asked = [];
|
|
576
|
+
// Someone asked before who never answered is asked again once the last ask is a while old: the
|
|
577
|
+
// request (or its answer) can be lost, and an unanswered join otherwise waits for good.
|
|
578
|
+
const reask = (u) => pending !== undefined && Date.now() - (pending.askedAtBy?.[u] ?? pending.askedAt) >= JOIN_REASK_MS;
|
|
579
|
+
let got = await pendingAnswers(app, pending);
|
|
580
|
+
const whole = (u) => answerComplete(got[u]?.versions, got[u]?.parts, offeredHead.ver);
|
|
581
|
+
for (const u of confirmers) {
|
|
582
|
+
if (whole(u) || (pending?.asked.includes(u) && !reask(u)))
|
|
583
|
+
continue;
|
|
584
|
+
// A part answer (parts lost, or the member's hourly budget ran out) is resumed from what is missing.
|
|
585
|
+
const fromVer = contiguousTop(got[u]?.versions) + 1;
|
|
586
|
+
try {
|
|
587
|
+
const want = await wantFor(app, cid, u, fromVer);
|
|
588
|
+
// pre-release soak: recorded as asked BEFORE the want goes out. A member can answer within a second,
|
|
589
|
+
// and another process of ours (the watch) may take the answer before this one gets here: an
|
|
590
|
+
// answer from someone not yet listed as asked is dropped (review L1), and the member's limits
|
|
591
|
+
// then refuse to send it again.
|
|
592
|
+
await markAsked(app, cid, u, Date.now());
|
|
593
|
+
const d = await app.deliver(u, "circle", { own: app.userId, ...CIRCLE_SID }, want, { extraCaps: u === offeredHead.owner ? extraOwnerCaps : [] });
|
|
594
|
+
if (d.relays.length > 0)
|
|
595
|
+
asked.push(u);
|
|
596
|
+
// Not delivered: listed, but due to be asked again on the next try.
|
|
597
|
+
else
|
|
598
|
+
await markAsked(app, cid, u, 0);
|
|
599
|
+
}
|
|
600
|
+
catch (e) {
|
|
601
|
+
await markAsked(app, cid, u, 0).catch(() => undefined);
|
|
602
|
+
app.io.err(`couldn't ask ${await app.addressOf(u)} for the circle's history: ${e.message}`);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
const deadline = Date.now() + (opts.waitSec ?? 0) * 1000;
|
|
606
|
+
// An answer counts once it is whole: a long chain comes in several envelopes (chunked bundles).
|
|
607
|
+
// Keep listening, up to the overall deadline, while parts are still arriving.
|
|
608
|
+
for (;;) {
|
|
609
|
+
pending = (await app.state.get("joins"))?.[cid];
|
|
610
|
+
got = await pendingAnswers(app, pending);
|
|
611
|
+
if (confirmers.every((u) => whole(u)) || Date.now() >= deadline)
|
|
612
|
+
break;
|
|
613
|
+
await app.pool.drain(Math.min(500, app.tun.drainQuietMs), Math.max(0, Math.min(2000, deadline - Date.now())));
|
|
614
|
+
}
|
|
615
|
+
pending = (await app.state.get("joins"))?.[cid];
|
|
616
|
+
got = await pendingAnswers(app, pending);
|
|
617
|
+
// Parts of an answer still on their way wait for the next try (they stay stored); a prefix of
|
|
618
|
+
// the chain counts for nobody, the second confirmer included.
|
|
619
|
+
const answers = Object.fromEntries(Object.entries(got).filter(([u]) => whole(u)).map(([u, a]) => [u, a.versions]));
|
|
620
|
+
const statements = [...new Set([...(pending?.joins ?? []), ...Object.values(got).flatMap((a) => a.joins)])];
|
|
621
|
+
const answered = Object.keys(answers);
|
|
622
|
+
const offeredVersions = answers[offeredHead.owner] ?? (input.inviter ? answers[input.inviter] : undefined);
|
|
623
|
+
if (!offeredVersions) {
|
|
624
|
+
return { ...base, status: "waiting", asked: pending?.asked ?? asked, answered };
|
|
625
|
+
}
|
|
626
|
+
// §3.3 bootstrap: the full chain from version 1, with the offered head on it.
|
|
627
|
+
// A gap (a version or the offered head still missing) means waiting, never a conflict: the join
|
|
628
|
+
// stays pending and the next try asks for what is missing.
|
|
629
|
+
const isGap = (e) => e instanceof P2PError && e.reason === "circle-gap";
|
|
630
|
+
let offered;
|
|
631
|
+
try {
|
|
632
|
+
offered = CircleChain.bootstrap(offeredVersions, { head: input.head, ...(await chainOpts(app)) });
|
|
633
|
+
}
|
|
634
|
+
catch (e) {
|
|
635
|
+
// Re-review N4: a gap with every version up to the offered head's `ver` present means the
|
|
636
|
+
// offered head isn't on the chain at all (a fork): that is a conflict, not something to wait for.
|
|
637
|
+
if (isGap(e) && contiguousTop(offeredVersions) < offeredHead.ver)
|
|
638
|
+
return { ...base, status: "waiting", asked: pending?.asked ?? asked, answered };
|
|
639
|
+
await dropPending(app, cid);
|
|
640
|
+
throw new CliError("join_conflict", `the circle's history doesn't check out: ${e.message}`);
|
|
641
|
+
}
|
|
642
|
+
const chains = [];
|
|
643
|
+
for (const [from, vs] of Object.entries(answers)) {
|
|
644
|
+
try {
|
|
645
|
+
chains.push({ from, chain: CircleChain.bootstrap(vs) });
|
|
646
|
+
}
|
|
647
|
+
catch (e) {
|
|
648
|
+
if (isGap(e))
|
|
649
|
+
continue;
|
|
650
|
+
await dropPending(app, cid);
|
|
651
|
+
throw new CliError("join_conflict", `${await app.addressOf(from)} answered with a chain that doesn't verify; not joining`);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
// Every answer must agree with the offered chain (§3.3: refuse on any conflict).
|
|
655
|
+
if (confirmJoin(offered, chains, { inviter: input.inviter ?? "", self: app.userId }) === "conflict") {
|
|
656
|
+
await dropPending(app, cid);
|
|
657
|
+
throw new CliError("join_conflict", "the answers about this circle conflict with the offered chain: refusing to join (§3.3)");
|
|
658
|
+
}
|
|
659
|
+
// We join the longest consistent chain (an answer may be newer than the link), so the
|
|
660
|
+
// confirmation is judged on THAT head (review M3): its owner, and another member it lists.
|
|
661
|
+
const best = chains.reduce((a, b) => (b.chain.head.ver > a.head.ver ? b.chain : a), offered);
|
|
662
|
+
if (!best.hasAncestor(jwsHash(input.head))) {
|
|
663
|
+
await dropPending(app, cid);
|
|
664
|
+
throw new CliError("join_conflict", "the newest chain the members sent doesn't contain the offered head: refusing to join");
|
|
665
|
+
}
|
|
666
|
+
// What the join is about to commit to is `best`, not the offered head: the caller's rules apply to it.
|
|
667
|
+
const refused = input.accept?.(best.head);
|
|
668
|
+
if (refused) {
|
|
669
|
+
await dropPending(app, cid);
|
|
670
|
+
return { ...base, ...headFacts(best.head), status: "refused", refused, asked: pending?.asked ?? asked, answered };
|
|
671
|
+
}
|
|
672
|
+
const conf2 = pickConfirmers(best.head, { inviter: input.inviter ?? "", self: app.userId, known: await knownUsers(app) });
|
|
673
|
+
// review N-C: like the first confirmers, asked again once its last ask is old (or failed: due 0).
|
|
674
|
+
if (conf2.other && !answers[conf2.other] && (!(pending?.asked ?? []).includes(conf2.other) || reask(conf2.other))) {
|
|
675
|
+
try {
|
|
676
|
+
const want = await wantFor(app, cid, conf2.other, contiguousTop(got[conf2.other]?.versions) + 1);
|
|
677
|
+
// Listed before it goes out (see above); its own ask time, so it is asked again on its own clock.
|
|
678
|
+
await markAsked(app, cid, conf2.other, Date.now());
|
|
679
|
+
const d = await app.deliver(conf2.other, "circle", { own: app.userId, ...CIRCLE_SID }, want);
|
|
680
|
+
if (d.relays.length === 0)
|
|
681
|
+
await markAsked(app, cid, conf2.other, 0);
|
|
682
|
+
}
|
|
683
|
+
catch {
|
|
684
|
+
// not reachable yet
|
|
685
|
+
await markAsked(app, cid, conf2.other, 0).catch(() => undefined);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
const verdict = confirmJoin(best, chains, { inviter: input.inviter ?? "", self: app.userId });
|
|
689
|
+
if (verdict === "conflict") {
|
|
690
|
+
await dropPending(app, cid);
|
|
691
|
+
throw new CliError("join_conflict", "the answers about this circle conflict with each other: refusing to join (§3.3)");
|
|
692
|
+
}
|
|
693
|
+
let confirmation = verdict === "confirmed" ? "confirmed" : "unconfirmed";
|
|
694
|
+
// Owner-only only when the head we join lists nobody but the owner (and us).
|
|
695
|
+
const onlyOwner = best.head.members.every((m) => m === best.head.owner || m === app.userId);
|
|
696
|
+
if (verdict === "unconfirmed" && onlyOwner && answers[best.head.owner])
|
|
697
|
+
confirmation = "owner-only";
|
|
698
|
+
if (confirmation === "unconfirmed") {
|
|
699
|
+
const ok = opts.yes || (opts.confirm ? await opts.confirm("Couldn't confirm this circle with a second member. Join anyway?") : false);
|
|
700
|
+
if (!ok)
|
|
701
|
+
return { ...base, status: "unconfirmed", confirmation, asked: (await app.state.get("joins"))?.[cid]?.asked ?? pending?.asked ?? [], answered };
|
|
702
|
+
}
|
|
703
|
+
const versions = best.versionsFrom(1);
|
|
704
|
+
if (!(await app.store.getCircle(cid)))
|
|
705
|
+
await storeOfferedCircle(app.store, versions, await chainOpts(app));
|
|
706
|
+
await applyCircleBundle(app.store, { circles: versions, joins: statements, ops: [] }, await chainOpts(app));
|
|
707
|
+
const c = (await loadCircle(app.store, cid));
|
|
708
|
+
// A circle already stored here may be ahead of `best` after the merge: the join signs onto the stored
|
|
709
|
+
// head, so the caller's rules see that one too, before anything is signed.
|
|
710
|
+
const late = c.chain.head.hash === best.head.hash ? undefined : input.accept?.(c.chain.head);
|
|
711
|
+
if (late) {
|
|
712
|
+
await dropPending(app, cid);
|
|
713
|
+
return { ...base, ...headFacts(c.chain.head), status: "refused", refused: late, asked: pending?.asked ?? [], answered };
|
|
714
|
+
}
|
|
715
|
+
await signOwnJoin(app, cid, c.chain.head.hash);
|
|
716
|
+
const mine = (await loadCircle(app.store, cid)).book[app.userId].jws;
|
|
717
|
+
const delivered = [];
|
|
718
|
+
const targets = [...new Set([c.chain.head.owner, ...c.chain.head.admins])].filter((u) => u !== app.userId);
|
|
719
|
+
for (const u of targets) {
|
|
720
|
+
try {
|
|
721
|
+
delivered.push(await deliverCircle(app, u, { joins: [mine] }, u === c.chain.head.owner ? extraOwnerCaps : []));
|
|
722
|
+
}
|
|
723
|
+
catch (e) {
|
|
724
|
+
app.io.err(`couldn't send your join to ${await app.addressOf(u)}: ${e.message}`);
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
await dropPending(app, cid);
|
|
728
|
+
await dropHeld(app, (h) => h.cid === cid && h.type === "circle-invite");
|
|
729
|
+
const exp = await exportCircle(app, cid);
|
|
730
|
+
if (exp)
|
|
731
|
+
await sendSync(app, { circles: [exp] });
|
|
732
|
+
if (!delivered.some((d) => d.relays.length > 0) && targets.length > 0) {
|
|
733
|
+
throw new CliError("undelivered", "joined locally, but the join was delivered via 0 relays: the owner doesn't know yet", { cid });
|
|
734
|
+
}
|
|
735
|
+
return {
|
|
736
|
+
...base,
|
|
737
|
+
// As joined: the stored chain's head, which may be newer than the offered one.
|
|
738
|
+
...headFacts(c.chain.head),
|
|
739
|
+
status: "joined",
|
|
740
|
+
confirmation,
|
|
741
|
+
asked: pending?.asked ?? [],
|
|
742
|
+
answered,
|
|
743
|
+
delivered,
|
|
744
|
+
...(circlePolicy(c.chain.head) === "open" ? { openWarning: true } : {}),
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
function headFacts(h) {
|
|
748
|
+
return { name: circleDisplayName(h), owner: h.owner, policy: circlePolicy(h), ownershipChanged: h.owner !== h.founder };
|
|
749
|
+
}
|
|
750
|
+
async function dropPending(app, cid) {
|
|
751
|
+
const gone = await app.state.update("joins", (cur = {}) => {
|
|
752
|
+
if (!cur[cid])
|
|
753
|
+
return { result: undefined };
|
|
754
|
+
const { [cid]: was, ...rest } = cur;
|
|
755
|
+
return { next: rest, result: was };
|
|
756
|
+
});
|
|
757
|
+
if (!gone)
|
|
758
|
+
return;
|
|
759
|
+
await dropAnswers(app, cid, gone.answerFrom ?? []);
|
|
760
|
+
// L1: the answer caps this join handed out have done their job (joined, or refused).
|
|
761
|
+
const ids = new Set(gone.answerCaps ?? []);
|
|
762
|
+
if (ids.size > 0) {
|
|
763
|
+
const caps = await app.store.takeCapsIssued((c) => ids.has(c.capid));
|
|
764
|
+
await app.revokeCaps(caps).catch(() => 0);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
export async function joinFromLink(app, link, opts) {
|
|
768
|
+
let parsed;
|
|
769
|
+
try {
|
|
770
|
+
parsed = parseCircleLink(link);
|
|
771
|
+
}
|
|
772
|
+
catch (e) {
|
|
773
|
+
if (e instanceof CliError)
|
|
774
|
+
throw e;
|
|
775
|
+
throw new CliError("usage", "that is not a circle link (p2p://circle/… or https://ix-infra.com/p2p/c#…)");
|
|
776
|
+
}
|
|
777
|
+
// The relays the link names (its owner's document, its join cap) are dialed before anyone confirms anything.
|
|
778
|
+
const hinted = [...App.relaysOf(parsed.hint?.doc), ...(capPeek(joinCapOf(parsed.hint?.join ?? "") ?? "")?.relays ?? [])];
|
|
779
|
+
await guardForeignRelays(app, hinted, "circle link", opts.allowPrivateRelay || app.env.P2P_ALLOW_PRIVATE_RELAY === "1");
|
|
780
|
+
return joinCircle(app, parsed, opts);
|
|
781
|
+
}
|
|
782
|
+
export async function joinFromHeld(app, item, opts) {
|
|
783
|
+
return joinCircle(app, { head: item.head, chain: item.chain, joins: item.joins, inviter: item.from }, opts);
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Open circles (P2, pre-release review M4): re-sign our join (n+1, a fresh cap of at
|
|
787
|
+
* most 14 days) when the owner removed anyone since our cap was issued, when
|
|
788
|
+
* the cap outlives 14 days, or when it lapses within 3 days; revoke the old
|
|
789
|
+
* cap at its relays, and tell the members. Returns how many were renewed.
|
|
790
|
+
*/
|
|
791
|
+
export async function renewOpenJoinCaps(app) {
|
|
792
|
+
const actions = await openCircleCapActions(app.store, app.userId);
|
|
793
|
+
let n = 0;
|
|
794
|
+
for (const a of actions) {
|
|
795
|
+
const c = await loadCircle(app.store, a.cid);
|
|
796
|
+
if (!c)
|
|
797
|
+
continue;
|
|
798
|
+
const cap = createCap(app.device, app.keys.cert, { purpose: "join", relays: app.relays, ttlSec: a.capTtlSec });
|
|
799
|
+
const jws = createMembershipStatement(app.signer(), { cid: a.cid, n: a.nextN, op: "join", at: a.at, cap });
|
|
800
|
+
const v = await verifyMembershipStatement(jws, app.signerCtx());
|
|
801
|
+
await recordJoin(app, v);
|
|
802
|
+
await app.recordIssued(cap);
|
|
803
|
+
if (a.revoke) {
|
|
804
|
+
const old = await app.store.takeCapsIssued((x) => x.capid === a.revoke.capid);
|
|
805
|
+
await app.revokeCaps(old.length > 0 ? old : [{ capid: a.revoke.capid, iss: app.userId, sub: "*", relays: a.revoke.relays, kinds: ["*"], exp: 0, jws: "" }]);
|
|
806
|
+
}
|
|
807
|
+
for (const m of c.chain.head.members) {
|
|
808
|
+
if (m === app.userId)
|
|
809
|
+
continue;
|
|
810
|
+
await deliverCircle(app, m, { joins: [jws] }, memberCaps(c, m)).catch(() => undefined);
|
|
811
|
+
}
|
|
812
|
+
n++;
|
|
813
|
+
}
|
|
814
|
+
return n;
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* §3.2 block, for circles: the blocked user holds our join cap (sub "*"), so
|
|
818
|
+
* revoking friend caps alone doesn't stop it reaching our mailbox. In every
|
|
819
|
+
* joined circle that lists them, re-sign our join with a fresh cap, revoke the
|
|
820
|
+
* old one at its relays, and send the new statement to the other members
|
|
821
|
+
* (never to the blocked user). Returns the circles re-keyed.
|
|
822
|
+
*/
|
|
823
|
+
export async function rekeyJoinsExcluding(app, blocked) {
|
|
824
|
+
const out = [];
|
|
825
|
+
for (const rec of await app.store.listCircles()) {
|
|
826
|
+
if (!rec.joinedByMe)
|
|
827
|
+
continue;
|
|
828
|
+
const c = await loadCircle(app.store, rec.cid);
|
|
829
|
+
if (!c || !c.chain.head.members.includes(blocked))
|
|
830
|
+
continue;
|
|
831
|
+
const mine = c.book[app.userId];
|
|
832
|
+
if (!mine || mine.op !== "join")
|
|
833
|
+
continue;
|
|
834
|
+
const oldCap = joinCapOf(mine.jws);
|
|
835
|
+
const cap = createCap(app.device, app.keys.cert, { purpose: "join", relays: app.relays, ttlSec: joinCapTtlFor(circlePolicy(c.chain.head)) });
|
|
836
|
+
const jws = createMembershipStatement(app.signer(), { cid: rec.cid, n: nextMembershipN(rec.myN), op: "join", at: c.chain.head.hash, cap });
|
|
837
|
+
const v = await verifyMembershipStatement(jws, app.signerCtx());
|
|
838
|
+
await recordJoin(app, v);
|
|
839
|
+
await app.recordIssued(cap);
|
|
840
|
+
if (oldCap) {
|
|
841
|
+
const p = decodeTyped(oldCap, TYP3.cap).payload;
|
|
842
|
+
const taken = await app.store.takeCapsIssued((x) => x.capid === p.capid);
|
|
843
|
+
const relays = Array.isArray(p.relays) ? p.relays : app.relays;
|
|
844
|
+
await app.revokeCaps(taken.length > 0 ? taken : [{ capid: String(p.capid), iss: app.userId, sub: "*", relays, kinds: ["*"], exp: 0, jws: oldCap }]);
|
|
845
|
+
}
|
|
846
|
+
for (const m of c.chain.head.members) {
|
|
847
|
+
if (m === app.userId || m === blocked)
|
|
848
|
+
continue;
|
|
849
|
+
await deliverCircle(app, m, { joins: [jws] }, memberCaps(c, m)).catch(() => undefined);
|
|
850
|
+
}
|
|
851
|
+
out.push(rec.cid);
|
|
852
|
+
}
|
|
853
|
+
return out;
|
|
854
|
+
}
|
|
855
|
+
// ---------------------------------------------------------------------------
|
|
856
|
+
// Leaving, proposals, transfer, policy
|
|
857
|
+
export async function leaveCircle(app, cidOrName) {
|
|
858
|
+
// Handle what's queued first: the circle bundles waiting here carry the members' join statements,
|
|
859
|
+
// whose caps are how a member we aren't friends with is reached. Without them a fresh member's
|
|
860
|
+
// leave reached nobody (told 0), the owner kept listing it, and its later re-join diverged.
|
|
861
|
+
await app.connectAndDrain();
|
|
862
|
+
const c = await resolveCircle(app, cidOrName);
|
|
863
|
+
const cid = c.record.cid;
|
|
864
|
+
if (c.chain.head.owner === app.userId)
|
|
865
|
+
throw new CliError("owner_cannot_leave", "you own this circle: hand it over first (`p2p circle transfer`)");
|
|
866
|
+
const jws = createMembershipStatement(app.signer(), { cid, n: nextMembershipN(c.record.myN), op: "leave" });
|
|
867
|
+
const v = await verifyMembershipStatement(jws, app.signerCtx());
|
|
868
|
+
let told = 0;
|
|
869
|
+
// §3.3: a leave goes to every member, who honour it at once.
|
|
870
|
+
for (const m of c.chain.head.members) {
|
|
871
|
+
if (m === app.userId)
|
|
872
|
+
continue;
|
|
873
|
+
try {
|
|
874
|
+
const d = await deliverCircle(app, m, { joins: [jws] }, memberCaps(c, m));
|
|
875
|
+
if (d.relays.length > 0)
|
|
876
|
+
told++;
|
|
877
|
+
}
|
|
878
|
+
catch {
|
|
879
|
+
// unreachable member
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
await recordOwnLeave(app.store, app.userId, v);
|
|
883
|
+
const exp = await exportCircle(app, cid);
|
|
884
|
+
if (exp)
|
|
885
|
+
await sendSync(app, { circles: [exp] });
|
|
886
|
+
if (app.self?.defaultCircle === cid)
|
|
887
|
+
await app.updateSelf((s) => ({ ...s, defaultCircle: undefined }));
|
|
888
|
+
return { cid, left: true, told };
|
|
889
|
+
}
|
|
890
|
+
const OPS = ["add", "remove", "promote", "demote", "rename"];
|
|
891
|
+
export async function propose(app, cidOrName, op, arg) {
|
|
892
|
+
if (!OPS.includes(op))
|
|
893
|
+
throw new CliError("usage", `op must be one of ${OPS.join(", ")}`);
|
|
894
|
+
await app.connectAndDrain();
|
|
895
|
+
const c = await resolveCircle(app, cidOrName);
|
|
896
|
+
const cid = c.record.cid;
|
|
897
|
+
const h = c.chain.head;
|
|
898
|
+
const target = op === "rename" ? undefined : await app.resolveUser(arg);
|
|
899
|
+
if (h.owner === app.userId) {
|
|
900
|
+
let members = [...h.members];
|
|
901
|
+
let admins = [...h.admins];
|
|
902
|
+
let name = h.name;
|
|
903
|
+
switch (op) {
|
|
904
|
+
case "add":
|
|
905
|
+
if (!members.includes(target))
|
|
906
|
+
members.push(target);
|
|
907
|
+
break;
|
|
908
|
+
case "remove":
|
|
909
|
+
if (target === h.owner)
|
|
910
|
+
throw new CliError("usage", "the owner can't be removed");
|
|
911
|
+
admins = admins.filter((a) => a !== target);
|
|
912
|
+
members = members.filter((m) => m !== target);
|
|
913
|
+
break;
|
|
914
|
+
case "promote":
|
|
915
|
+
if (!members.includes(target))
|
|
916
|
+
throw new CliError("usage", "only members can be admins");
|
|
917
|
+
if (!admins.includes(target))
|
|
918
|
+
admins.push(target);
|
|
919
|
+
break;
|
|
920
|
+
case "demote":
|
|
921
|
+
admins = admins.filter((a) => a !== target);
|
|
922
|
+
break;
|
|
923
|
+
case "rename":
|
|
924
|
+
if (arg.trim() === "" || [...arg].length > 128)
|
|
925
|
+
throw new CliError("usage", "a circle name is 1–128 characters");
|
|
926
|
+
name = arg;
|
|
927
|
+
break;
|
|
928
|
+
}
|
|
929
|
+
if (name === h.name && admins.join() === h.admins.join() && members.join() === h.members.join())
|
|
930
|
+
return { cid, op, applied: false, ver: h.ver };
|
|
931
|
+
const v = await ownerPublish(app, cid, { members, admins, name });
|
|
932
|
+
return { cid, op, applied: true, ver: v.ver };
|
|
933
|
+
}
|
|
934
|
+
if (!h.admins.includes(app.userId))
|
|
935
|
+
throw new CliError("not_admin", "only admins propose changes (the owner applies them)");
|
|
936
|
+
const p = createProposal(app.signer(), { cid, base: h.ver, op: op, ...(target ? { target } : { name: arg }) });
|
|
937
|
+
const d = await deliverCircle(app, h.owner, { ops: [p] }, ownerCaps(c));
|
|
938
|
+
if (d.relays.length === 0)
|
|
939
|
+
throw new CliError("undelivered", "the proposal was delivered via 0 relays");
|
|
940
|
+
return { cid, op, applied: false, sentTo: h.owner };
|
|
941
|
+
}
|
|
942
|
+
export async function transfer(app, cidOrName, who, opts) {
|
|
943
|
+
await app.connectAndDrain();
|
|
944
|
+
const c = await resolveCircle(app, cidOrName);
|
|
945
|
+
const cid = c.record.cid;
|
|
946
|
+
const h = c.chain.head;
|
|
947
|
+
if (opts.accept) {
|
|
948
|
+
// The successor consents to exactly {cid, ver, prev} (§3.3 rule 3).
|
|
949
|
+
const ik = app.requireKeyholder("Consenting to take over a circle");
|
|
950
|
+
if (!h.members.includes(app.userId))
|
|
951
|
+
throw new CliError("usage", "only a member can take over a circle");
|
|
952
|
+
const consent = createCircleTransferAccept(ik, { cid, ver: h.ver + 1, prev: h.hash });
|
|
953
|
+
const d = await deliverCircle(app, h.owner, { ops: [consent] }, ownerCaps(c));
|
|
954
|
+
return { cid, consent, sentTo: h.owner, delivered: d.relays.length };
|
|
955
|
+
}
|
|
956
|
+
if (h.owner !== app.userId)
|
|
957
|
+
throw new CliError("not_owner", "only the owner can hand the circle over");
|
|
958
|
+
if (!who)
|
|
959
|
+
throw new CliError("usage", "name the new owner");
|
|
960
|
+
const u = await app.resolveUser(who);
|
|
961
|
+
if (!h.members.includes(u))
|
|
962
|
+
throw new CliError("usage", "the new owner must be a member");
|
|
963
|
+
const consent = opts.consent ?? (await app.state.get("transfers"))?.[cid]?.[u];
|
|
964
|
+
if (!consent) {
|
|
965
|
+
throw new CliError("needs_consent", `${await app.addressOf(u)} must consent first: ask them to run \`p2p circle transfer ${cid} --accept\`, then run this again`);
|
|
966
|
+
}
|
|
967
|
+
const t = decodeTyped(consent, TYP3.circleAccept).payload;
|
|
968
|
+
if (t.iss !== u || t.cid !== cid || t.ver !== h.ver + 1 || t.prev !== h.hash || typeof t.ik !== "string") {
|
|
969
|
+
throw new CliError("stale_consent", "that consent is for another state of the circle: ask for a fresh `--accept`");
|
|
970
|
+
}
|
|
971
|
+
const v = await ownerPublish(app, cid, { newOwner: { userId: u, ik: t.ik, transfer: consent } });
|
|
972
|
+
return { cid, owner: u, address: await app.addressOf(u), ver: v.ver };
|
|
973
|
+
}
|
|
974
|
+
export async function setPolicy(app, cidOrName, policy) {
|
|
975
|
+
if (policy !== "invite" && policy !== "open")
|
|
976
|
+
throw new CliError("usage", "policy is invite or open");
|
|
977
|
+
await app.connectAndDrain();
|
|
978
|
+
const c = await resolveCircle(app, cidOrName);
|
|
979
|
+
if (circlePolicy(c.chain.head) === policy)
|
|
980
|
+
return { cid: c.record.cid, policy, ver: c.chain.head.ver };
|
|
981
|
+
const v = await ownerPublish(app, c.record.cid, { policy });
|
|
982
|
+
return { cid: c.record.cid, policy, ver: v.ver };
|
|
983
|
+
}
|
|
984
|
+
/**
|
|
985
|
+
* §3.3 "the owner may also set a policy to hold proposals for approval":
|
|
986
|
+
* a local, per-circle setting on the owner's devices. While on, admins'
|
|
987
|
+
* proposals and rotated members (§2.8) wait in `p2p held` for the owner.
|
|
988
|
+
*/
|
|
989
|
+
export async function setCircleHold(app, cidOrName, on) {
|
|
990
|
+
const c = await resolveCircle(app, cidOrName);
|
|
991
|
+
const cid = c.record.cid;
|
|
992
|
+
if (on !== undefined) {
|
|
993
|
+
if (c.chain.head.owner !== app.userId)
|
|
994
|
+
throw new CliError("not_owner", "only the owner holds changes to a circle for approval");
|
|
995
|
+
await app.state.update("circleHold", (cur = {}) => {
|
|
996
|
+
const next = { ...cur };
|
|
997
|
+
if (on)
|
|
998
|
+
next[cid] = true;
|
|
999
|
+
else
|
|
1000
|
+
delete next[cid];
|
|
1001
|
+
return { next, result: undefined };
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
return { cid, hold: await circleHeld(app, cid) };
|
|
1005
|
+
}
|
|
1006
|
+
/** Owner: approves a held join request. */
|
|
1007
|
+
export async function approveJoinRequest(app, item) {
|
|
1008
|
+
const c = await loadCircle(app.store, item.cid);
|
|
1009
|
+
if (!c)
|
|
1010
|
+
throw new CliError("not_found", "circle not held");
|
|
1011
|
+
await app.connect();
|
|
1012
|
+
const h = c.chain.head;
|
|
1013
|
+
if (h.members.includes(item.from))
|
|
1014
|
+
return { cid: c.record.cid, added: item.from, ver: h.ver };
|
|
1015
|
+
const v = await ownerPublish(app, c.record.cid, { members: [...h.members, item.from] });
|
|
1016
|
+
return { cid: c.record.cid, added: item.from, ver: v.ver };
|
|
1017
|
+
}
|
|
1018
|
+
// ---------------------------------------------------------------------------
|
|
1019
|
+
// Inbound `circle` envelopes
|
|
1020
|
+
export async function onCircleEnvelope(app, env, r, relay) {
|
|
1021
|
+
const pt = r.plaintext;
|
|
1022
|
+
const info = r.circle;
|
|
1023
|
+
const from = await fromOf(app, r);
|
|
1024
|
+
const at = r.envelope.ts;
|
|
1025
|
+
if (pt.want) {
|
|
1026
|
+
await answerWant(app, r.envelope.from, r.envelope.fdid, pt.want, info.authorizedBy, relay, pt.cap, pt.pow, { ts: r.envelope.ts });
|
|
1027
|
+
return [];
|
|
1028
|
+
}
|
|
1029
|
+
const circles = pt.circles ?? [];
|
|
1030
|
+
const joins = pt.joins ?? [];
|
|
1031
|
+
const ops = pt.ops ?? [];
|
|
1032
|
+
const events = [];
|
|
1033
|
+
// Versions of circles we don't hold: an answer to a pending join, or an invite to hold.
|
|
1034
|
+
const byCid = new Map();
|
|
1035
|
+
for (const j of circles) {
|
|
1036
|
+
try {
|
|
1037
|
+
const cid = parseCircleVersion(j).cid;
|
|
1038
|
+
byCid.set(cid, [...(byCid.get(cid) ?? []), j]);
|
|
1039
|
+
}
|
|
1040
|
+
catch {
|
|
1041
|
+
// ignore malformed
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
const known = [];
|
|
1045
|
+
for (const [cid, vs] of byCid) {
|
|
1046
|
+
const cidJoins = joins.filter((j) => {
|
|
1047
|
+
try {
|
|
1048
|
+
return decodeTyped(j, TYP3.join).payload.cid === cid;
|
|
1049
|
+
}
|
|
1050
|
+
catch {
|
|
1051
|
+
return false;
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
if (await app.store.getCircle(cid)) {
|
|
1055
|
+
known.push(...vs);
|
|
1056
|
+
// A circle we still hold but are joining again (we left it): the members we asked answer
|
|
1057
|
+
// here too. Without this a former member's join waited for an answer that never counted.
|
|
1058
|
+
if (await recordJoinAnswer(app, r.envelope.from, vs, cidJoins, { part: pt.part }))
|
|
1059
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: "join-answer", cid }, {}, cid));
|
|
1060
|
+
continue;
|
|
1061
|
+
}
|
|
1062
|
+
if (await recordJoinAnswer(app, r.envelope.from, vs, cidJoins, { part: pt.part })) {
|
|
1063
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: "join-answer", cid }, {}, cid));
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
const head = vs.map((v) => parseCircleVersion(v)).sort((a, b) => b.ver - a.ver)[0];
|
|
1067
|
+
const headJws = vs.find((v) => parseCircleVersion(v).ver === head.ver && parseCircleVersion(v).cid === cid);
|
|
1068
|
+
const item = withHeldId({ type: "circle-invite", from: r.envelope.from, at, head: headJws, chain: vs, joins: cidJoins, cid });
|
|
1069
|
+
await hold(app, item);
|
|
1070
|
+
events.push(makeEvent(env, "p2p.held", at, { from, held: { id: item.id, type: item.type, cid } }, {}, cid));
|
|
1071
|
+
}
|
|
1072
|
+
// The statements-only part of a chunked answer to a pending join (its versions came before).
|
|
1073
|
+
const loose = new Map();
|
|
1074
|
+
for (const j of joins) {
|
|
1075
|
+
try {
|
|
1076
|
+
const cid = decodeTyped(j, TYP3.join).payload.cid;
|
|
1077
|
+
if (typeof cid === "string" && !byCid.has(cid))
|
|
1078
|
+
loose.set(cid, [...(loose.get(cid) ?? []), j]);
|
|
1079
|
+
}
|
|
1080
|
+
catch {
|
|
1081
|
+
// ignore malformed
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
// Also for a circle we still hold but are joining again (L5): recordJoinAnswer matches only a pending join.
|
|
1085
|
+
for (const [cid, js] of loose)
|
|
1086
|
+
await recordJoinAnswer(app, r.envelope.from, [], js, { cid, part: pt.part });
|
|
1087
|
+
const before = new Map();
|
|
1088
|
+
for (const cid of info.cids) {
|
|
1089
|
+
const c = await loadCircle(app.store, cid);
|
|
1090
|
+
if (c)
|
|
1091
|
+
before.set(cid, { ver: c.chain.head.ver, member: c.chain.head.members.includes(app.userId) });
|
|
1092
|
+
}
|
|
1093
|
+
const res = await applyCircleBundle(app.store, { circles: known, joins, ops }, await chainOpts(app));
|
|
1094
|
+
for (const [cid, results] of Object.entries(res.versions)) {
|
|
1095
|
+
const c = await loadCircle(app.store, cid);
|
|
1096
|
+
if (!c)
|
|
1097
|
+
continue;
|
|
1098
|
+
const b = before.get(cid);
|
|
1099
|
+
for (const x of results)
|
|
1100
|
+
if (x.alert)
|
|
1101
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: "alert", cid, alert: x.alert }, {}, `${cid}${x.hash}`));
|
|
1102
|
+
if (b && c.chain.head.ver !== b.ver) {
|
|
1103
|
+
const removed = b.member && !c.chain.head.members.includes(app.userId);
|
|
1104
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: removed ? "removed" : "version", cid, name: circleDisplayName(c.chain.head), ver: c.chain.head.ver, policy: circlePolicy(c.chain.head) }, {}, cid));
|
|
1105
|
+
if (removed) {
|
|
1106
|
+
await app.store.updateCircle(cid, (cur) => (cur ? { next: { ...cur, joinedByMe: false }, result: undefined } : { result: undefined }));
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
const applied = res.joins.filter((j) => j.status === "applied" && j.statement).map((j) => j.statement);
|
|
1111
|
+
for (const s of applied) {
|
|
1112
|
+
if (s.iss === app.userId)
|
|
1113
|
+
continue;
|
|
1114
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: s.op === "join" ? "member-joined" : "member-left", cid: s.cid, member: s.iss, address: await app.addressOf(s.iss) }, {}, s.hash));
|
|
1115
|
+
}
|
|
1116
|
+
// Transfer consents (CLI reading: carried in `ops`).
|
|
1117
|
+
for (const j of ops) {
|
|
1118
|
+
try {
|
|
1119
|
+
const t = decodeTyped(j, TYP3.circleAccept).payload;
|
|
1120
|
+
if (typeof t.cid === "string" && t.iss === r.envelope.from) {
|
|
1121
|
+
await app.state.update("transfers", (cur = {}) => ({ next: { ...cur, [t.cid]: { ...(cur[t.cid] ?? {}), [t.iss]: j } }, result: undefined }));
|
|
1122
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: "transfer-consent", cid: t.cid }, {}, j));
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
catch {
|
|
1126
|
+
// a proposal, handled by core
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
if (Object.keys(res.versions).length > 0)
|
|
1130
|
+
await renewOpenJoinCaps(app).catch(() => 0);
|
|
1131
|
+
const statements = res.joins.map((j) => j.statement).filter((s) => !!s);
|
|
1132
|
+
// §2.8 (P3): a rotated member's join with the statement. The owner swaps old for new (or holds it);
|
|
1133
|
+
// its statements are then no ordinary join request.
|
|
1134
|
+
let rotated;
|
|
1135
|
+
if (pt.rotation) {
|
|
1136
|
+
const o = await onRotationJoin(app, env, at, from, pt.rotation, r.envelope.from, statements);
|
|
1137
|
+
events.push(...o.events);
|
|
1138
|
+
rotated = { iss: r.envelope.from, ...(o.old ? { old: o.old } : {}), handled: o.handled };
|
|
1139
|
+
}
|
|
1140
|
+
// The old identity's leave that came with it waits too: the swap replaces old with new in one
|
|
1141
|
+
// version, so a held swap leaves the old member listed (with no standing) until it is decided.
|
|
1142
|
+
const ordinary = (s) => !(rotated && rotated.handled.has(s.cid) && (s.iss === rotated.iss || s.iss === rotated.old));
|
|
1143
|
+
// Owner duties for circles we own.
|
|
1144
|
+
const owned = new Set();
|
|
1145
|
+
for (const s of statements)
|
|
1146
|
+
owned.add(s.cid);
|
|
1147
|
+
for (const o of res.ops)
|
|
1148
|
+
if (o.status === "queued" && o.proposal)
|
|
1149
|
+
owned.add(o.proposal.cid);
|
|
1150
|
+
for (const cid of owned) {
|
|
1151
|
+
const c = await loadCircle(app.store, cid);
|
|
1152
|
+
if (!c || c.chain.head.owner !== app.userId || !app.isKeyholder)
|
|
1153
|
+
continue;
|
|
1154
|
+
events.push(...(await ownerDuties(app, env, at, from, c, statements.filter((s) => s.cid === cid && ordinary(s)), applied.some((s) => s.cid === cid), res.ops.some((o) => o.status === "queued" && o.proposal?.cid === cid))));
|
|
1155
|
+
}
|
|
1156
|
+
return events;
|
|
1157
|
+
}
|
|
1158
|
+
async function ownerDuties(app, env, at, from, c, statements, anyApplied, proposals) {
|
|
1159
|
+
const cid = c.record.cid;
|
|
1160
|
+
const events = [];
|
|
1161
|
+
const blocks = new Set((await app.store.listBlocks()).map((b) => b.userId));
|
|
1162
|
+
const h = c.chain.head;
|
|
1163
|
+
let members = [...h.members];
|
|
1164
|
+
let admins = [...h.admins];
|
|
1165
|
+
let name = h.name;
|
|
1166
|
+
if (proposals) {
|
|
1167
|
+
// §3.3: the owner may hold proposals for approval (`p2p circle hold`).
|
|
1168
|
+
const r = await applyOwnerProposals(app.store, cid, { ...app.signerCtx(), hold: await circleHeld(app, cid) });
|
|
1169
|
+
if (r?.draft) {
|
|
1170
|
+
members = r.draft.members;
|
|
1171
|
+
admins = r.draft.admins;
|
|
1172
|
+
name = r.draft.name;
|
|
1173
|
+
}
|
|
1174
|
+
for (const x of r?.results ?? [])
|
|
1175
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: "proposal", cid, status: x.status, proposer: x.iss }, {}, x.nonce));
|
|
1176
|
+
}
|
|
1177
|
+
for (const s of statements) {
|
|
1178
|
+
if (s.op === "leave") {
|
|
1179
|
+
if (members.includes(s.iss) && s.iss !== h.owner && c.book[s.iss]?.hash === s.hash) {
|
|
1180
|
+
members = members.filter((m) => m !== s.iss);
|
|
1181
|
+
admins = admins.filter((m) => m !== s.iss);
|
|
1182
|
+
}
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
if (members.includes(s.iss))
|
|
1186
|
+
continue;
|
|
1187
|
+
if (blocks.has(s.iss))
|
|
1188
|
+
continue;
|
|
1189
|
+
const d = await decideOpenJoinFor(app.store, s);
|
|
1190
|
+
if (d.decision === "accept")
|
|
1191
|
+
members.push(s.iss);
|
|
1192
|
+
else if (d.decision === "hold") {
|
|
1193
|
+
const item = withHeldId({ type: "circle-join", from: s.iss, at, cid, head: h.jws, join: s.jws, reason: d.reason });
|
|
1194
|
+
await hold(app, item);
|
|
1195
|
+
events.push(makeEvent(env, "p2p.held", at, { from, held: { id: item.id, type: item.type, cid, reason: d.reason } }, {}, s.hash));
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
const changed = name !== h.name || admins.join() !== h.admins.join() || members.join() !== h.members.join();
|
|
1199
|
+
if (changed) {
|
|
1200
|
+
const v = await ownerPublish(app, cid, { members, admins, name });
|
|
1201
|
+
events.push(makeEvent(env, "p2p.circle", at, { from, event: "published", cid, ver: v.ver, name: circleDisplayName(v) }, {}, `${cid}${v.ver}`));
|
|
1202
|
+
}
|
|
1203
|
+
else if (anyApplied) {
|
|
1204
|
+
// A statement changed standing without a new version: tell the members.
|
|
1205
|
+
await distribute(app, cid);
|
|
1206
|
+
}
|
|
1207
|
+
return events;
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Answers to one asker's `want`s per rolling hour (all circles; members too, review M1). The byte
|
|
1211
|
+
* budgets (per asker, per circle, the non-member pools) are what bound the cost; this only caps
|
|
1212
|
+
* how often. 3 was too few: a member who leaves and joins again a few times in an hour (each join
|
|
1213
|
+
* needs an answer) was refused, and could not join until the hour passed (pre-release soak, seed 21).
|
|
1214
|
+
*/
|
|
1215
|
+
export const ANSWERS_PER_ASKER_PER_HOUR = ANSWERS_PER_HOUR;
|
|
1216
|
+
const HOUR_MS = 3_600_000;
|
|
1217
|
+
function prunedAnswers(cur, now) {
|
|
1218
|
+
const fresh = (xs) => (xs ?? []).filter((x) => now - x.at < HOUR_MS);
|
|
1219
|
+
const by = {};
|
|
1220
|
+
for (const [u, ts] of Object.entries(cur?.by ?? {})) {
|
|
1221
|
+
const keep = ts.filter((t) => now - t < HOUR_MS);
|
|
1222
|
+
if (keep.length > 0)
|
|
1223
|
+
by[u] = keep;
|
|
1224
|
+
}
|
|
1225
|
+
const bytes = {};
|
|
1226
|
+
for (const [u, xs] of Object.entries(cur?.bytes ?? {})) {
|
|
1227
|
+
const keep = fresh(xs);
|
|
1228
|
+
if (keep.length > 0)
|
|
1229
|
+
bytes[u] = keep;
|
|
1230
|
+
}
|
|
1231
|
+
const last = {};
|
|
1232
|
+
for (const [k, v] of Object.entries(cur?.last ?? {}))
|
|
1233
|
+
if (now - v.at < HOUR_MS)
|
|
1234
|
+
last[k] = v;
|
|
1235
|
+
const members = {};
|
|
1236
|
+
for (const [c, xs] of Object.entries(cur?.members ?? {})) {
|
|
1237
|
+
const keep = fresh(xs);
|
|
1238
|
+
if (keep.length > 0)
|
|
1239
|
+
members[c] = keep;
|
|
1240
|
+
}
|
|
1241
|
+
const refused = {};
|
|
1242
|
+
for (const [k, t] of Object.entries(cur?.refused ?? {}))
|
|
1243
|
+
if (now - t < HOUR_MS)
|
|
1244
|
+
refused[k] = t;
|
|
1245
|
+
// review N-B: bounded however many askers and circles there are. Maps keep their most recent keys;
|
|
1246
|
+
// the pool lists fold their oldest entries into one (dated by the newest folded), so evicting
|
|
1247
|
+
// never frees budget a pool already spent.
|
|
1248
|
+
const latest = (xs) => xs.reduce((a, b) => (b > a ? b : a), 0);
|
|
1249
|
+
const capMap = (m, max, at) => {
|
|
1250
|
+
const keys = Object.keys(m);
|
|
1251
|
+
if (keys.length <= max)
|
|
1252
|
+
return m;
|
|
1253
|
+
return Object.fromEntries(keys.map((k) => [k, m[k]]).sort((a, b) => at(b[1]) - at(a[1])).slice(0, max));
|
|
1254
|
+
};
|
|
1255
|
+
const fold = (xs, max) => {
|
|
1256
|
+
if (xs.length <= max)
|
|
1257
|
+
return xs;
|
|
1258
|
+
const sorted = [...xs].sort((a, b) => a.at - b.at);
|
|
1259
|
+
const old = sorted.slice(0, xs.length - max + 1);
|
|
1260
|
+
const merged = { ...old[old.length - 1], bytes: old.reduce((n, x) => n + x.bytes, 0) };
|
|
1261
|
+
return [merged, ...sorted.slice(xs.length - max + 1)];
|
|
1262
|
+
};
|
|
1263
|
+
const foldedMembers = {};
|
|
1264
|
+
for (const [c, xs] of Object.entries(capMap(members, MAX_ANSWER_CIRCLES, (v) => latest(v.map((x) => x.at)))))
|
|
1265
|
+
foldedMembers[c] = fold(xs, MAX_POOL_ENTRIES);
|
|
1266
|
+
const byKept = capMap(by, MAX_ANSWER_ASKERS, latest);
|
|
1267
|
+
const bytesKept = {};
|
|
1268
|
+
for (const [u, xs] of Object.entries(bytes))
|
|
1269
|
+
if (byKept[u] || Object.keys(bytes).length <= MAX_ANSWER_ASKERS)
|
|
1270
|
+
bytesKept[u] = fold(xs, MAX_POOL_ENTRIES);
|
|
1271
|
+
return {
|
|
1272
|
+
by: byKept,
|
|
1273
|
+
bytes: capMap(bytesKept, MAX_ANSWER_ASKERS, (v) => latest(v.map((x) => x.at))),
|
|
1274
|
+
sent: fold(fresh(cur?.sent), MAX_POOL_ENTRIES),
|
|
1275
|
+
last: capMap(last, MAX_ANSWER_ASKERS, (v) => v.at),
|
|
1276
|
+
members: foldedMembers,
|
|
1277
|
+
pows: keepPows(fresh(cur?.pows), now),
|
|
1278
|
+
refused: capMap(refused, MAX_ANSWER_ASKERS, (t) => t),
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Spent proofs of work, bounded (review N-B) without ever forgetting one that could still be
|
|
1283
|
+
* replayed (review P3): every proof spent within the window a proof is accepted in (±10 min, so 20
|
|
1284
|
+
* minutes back) is kept, and only older ones are dropped beyond MAX_POOL_ENTRIES.
|
|
1285
|
+
*/
|
|
1286
|
+
function keepPows(pows, now) {
|
|
1287
|
+
if (pows.length <= MAX_POOL_ENTRIES)
|
|
1288
|
+
return pows;
|
|
1289
|
+
const live = pows.filter((p) => now - p.at <= 2 * WANT_POW_WINDOW_SEC * 1000);
|
|
1290
|
+
const old = pows.filter((p) => now - p.at > 2 * WANT_POW_WINDOW_SEC * 1000);
|
|
1291
|
+
const room = MAX_POOL_ENTRIES - live.length;
|
|
1292
|
+
return [...(room > 0 ? old.slice(-room) : []), ...live];
|
|
1293
|
+
}
|
|
1294
|
+
/** Askers (or asker|circle pairs) whose answer records are kept, the most recent first (review N-B). */
|
|
1295
|
+
export const MAX_ANSWER_ASKERS = 2048;
|
|
1296
|
+
/** Circles whose member pools are kept. */
|
|
1297
|
+
export const MAX_ANSWER_CIRCLES = 512;
|
|
1298
|
+
/** Entries per pool list before the oldest are folded into one. */
|
|
1299
|
+
export const MAX_POOL_ENTRIES = 4096;
|
|
1300
|
+
const sum = (xs) => (xs ?? []).reduce((a, x) => a + x.bytes, 0);
|
|
1301
|
+
/**
|
|
1302
|
+
* How many bytes this client may still send `asker` this hour: every asker has a count and a
|
|
1303
|
+
* byte budget (review M1); non-members also share a pool, with a separate reserve for those whose
|
|
1304
|
+
* want named a version they were offered, so identities that only know a circle id can't spend
|
|
1305
|
+
* what link-holders need (review M2).
|
|
1306
|
+
*/
|
|
1307
|
+
function allowanceIn(doc, app, asker, pool, cid) {
|
|
1308
|
+
if ((doc.by[asker]?.length ?? 0) >= ANSWERS_PER_ASKER_PER_HOUR)
|
|
1309
|
+
return { ok: false, why: `already answered them ${ANSWERS_PER_ASKER_PER_HOUR} times this hour` };
|
|
1310
|
+
const mine = app.tun.answerBytesPerAskerPerHour - sum(doc.bytes[asker]);
|
|
1311
|
+
if (mine <= 0)
|
|
1312
|
+
return { ok: false, why: `this hour's budget for answering them (${app.tun.answerBytesPerAskerPerHour} bytes) is spent` };
|
|
1313
|
+
if (pool === "member") {
|
|
1314
|
+
// Re-review N2: an open circle admits up to 20 a rolling hour, each with its own per-asker
|
|
1315
|
+
// budget; all of a circle's members together share one pool too.
|
|
1316
|
+
const cap = app.tun.memberAnswerBytesPerCirclePerHour;
|
|
1317
|
+
const left = cap - sum(doc.members?.[cid]);
|
|
1318
|
+
if (left <= 0)
|
|
1319
|
+
return { ok: false, why: `this hour's budget for answering this circle's members (${cap} bytes) is spent` };
|
|
1320
|
+
return { ok: true, bytes: Math.min(mine, left) };
|
|
1321
|
+
}
|
|
1322
|
+
const cap = pool === "reserve" ? app.tun.strangerAnswerBytesPerHour : app.tun.unlinkedAnswerBytesPerHour;
|
|
1323
|
+
const left = cap - sum(doc.sent.filter((x) => (x.pool === "open" ? "open" : "reserve") === pool));
|
|
1324
|
+
if (left <= 0)
|
|
1325
|
+
return { ok: false, why: `this hour's budget for answering non-members${pool === "open" ? " whose want carries no proof of work" : ""} (${cap} bytes) is spent` };
|
|
1326
|
+
return { ok: true, bytes: Math.min(mine, left) };
|
|
1327
|
+
}
|
|
1328
|
+
/** What `asker` may still be sent this hour, checked before anything is built or fetched (review L4). Charges nothing. */
|
|
1329
|
+
export async function answerAllowance(app, asker, pool, cid) {
|
|
1330
|
+
const doc = prunedAnswers(await app.state.get("wantAnswers"), Date.now());
|
|
1331
|
+
return { ...allowanceIn(doc, app, asker, pool, cid), last: doc.last, pows: new Set((doc.pows ?? []).map((x) => x.id)) };
|
|
1332
|
+
}
|
|
1333
|
+
export async function chargeAnswer(app, asker, pool, bytes, mark) {
|
|
1334
|
+
return app.state.update("wantAnswers", (cur) => {
|
|
1335
|
+
const now = Date.now();
|
|
1336
|
+
const doc = prunedAnswers(cur, now);
|
|
1337
|
+
const cid = mark?.cid ?? "";
|
|
1338
|
+
if (pool === "reserve" && mark?.pow !== undefined && (doc.pows ?? []).some((x) => x.id === mark.pow)) {
|
|
1339
|
+
return { next: doc, result: { ok: false, why: "that proof of work was already used" } };
|
|
1340
|
+
}
|
|
1341
|
+
const a = allowanceIn(doc, app, asker, pool, cid);
|
|
1342
|
+
if (!a.ok)
|
|
1343
|
+
return { next: doc, result: a };
|
|
1344
|
+
if (pool === "reserve" && mark?.pow !== undefined)
|
|
1345
|
+
doc.pows = [...(doc.pows ?? []), { id: mark.pow, at: now }];
|
|
1346
|
+
if (bytes > a.bytes)
|
|
1347
|
+
return { next: doc, result: { ok: false, why: `the answer (${bytes} bytes) is over what is left of this hour's budget (${a.bytes})` } };
|
|
1348
|
+
doc.by[asker] = [...(doc.by[asker] ?? []), now];
|
|
1349
|
+
doc.bytes[asker] = [...(doc.bytes[asker] ?? []), { at: now, bytes }];
|
|
1350
|
+
if (pool !== "member")
|
|
1351
|
+
doc.sent.push({ at: now, bytes, pool });
|
|
1352
|
+
else
|
|
1353
|
+
doc.members = { ...doc.members, [cid]: [...(doc.members?.[cid] ?? []), { at: now, bytes }] };
|
|
1354
|
+
let prevLast;
|
|
1355
|
+
if (mark) {
|
|
1356
|
+
const k = `${asker}|${mark.cid}`;
|
|
1357
|
+
const prev = doc.last[k];
|
|
1358
|
+
prevLast = prev;
|
|
1359
|
+
const sameHead = prev !== undefined && mark.ver <= prev.ver;
|
|
1360
|
+
doc.last[k] = { ver: Math.max(mark.ver, prev?.ver ?? 0), at: now, ...(mark.resent || (sameHead && prev?.resent) ? { resent: true } : {}) };
|
|
1361
|
+
}
|
|
1362
|
+
const receipt = { asker, pool, cid, at: now, bytes, ...(pool === "reserve" && mark?.pow ? { pow: mark.pow } : {}), ...(prevLast ? { prevLast } : {}) };
|
|
1363
|
+
// Bounded again with the new entries in (N-B).
|
|
1364
|
+
return { next: prunedAnswers(doc, now), result: { ok: true, bytes: a.bytes - bytes, receipt } };
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* Settles a charge with what actually went out (pre-release review N-A, review P1): the bytes this member
|
|
1369
|
+
* wrote to the wire (each part's sealed size times the relays it was written to, whatever they
|
|
1370
|
+
* replied: a relay can store a part and answer an error), never less than ANSWER_ATTEMPT_MIN_BYTES, stay charged
|
|
1371
|
+
* against the asker and the pools; only the undelivered remainder comes back. `last` goes back to
|
|
1372
|
+
* what it was when the answer didn't fully go out, so the asker may ask for the rest without
|
|
1373
|
+
* being refused as a resend; the proof of work comes back only when nothing went out at all. An
|
|
1374
|
+
* asker steering parts to a relay that drops one of them can't get the rest for free.
|
|
1375
|
+
*/
|
|
1376
|
+
export const ANSWER_ATTEMPT_MIN_BYTES = 4096;
|
|
1377
|
+
export async function settleAnswer(app, r, spent) {
|
|
1378
|
+
const keep = Math.min(r.bytes, Math.max(ANSWER_ATTEMPT_MIN_BYTES, spent));
|
|
1379
|
+
await app.state.update("wantAnswers", (cur) => {
|
|
1380
|
+
const doc = prunedAnswers(cur, Date.now());
|
|
1381
|
+
const adjust = (xs) => xs.map((x) => (x.at === r.at && x.bytes === r.bytes ? { ...x, bytes: keep } : x));
|
|
1382
|
+
if (doc.bytes[r.asker])
|
|
1383
|
+
doc.bytes[r.asker] = adjust(doc.bytes[r.asker]);
|
|
1384
|
+
if (r.pool === "member") {
|
|
1385
|
+
if (doc.members?.[r.cid])
|
|
1386
|
+
doc.members = { ...doc.members, [r.cid]: adjust(doc.members[r.cid]) };
|
|
1387
|
+
}
|
|
1388
|
+
else
|
|
1389
|
+
doc.sent = adjust(doc.sent);
|
|
1390
|
+
if (r.pow && spent === 0)
|
|
1391
|
+
doc.pows = (doc.pows ?? []).filter((x) => x.id !== r.pow);
|
|
1392
|
+
const k = `${r.asker}|${r.cid}`;
|
|
1393
|
+
if (r.prevLast)
|
|
1394
|
+
doc.last[k] = r.prevLast;
|
|
1395
|
+
else
|
|
1396
|
+
delete doc.last[k];
|
|
1397
|
+
return { next: doc, result: undefined };
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
/** Undoes a charge entirely (nothing went out). */
|
|
1401
|
+
export async function refundAnswer(app, r) {
|
|
1402
|
+
await app.state.update("wantAnswers", (cur) => {
|
|
1403
|
+
const doc = prunedAnswers(cur, Date.now());
|
|
1404
|
+
const not = (x) => !(x.at === r.at && x.bytes === r.bytes);
|
|
1405
|
+
if (doc.bytes[r.asker])
|
|
1406
|
+
doc.bytes[r.asker] = doc.bytes[r.asker].filter(not);
|
|
1407
|
+
if (r.pool === "member") {
|
|
1408
|
+
if (doc.members?.[r.cid])
|
|
1409
|
+
doc.members = { ...doc.members, [r.cid]: doc.members[r.cid].filter(not) };
|
|
1410
|
+
}
|
|
1411
|
+
else
|
|
1412
|
+
doc.sent = doc.sent.filter(not);
|
|
1413
|
+
if (r.pow)
|
|
1414
|
+
doc.pows = (doc.pows ?? []).filter((x) => x.id !== r.pow);
|
|
1415
|
+
const k = `${r.asker}|${r.cid}`;
|
|
1416
|
+
if (r.prevLast)
|
|
1417
|
+
doc.last[k] = r.prevLast;
|
|
1418
|
+
else
|
|
1419
|
+
delete doc.last[k];
|
|
1420
|
+
return { next: doc, result: undefined };
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
/**
|
|
1424
|
+
* The parts of an answer from version `fromVer`, cut to `budget` bytes: whole versions in order,
|
|
1425
|
+
* then the statements if everything up to the head fits; a cut answer always stops short of the
|
|
1426
|
+
* head, so the answer that reaches it carries the statements. What doesn't fit is asked for again
|
|
1427
|
+
* later (`fromVer`), so a chain larger than one hour's budget still gets through over hours.
|
|
1428
|
+
*/
|
|
1429
|
+
export function answerParts(versions, statements, budget, cost) {
|
|
1430
|
+
const measure = (vs, js) => {
|
|
1431
|
+
const parts = chunkBody({ circles: [...vs], joins: [...js], ops: [] }).map((p) => ({ circles: p.circles ?? [], joins: p.joins ?? [] }));
|
|
1432
|
+
return { parts, bytes: parts.reduce((a, p) => a + cost(bodyBytes(p)), 0) };
|
|
1433
|
+
};
|
|
1434
|
+
const all = measure(versions, statements);
|
|
1435
|
+
if (all.bytes <= budget)
|
|
1436
|
+
return { ...all, sentVersions: versions.length };
|
|
1437
|
+
// Versions only, the longest prefix that fits (binary search on the count). Re-review N7: never
|
|
1438
|
+
// all of them without the statements: an answer that reaches the head counts as whole, so the
|
|
1439
|
+
// head goes out only with the statements, in a later answer once they fit.
|
|
1440
|
+
let lo = 0;
|
|
1441
|
+
let hi = statements.length > 0 ? versions.length - 1 : versions.length;
|
|
1442
|
+
while (lo < hi) {
|
|
1443
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
1444
|
+
if (measure(versions.slice(0, mid), []).bytes <= budget)
|
|
1445
|
+
lo = mid;
|
|
1446
|
+
else
|
|
1447
|
+
hi = mid - 1;
|
|
1448
|
+
}
|
|
1449
|
+
if (lo === 0)
|
|
1450
|
+
return { parts: [], bytes: 0, sentVersions: 0 };
|
|
1451
|
+
return { ...measure(versions.slice(0, lo), []), sentVersions: lo };
|
|
1452
|
+
}
|
|
1453
|
+
/**
|
|
1454
|
+
* The one device of ours that answers `want`s (review M3), chosen the same way on every device
|
|
1455
|
+
* from our identity document: the lowest-sorting did among the key holders it lists (they hold
|
|
1456
|
+
* every circle we own and sign its versions), else the lowest-sorting listed device.
|
|
1457
|
+
*/
|
|
1458
|
+
export function answeringDevice(view) {
|
|
1459
|
+
const kh = view.keyholders.filter((d) => view.devices.includes(d));
|
|
1460
|
+
const pool = kh.length > 0 ? kh : view.devices;
|
|
1461
|
+
return [...pool].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))[0];
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* This device's place in the answering order (re-review N6): 0 answers at once, rank r answers a
|
|
1465
|
+
* want r fallback delays later if no device of ours has answered it by then (the order is the
|
|
1466
|
+
* election's: key holders first, then the other listed devices, each lowest-sorting first). A
|
|
1467
|
+
* device can't see what the others hold, so one that doesn't hold the circle just can't answer,
|
|
1468
|
+
* and the next in line does. `undefined`: not listed (answer, as before).
|
|
1469
|
+
*/
|
|
1470
|
+
export function answeringRank(view, did) {
|
|
1471
|
+
const sorted = (xs) => [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
1472
|
+
const kh = sorted(view.keyholders.filter((d) => view.devices.includes(d)));
|
|
1473
|
+
const order = [...kh, ...sorted(view.devices.filter((d) => !kh.includes(d)))];
|
|
1474
|
+
const i = order.indexOf(did);
|
|
1475
|
+
return i < 0 ? undefined : i;
|
|
1476
|
+
}
|
|
1477
|
+
async function myAnsweringRank(app) {
|
|
1478
|
+
try {
|
|
1479
|
+
return answeringRank(await app.ownView(), app.did) ?? 0;
|
|
1480
|
+
}
|
|
1481
|
+
catch {
|
|
1482
|
+
return 0;
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
/** At most this many wants wait for a fallback answer on one device (the oldest go first). */
|
|
1486
|
+
export const MAX_DEFERRED_WANTS = 64;
|
|
1487
|
+
/** At most this many from one asker (review F3). */
|
|
1488
|
+
export const MAX_DEFERRED_PER_ASKER = 4;
|
|
1489
|
+
/** A deferred want older than this (by its envelope's `ts`) is dropped unanswered (review F2). */
|
|
1490
|
+
export const DEFERRED_WANT_MAX_AGE_MS = 30 * 60_000;
|
|
1491
|
+
/** Whether a device of ours answered or refused `asker` about `cid` since `at` (minus the fallback slack). */
|
|
1492
|
+
function handledSince(doc, asker, cid, at, slackMs) {
|
|
1493
|
+
const k = `${asker}|${cid}`;
|
|
1494
|
+
const last = doc?.last?.[k];
|
|
1495
|
+
const refused = doc?.refused?.[k];
|
|
1496
|
+
return (last !== undefined && last.at >= at - slackMs) || (refused !== undefined && refused >= at - slackMs);
|
|
1497
|
+
}
|
|
1498
|
+
/**
|
|
1499
|
+
* Answers the deferred wants that are due (re-review N6), unless a device of ours answered or
|
|
1500
|
+
* refused that asker about that circle since (the synced `wantAnswers`), and drops those too old
|
|
1501
|
+
* to answer (review F2). The answer re-checks everything, the proof of work's window included.
|
|
1502
|
+
*/
|
|
1503
|
+
export async function answerDeferredWants(app) {
|
|
1504
|
+
const now = Date.now();
|
|
1505
|
+
const due = await app.state.update("deferredWants", (cur = []) => {
|
|
1506
|
+
const keep = cur.filter((w) => now - w.at <= DEFERRED_WANT_MAX_AGE_MS);
|
|
1507
|
+
const ready = keep.filter((w) => w.due <= now);
|
|
1508
|
+
if (ready.length === 0 && keep.length === cur.length)
|
|
1509
|
+
return { result: [] };
|
|
1510
|
+
return { next: keep.filter((w) => w.due > now), result: ready };
|
|
1511
|
+
});
|
|
1512
|
+
let n = 0;
|
|
1513
|
+
for (const w of due) {
|
|
1514
|
+
if (handledSince(await app.state.get("wantAnswers"), w.from, w.want.cid, w.at, app.tun.wantFallbackSec * 1000))
|
|
1515
|
+
continue;
|
|
1516
|
+
await answerWant(app, w.from, w.fdid, w.want, "fallback", w.relay, w.cap, w.pow, { fallback: true, ts: w.at });
|
|
1517
|
+
n++;
|
|
1518
|
+
}
|
|
1519
|
+
return n;
|
|
1520
|
+
}
|
|
1521
|
+
/** Tells our other devices what this device answered (or refused), so their fallback stays quiet and the pools are shared (review F2). */
|
|
1522
|
+
async function noteHandled(app, rec) {
|
|
1523
|
+
await sendSync(app, { wantAnswered: [rec] }).catch(() => undefined);
|
|
1524
|
+
}
|
|
1525
|
+
/** Merges our other devices' answer and refusal records into this device's (sync.ts): every budget and pool is shared. */
|
|
1526
|
+
export async function importWantAnswered(app, recs) {
|
|
1527
|
+
if (!Array.isArray(recs))
|
|
1528
|
+
return;
|
|
1529
|
+
const int = (x) => Number.isSafeInteger(x);
|
|
1530
|
+
const ok = recs.filter((r) => typeof r === "object" &&
|
|
1531
|
+
r !== null &&
|
|
1532
|
+
typeof r.asker === "string" &&
|
|
1533
|
+
typeof r.cid === "string" &&
|
|
1534
|
+
int(r.at) &&
|
|
1535
|
+
(r.refused === true || (int(r.ver) && int(r.bytes) && (r.pool === undefined || ["member", "reserve", "open"].includes(r.pool)) && (r.pow === undefined || typeof r.pow === "string"))));
|
|
1536
|
+
if (ok.length === 0)
|
|
1537
|
+
return;
|
|
1538
|
+
await app.state.update("wantAnswers", (cur) => {
|
|
1539
|
+
const doc = prunedAnswers(cur, Date.now());
|
|
1540
|
+
for (const r of ok.slice(0, 256)) {
|
|
1541
|
+
const k = `${r.asker}|${r.cid}`;
|
|
1542
|
+
if (r.refused) {
|
|
1543
|
+
doc.refused = { ...doc.refused, [k]: Math.max(r.at, doc.refused?.[k] ?? 0) };
|
|
1544
|
+
continue;
|
|
1545
|
+
}
|
|
1546
|
+
const prev = doc.last[k];
|
|
1547
|
+
doc.last[k] = { ver: Math.max(r.ver, prev?.ver ?? 0), at: Math.max(r.at, prev?.at ?? 0), ...(prev?.resent ? { resent: true } : {}) };
|
|
1548
|
+
doc.by[r.asker] = [...(doc.by[r.asker] ?? []), r.at];
|
|
1549
|
+
doc.bytes[r.asker] = [...(doc.bytes[r.asker] ?? []), { at: r.at, bytes: r.bytes }];
|
|
1550
|
+
if (r.pool === "member")
|
|
1551
|
+
doc.members = { ...doc.members, [r.cid]: [...(doc.members?.[r.cid] ?? []), { at: r.at, bytes: r.bytes }] };
|
|
1552
|
+
else if (r.pool !== undefined)
|
|
1553
|
+
doc.sent.push({ at: r.at, bytes: r.bytes, pool: r.pool });
|
|
1554
|
+
if (r.pow !== undefined)
|
|
1555
|
+
doc.pows = [...(doc.pows ?? []), { id: r.pow, at: r.at }];
|
|
1556
|
+
}
|
|
1557
|
+
return { next: prunedAnswers(doc, Date.now()), result: undefined };
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
/** Records a refusal here and tells our other devices, at most once per asker and circle every 10 minutes. */
|
|
1561
|
+
export async function noteRefused(app, asker, cid) {
|
|
1562
|
+
const k = `${asker}|${cid}`;
|
|
1563
|
+
const now = Date.now();
|
|
1564
|
+
const fresh = await app.state.update("wantAnswers", (cur) => {
|
|
1565
|
+
const doc = prunedAnswers(cur, now);
|
|
1566
|
+
const was = doc.refused?.[k];
|
|
1567
|
+
// review N-B: a refusal recorded in the last 10 minutes changes nothing worth a rewrite.
|
|
1568
|
+
if (was !== undefined && now - was <= 10 * 60_000)
|
|
1569
|
+
return { result: false };
|
|
1570
|
+
doc.refused = { ...doc.refused, [k]: now };
|
|
1571
|
+
return { next: prunedAnswers(doc, now), result: true };
|
|
1572
|
+
});
|
|
1573
|
+
if (fresh)
|
|
1574
|
+
await noteHandled(app, { asker, cid, at: now, refused: true });
|
|
1575
|
+
}
|
|
1576
|
+
/** The asker's answer cap for us, verified (§3.3): issued by the asker, for us, kinds ["*"], at most a day. */
|
|
1577
|
+
async function answerCapOf(app, capJws, asker) {
|
|
1578
|
+
if (capJws === undefined)
|
|
1579
|
+
return undefined;
|
|
1580
|
+
try {
|
|
1581
|
+
const view = await app.view(asker);
|
|
1582
|
+
const cap = verifyCap(capJws, { purpose: "answer", ...(view ? { identityDoc: { iss: view.iss, ik: view.ik, devices: view.devices } } : {}) });
|
|
1583
|
+
return cap.iss === asker && cap.sub === app.userId ? capJws : undefined;
|
|
1584
|
+
}
|
|
1585
|
+
catch {
|
|
1586
|
+
return undefined;
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
const bodyBytes = (v) => Buffer.byteLength(JSON.stringify(v), "utf8");
|
|
1590
|
+
/**
|
|
1591
|
+
* What one answer envelope costs on the wire (review L2): sealing and two layers of base64 make it
|
|
1592
|
+
* about 16/9 of its plaintext, plus ~3 KiB of certificate and fields, sent once to each relay.
|
|
1593
|
+
*/
|
|
1594
|
+
export const sealedCost = (relays) => (plainBytes) => (Math.ceil((plainBytes * 16) / 9) + 3072) * Math.max(1, relays);
|
|
1595
|
+
async function answerWant(app, from, fdid, want, authorizedBy, relay, capJws, pow, opts = {}) {
|
|
1596
|
+
const c = await loadCircle(app.store, want.cid);
|
|
1597
|
+
// A device that doesn't hold the circle can't answer: the next in line will (re-review N6).
|
|
1598
|
+
if (!c)
|
|
1599
|
+
return;
|
|
1600
|
+
const h = c.chain.head;
|
|
1601
|
+
// review L2: the roster only to members of the head, or to anyone for an open circle (friendship alone isn't enough).
|
|
1602
|
+
void authorizedBy;
|
|
1603
|
+
const member = h.members.includes(from);
|
|
1604
|
+
const mayKnow = member || circlePolicy(h) === "open";
|
|
1605
|
+
// review F3: the cheap checks come before a want is queued for a fallback answer.
|
|
1606
|
+
if (!mayKnow || (await app.store.isBlocked(from)))
|
|
1607
|
+
return;
|
|
1608
|
+
// Re-review N3: a non-member draws on the reserve only with a fresh proof of work for this want
|
|
1609
|
+
// (an ancestor hash is public: `prev`, join statements' `at`); without one, on a small pool.
|
|
1610
|
+
const powId = member ? undefined : checkWantPow(pow, from, app.userId, want.cid, want.fromVer, nowSec());
|
|
1611
|
+
// M3: every device of ours gets the want; the first in line answers, the others wait their
|
|
1612
|
+
// turn and answer only if nobody did (re-review N6).
|
|
1613
|
+
if (!opts.fallback) {
|
|
1614
|
+
const rank = await myAnsweringRank(app);
|
|
1615
|
+
if (rank > 0) {
|
|
1616
|
+
// review F2: dated by the want's envelope, not by when it reached this device.
|
|
1617
|
+
const at = opts.ts ?? Date.now();
|
|
1618
|
+
const w = { from, fdid, want, relay, ...(capJws ? { cap: capJws } : {}), ...(pow ? { pow } : {}), at, due: at + rank * app.tun.wantFallbackSec * 1000 };
|
|
1619
|
+
await app.state.update("deferredWants", (cur = []) => {
|
|
1620
|
+
if (cur.filter((x) => x.from === from).length >= MAX_DEFERRED_PER_ASKER)
|
|
1621
|
+
return { result: undefined };
|
|
1622
|
+
return { next: [...cur, w].slice(-MAX_DEFERRED_WANTS), result: undefined };
|
|
1623
|
+
});
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
const who = async () => app.addressOf(from);
|
|
1628
|
+
const refuse = async (why) => {
|
|
1629
|
+
app.io.err(`not answering ${await who()}'s request for circle ${want.cid}: ${why}`);
|
|
1630
|
+
// review F2: our other devices don't answer what this one refused.
|
|
1631
|
+
await noteRefused(app, from, want.cid);
|
|
1632
|
+
};
|
|
1633
|
+
// L4: the limits first, before any bundle is built or identity document fetched.
|
|
1634
|
+
let pool = member ? "member" : powId !== undefined ? "reserve" : "open";
|
|
1635
|
+
let allow = await answerAllowance(app, from, pool, want.cid);
|
|
1636
|
+
if (pool === "reserve" && allow.pows.has(powId)) {
|
|
1637
|
+
pool = "open";
|
|
1638
|
+
allow = await answerAllowance(app, from, pool, want.cid);
|
|
1639
|
+
}
|
|
1640
|
+
if (!allow.ok)
|
|
1641
|
+
return refuse(allow.why);
|
|
1642
|
+
// M1: what was already sent to this asker this hour isn't sent again, except once (a lost part).
|
|
1643
|
+
// Once the circle has moved on (a newer head), what they hold is stale anyway: that is new.
|
|
1644
|
+
const last = allow.last[`${from}|${want.cid}`];
|
|
1645
|
+
const resend = last !== undefined && want.fromVer <= last.ver && h.ver <= last.ver;
|
|
1646
|
+
if (resend && last.resent)
|
|
1647
|
+
return refuse(`already sent them this circle up to version ${last.ver} this hour`);
|
|
1648
|
+
const fromVer = Math.max(1, want.fromVer);
|
|
1649
|
+
// M2: only the device that asked gets the answer, so it is counted (and sent) once.
|
|
1650
|
+
const toAsker = { onlyDevices: [fdid], hint: [relay] };
|
|
1651
|
+
try {
|
|
1652
|
+
const held = (await app.capsFor(from, "circle")).size > 0;
|
|
1653
|
+
const answerCap = held ? undefined : await answerCapOf(app, capJws, from);
|
|
1654
|
+
if (held || answerCap) {
|
|
1655
|
+
const view = held ? await app.view(from) : await app.viewFor(from, { hint: [relay] });
|
|
1656
|
+
if (!view?.devices.includes(fdid))
|
|
1657
|
+
return refuse("the asking device isn't on their identity document");
|
|
1658
|
+
const ob = await outgoingCircleBundle(app.store, want.cid, { fromVer });
|
|
1659
|
+
// A blocked asker was refused above; our own statement is never in an answer to one (R3-L1).
|
|
1660
|
+
const cut = answerParts(ob?.circles ?? [], ob?.joins ?? [], allow.bytes, sealedCost(Math.min(3, view.head.relays.length)));
|
|
1661
|
+
if (cut.parts.length === 0)
|
|
1662
|
+
return refuse("not even one version fits what is left of this hour's budget");
|
|
1663
|
+
const charged = await chargeAnswer(app, from, pool, cut.bytes, { cid: want.cid, ver: fromVer + cut.sentVersions - 1, resent: resend, ...(pool === "reserve" ? { pow: powId } : {}) });
|
|
1664
|
+
if (!charged.ok)
|
|
1665
|
+
return refuse(charged.why);
|
|
1666
|
+
// Ordinary `circle` bundles, chunked under the envelope cap, each saying which part of how
|
|
1667
|
+
// many it is, so the asker knows when the answer is whole (§3.3).
|
|
1668
|
+
const id = b64uEncode(randomBytes(9));
|
|
1669
|
+
let all = true;
|
|
1670
|
+
// What actually went out, at the price the charge used: each part's sealed size, per relay reached.
|
|
1671
|
+
const perRelay = sealedCost(1);
|
|
1672
|
+
let spent = 0;
|
|
1673
|
+
try {
|
|
1674
|
+
for (const [i, part] of cut.parts.entries()) {
|
|
1675
|
+
const d = await app.deliver(from, "circle", { own: app.userId, ...CIRCLE_SID }, { circles: part.circles, joins: part.joins, ops: [], part: { id, i: i + 1, n: cut.parts.length } }, { extraCaps: answerCap ? [answerCap] : [], ...toAsker });
|
|
1676
|
+
// review P1: what this member wrote to the wire, whatever the relays replied: a relay the
|
|
1677
|
+
// asker controls could store each part and answer an error.
|
|
1678
|
+
const wrote = d.relays.length + (d.errors ?? []).filter((e) => e.written).length;
|
|
1679
|
+
spent += perRelay(bodyBytes({ circles: part.circles, joins: part.joins })) * wrote;
|
|
1680
|
+
// The rest still goes: the asker keeps what arrives and asks again for the gap.
|
|
1681
|
+
if (d.relays.length === 0) {
|
|
1682
|
+
if (all)
|
|
1683
|
+
app.io.err(`part ${i + 1} of the answer to ${await who()} about circle ${want.cid} reached no relay (${[...new Set((d.errors ?? []).map((x) => x.code))].join(", ") || "no relay"})`);
|
|
1684
|
+
all = false;
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
catch (e) {
|
|
1689
|
+
all = false;
|
|
1690
|
+
app.io.err(`couldn't finish answering ${await who()} about circle ${want.cid}: ${e.message}`);
|
|
1691
|
+
}
|
|
1692
|
+
// review F2 and the soak: an answer that didn't fully go out isn't one. It is refunded (the
|
|
1693
|
+
// asker's next want is answered, not refused as a resend), and our other devices aren't told.
|
|
1694
|
+
if (!all) {
|
|
1695
|
+
// N-A: charged for what went out, refunded only the rest.
|
|
1696
|
+
if (charged.receipt)
|
|
1697
|
+
await settleAnswer(app, charged.receipt, spent);
|
|
1698
|
+
return;
|
|
1699
|
+
}
|
|
1700
|
+
await noteHandled(app, { asker: from, cid: want.cid, at: Date.now(), ver: fromVer + cut.sentVersions - 1, bytes: cut.bytes, pool, ...(pool === "reserve" && powId ? { pow: powId } : {}) });
|
|
1701
|
+
return;
|
|
1702
|
+
}
|
|
1703
|
+
// An older client's want, with no cap: one cap-less `contact` envelope (§5.4: relay rate limits
|
|
1704
|
+
// and PoW apply), so only a chain that fits one envelope can go this way.
|
|
1705
|
+
const body = { circle: h.jws, chain: c.chain.versionsFrom(1).slice(0, -1) };
|
|
1706
|
+
if (bodyBytes(body) > SYNC_CHUNK_BYTES)
|
|
1707
|
+
return refuse("its history is too long for one first-contact envelope, and their client sent no answer cap (it needs updating)");
|
|
1708
|
+
const view = await app.discover(from, [relay]);
|
|
1709
|
+
if (!view?.devices.includes(fdid))
|
|
1710
|
+
return refuse("the asking device isn't on their identity document");
|
|
1711
|
+
const charged = await chargeAnswer(app, from, pool, sealedCost(Math.min(3, view.head.relays.length))(bodyBytes(body)), { cid: want.cid, ver: h.ver, resent: resend, ...(pool === "reserve" ? { pow: powId } : {}) });
|
|
1712
|
+
if (!charged.ok)
|
|
1713
|
+
return refuse(charged.why);
|
|
1714
|
+
const d = await app.deliver(from, "contact", { own: app.userId, sid: "~contact" }, body, toAsker).catch(() => undefined);
|
|
1715
|
+
if (!d || d.relays.length === 0) {
|
|
1716
|
+
if (charged.receipt)
|
|
1717
|
+
await refundAnswer(app, charged.receipt);
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
await noteHandled(app, { asker: from, cid: want.cid, at: Date.now(), ver: h.ver, bytes: bodyBytes(body), pool, ...(pool === "reserve" && powId ? { pow: powId } : {}) });
|
|
1721
|
+
}
|
|
1722
|
+
catch (e) {
|
|
1723
|
+
app.io.err(`couldn't answer ${await who()}'s request for circle ${want.cid}: ${e.message}`);
|
|
1724
|
+
}
|
|
1725
|
+
}
|