@941design/marmot-engine 0.0.0-stage → 0.2.0-alpha.1
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/CHANGELOG.md +477 -0
- package/LICENSE +53 -0
- package/README.md +33 -2
- package/dist/audit/emitter.d.ts +17 -0
- package/dist/audit/emitter.js +30 -0
- package/dist/audit/helpers.d.ts +16 -0
- package/dist/audit/helpers.js +103 -0
- package/dist/audit/index.d.ts +6 -0
- package/dist/audit/index.js +6 -0
- package/dist/audit/recorder.d.ts +13 -0
- package/dist/audit/recorder.js +24 -0
- package/dist/audit/sink.d.ts +16 -0
- package/dist/audit/sink.js +27 -0
- package/dist/audit/types-internal.d.ts +7 -0
- package/dist/audit/types-internal.js +1 -0
- package/dist/audit/types.d.ts +289 -0
- package/dist/audit/types.js +2 -0
- package/dist/core/account-identity-proof.d.ts +165 -0
- package/dist/core/account-identity-proof.js +277 -0
- package/dist/core/application-rumor.d.ts +45 -0
- package/dist/core/application-rumor.js +120 -0
- package/dist/core/auth-service.d.ts +2 -0
- package/dist/core/auth-service.js +52 -0
- package/dist/core/binary.d.ts +142 -0
- package/dist/core/binary.js +363 -0
- package/dist/core/capabilities.d.ts +51 -0
- package/dist/core/capabilities.js +102 -0
- package/dist/core/client-state.d.ts +119 -0
- package/dist/core/client-state.js +226 -0
- package/dist/core/commit-authorization.d.ts +26 -0
- package/dist/core/commit-authorization.js +26 -0
- package/dist/core/components/admin-policy.d.ts +4 -0
- package/dist/core/components/admin-policy.js +69 -0
- package/dist/core/components/agent-text-stream.d.ts +51 -0
- package/dist/core/components/agent-text-stream.js +112 -0
- package/dist/core/components/app-components-list.d.ts +17 -0
- package/dist/core/components/app-components-list.js +35 -0
- package/dist/core/components/avatar-url.d.ts +12 -0
- package/dist/core/components/avatar-url.js +85 -0
- package/dist/core/components/bytes.d.ts +5 -0
- package/dist/core/components/bytes.js +18 -0
- package/dist/core/components/dictionary.d.ts +80 -0
- package/dist/core/components/dictionary.js +175 -0
- package/dist/core/components/disband-validation.d.ts +21 -0
- package/dist/core/components/disband-validation.js +173 -0
- package/dist/core/components/encrypted-media.d.ts +44 -0
- package/dist/core/components/encrypted-media.js +210 -0
- package/dist/core/components/group-lifecycle.d.ts +10 -0
- package/dist/core/components/group-lifecycle.js +32 -0
- package/dist/core/components/group-profile.d.ts +24 -0
- package/dist/core/components/group-profile.js +35 -0
- package/dist/core/components/host-safety.d.ts +9 -0
- package/dist/core/components/host-safety.js +148 -0
- package/dist/core/components/ids.d.ts +93 -0
- package/dist/core/components/ids.js +92 -0
- package/dist/core/components/index.d.ts +14 -0
- package/dist/core/components/index.js +14 -0
- package/dist/core/components/integrity.d.ts +141 -0
- package/dist/core/components/integrity.js +293 -0
- package/dist/core/components/message-retention.d.ts +17 -0
- package/dist/core/components/message-retention.js +26 -0
- package/dist/core/components/nostr-routing.d.ts +8 -0
- package/dist/core/components/nostr-routing.js +92 -0
- package/dist/core/components/url.d.ts +26 -0
- package/dist/core/components/url.js +44 -0
- package/dist/core/convergence-status.d.ts +84 -0
- package/dist/core/convergence-status.js +82 -0
- package/dist/core/convergence.d.ts +567 -0
- package/dist/core/convergence.js +1150 -0
- package/dist/core/credential.d.ts +16 -0
- package/dist/core/credential.js +64 -0
- package/dist/core/default-capabilities.d.ts +9 -0
- package/dist/core/default-capabilities.js +34 -0
- package/dist/core/extensions.d.ts +9 -0
- package/dist/core/extensions.js +5 -0
- package/dist/core/grease.d.ts +2 -0
- package/dist/core/grease.js +6 -0
- package/dist/core/group-event.d.ts +18 -0
- package/dist/core/group-event.js +30 -0
- package/dist/core/group-lifecycle.d.ts +42 -0
- package/dist/core/group-lifecycle.js +66 -0
- package/dist/core/group-members.d.ts +37 -0
- package/dist/core/group-members.js +99 -0
- package/dist/core/group-message-classify.d.ts +42 -0
- package/dist/core/group-message-classify.js +57 -0
- package/dist/core/group-message-crypto.d.ts +53 -0
- package/dist/core/group-message-crypto.js +140 -0
- package/dist/core/group-message.d.ts +5 -0
- package/dist/core/group-message.js +11 -0
- package/dist/core/group.d.ts +56 -0
- package/dist/core/group.js +95 -0
- package/dist/core/inbound.d.ts +102 -0
- package/dist/core/inbound.js +79 -0
- package/dist/core/index.d.ts +29 -0
- package/dist/core/index.js +27 -0
- package/dist/core/key-package-eligibility.d.ts +31 -0
- package/dist/core/key-package-eligibility.js +116 -0
- package/dist/core/key-package-event-decode.d.ts +43 -0
- package/dist/core/key-package-event-decode.js +118 -0
- package/dist/core/key-package-event-delete.d.ts +16 -0
- package/dist/core/key-package-event-delete.js +46 -0
- package/dist/core/key-package-event-encode.d.ts +28 -0
- package/dist/core/key-package-event-encode.js +117 -0
- package/dist/core/key-package-event.d.ts +4 -0
- package/dist/core/key-package-event.js +8 -0
- package/dist/core/key-package.d.ts +66 -0
- package/dist/core/key-package.js +147 -0
- package/dist/core/leaf-succession.d.ts +83 -0
- package/dist/core/leaf-succession.js +97 -0
- package/dist/core/media/canonical.d.ts +34 -0
- package/dist/core/media/canonical.js +57 -0
- package/dist/core/media/crypto.d.ts +79 -0
- package/dist/core/media/crypto.js +215 -0
- package/dist/core/media/imeta.d.ts +33 -0
- package/dist/core/media/imeta.js +188 -0
- package/dist/core/media/locator.d.ts +44 -0
- package/dist/core/media/locator.js +69 -0
- package/dist/core/media/types.d.ts +83 -0
- package/dist/core/media/types.js +12 -0
- package/dist/core/media.d.ts +6 -0
- package/dist/core/media.js +12 -0
- package/dist/core/protocol-profile.d.ts +262 -0
- package/dist/core/protocol-profile.js +535 -0
- package/dist/core/protocol.d.ts +51 -0
- package/dist/core/protocol.js +41 -0
- package/dist/core/relay-lists.d.ts +52 -0
- package/dist/core/relay-lists.js +86 -0
- package/dist/core/retained-history.d.ts +78 -0
- package/dist/core/retained-history.js +59 -0
- package/dist/core/transport.d.ts +43 -0
- package/dist/core/transport.js +21 -0
- package/dist/core/welcome-event.d.ts +61 -0
- package/dist/core/welcome-event.js +116 -0
- package/dist/core/welcome-join.d.ts +155 -0
- package/dist/core/welcome-join.js +243 -0
- package/dist/core/welcome.d.ts +3 -0
- package/dist/core/welcome.js +6 -0
- package/dist/engine/admin-policy.d.ts +75 -0
- package/dist/engine/admin-policy.js +137 -0
- package/dist/engine/auto-committer.d.ts +39 -0
- package/dist/engine/auto-committer.js +42 -0
- package/dist/engine/delivered-payloads.d.ts +61 -0
- package/dist/engine/delivered-payloads.js +84 -0
- package/dist/engine/disband-request.d.ts +41 -0
- package/dist/engine/disband-request.js +86 -0
- package/dist/engine/disband-tombstone.d.ts +14 -0
- package/dist/engine/disband-tombstone.js +66 -0
- package/dist/engine/fork-recovery.d.ts +672 -0
- package/dist/engine/fork-recovery.js +1615 -0
- package/dist/engine/group-engine.d.ts +571 -0
- package/dist/engine/group-engine.js +5134 -0
- package/dist/engine/history-tree.d.ts +232 -0
- package/dist/engine/history-tree.js +651 -0
- package/dist/engine/index.d.ts +16 -0
- package/dist/engine/index.js +15 -0
- package/dist/engine/ingest-disposition.d.ts +5 -0
- package/dist/engine/ingest-disposition.js +63 -0
- package/dist/engine/ingest.d.ts +390 -0
- package/dist/engine/ingest.js +1258 -0
- package/dist/engine/ingestion-pool.d.ts +74 -0
- package/dist/engine/ingestion-pool.js +95 -0
- package/dist/engine/message-dedup.d.ts +16 -0
- package/dist/engine/message-dedup.js +20 -0
- package/dist/engine/own-commit-stamp.d.ts +30 -0
- package/dist/engine/own-commit-stamp.js +71 -0
- package/dist/engine/retained-store.d.ts +79 -0
- package/dist/engine/retained-store.js +133 -0
- package/dist/engine/sender-ratchet.d.ts +50 -0
- package/dist/engine/sender-ratchet.js +196 -0
- package/dist/engine/state-notifications.d.ts +122 -0
- package/dist/engine/state-notifications.js +173 -0
- package/dist/engine/tree-convergence.d.ts +41 -0
- package/dist/engine/tree-convergence.js +90 -0
- package/dist/engine/types.d.ts +366 -0
- package/dist/engine/types.js +14 -0
- package/dist/engine/wire-format.d.ts +77 -0
- package/dist/engine/wire-format.js +120 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -0
- package/dist/mls.d.ts +11 -0
- package/dist/mls.js +11 -0
- package/dist/utils/debug.d.ts +3 -0
- package/dist/utils/debug.js +3 -0
- package/dist/utils/encoding.d.ts +38 -0
- package/dist/utils/encoding.js +91 -0
- package/dist/utils/key-value.d.ts +18 -0
- package/dist/utils/key-value.js +2 -0
- package/dist/utils/nostr.d.ts +35 -0
- package/dist/utils/nostr.js +26 -0
- package/dist/utils/relay-url.d.ts +10 -0
- package/dist/utils/relay-url.js +23 -0
- package/dist/utils/tag-cardinality.d.ts +50 -0
- package/dist/utils/tag-cardinality.js +91 -0
- package/dist/utils/timestamp.d.ts +50 -0
- package/dist/utils/timestamp.js +95 -0
- package/dist/version.d.ts +112 -0
- package/dist/version.js +112 -0
- package/package.json +68 -3
|
@@ -0,0 +1,1615 @@
|
|
|
1
|
+
/** @module @category Engine */
|
|
2
|
+
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
|
|
3
|
+
import { defaultProposalTypes, encode, getCredentialFromLeafIndex, InternalError, mlsMessageEncoder, nodeTypes, processMessage, selfRemoveProposalType, ValidationError, wireformats, senderTypes, } from "ts-mls";
|
|
4
|
+
import { marmotAuthService } from "../core/auth-service.js";
|
|
5
|
+
import { validateCommitLegality } from "../core/components/integrity.js";
|
|
6
|
+
import { commitDigest, compareBranchScores, DEFAULT_CONVERGENCE_POLICY, isBranchEligible, isWitnessEligible, opaqueBestCase, opaqueCouldWin, phaseOneNodesOf, scoreBranch, selectCanonicalBranch, selectCanonicalBranchCredited, } from "../core/convergence.js";
|
|
7
|
+
import { getCredentialPubkey } from "../core/credential.js";
|
|
8
|
+
import { leafKeySuccessions, } from "../core/leaf-succession.js";
|
|
9
|
+
import { deserializeClientState, serializeClientState, } from "../core/client-state.js";
|
|
10
|
+
import { withCapturedProposals } from "./admin-policy.js";
|
|
11
|
+
import { framedEpoch } from "./wire-format.js";
|
|
12
|
+
/**
|
|
13
|
+
* Seam (convergence rejection reason): the order in which the reasons a commit
|
|
14
|
+
* was rejected for at different nodes are reported (the first listed wins).
|
|
15
|
+
*/
|
|
16
|
+
const REJECTION_ORDER = [
|
|
17
|
+
"admin-policy",
|
|
18
|
+
"component-integrity",
|
|
19
|
+
"admin-leaf-coupling",
|
|
20
|
+
"disband-legality",
|
|
21
|
+
];
|
|
22
|
+
/**
|
|
23
|
+
* Authenticates a Commit against one exact parent, then applies the shared
|
|
24
|
+
* parent-relative authorization/component gate. A stamped own Commit is
|
|
25
|
+
* already authenticated and authorized and therefore uses its recorded child.
|
|
26
|
+
*/
|
|
27
|
+
export async function resolveCandidateParent(params) {
|
|
28
|
+
const { ciphersuite, clientConfig, parent, message, callback, known } = params;
|
|
29
|
+
if (known?.parentTag === bytesToHex(parent.confirmationTag))
|
|
30
|
+
return {
|
|
31
|
+
kind: "resolved",
|
|
32
|
+
result: {
|
|
33
|
+
kind: "newState",
|
|
34
|
+
newState: known.state,
|
|
35
|
+
actionTaken: "accept",
|
|
36
|
+
consumed: [],
|
|
37
|
+
senderLeafIndex: known.senderLeafIndex,
|
|
38
|
+
aad: new Uint8Array(),
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
const capture = withCapturedProposals(callback);
|
|
42
|
+
capture.take();
|
|
43
|
+
let result;
|
|
44
|
+
try {
|
|
45
|
+
result = await processMessage({
|
|
46
|
+
context: {
|
|
47
|
+
cipherSuite: ciphersuite,
|
|
48
|
+
authService: marmotAuthService,
|
|
49
|
+
externalPsks: {},
|
|
50
|
+
clientConfig,
|
|
51
|
+
},
|
|
52
|
+
state: parent,
|
|
53
|
+
message,
|
|
54
|
+
callback: capture.callback,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
const captured = capture.take();
|
|
59
|
+
const committerLeafIndex = captured.committerLeafIndex;
|
|
60
|
+
if (isNoOverlapError(error))
|
|
61
|
+
return {
|
|
62
|
+
kind: "fenced",
|
|
63
|
+
cause: error,
|
|
64
|
+
...(committerLeafIndex === undefined
|
|
65
|
+
? {}
|
|
66
|
+
: {
|
|
67
|
+
senderLeafIndex: committerLeafIndex,
|
|
68
|
+
proposals: captured.proposals,
|
|
69
|
+
}),
|
|
70
|
+
};
|
|
71
|
+
// The sole-member shape of the same own commit: its `UpdatePath` is empty,
|
|
72
|
+
// so ts-mls fails one step earlier ({@link isNoCommonAncestorError}). Only
|
|
73
|
+
// when the authenticated committer (the admin callback ran after the
|
|
74
|
+
// framing was verified and a PrivateMessage's sender data decrypted) is
|
|
75
|
+
// this parent's own leaf.
|
|
76
|
+
if (classifyOwnCommitPathLoss(error, committerLeafIndex, parent.privatePath.leafIndex))
|
|
77
|
+
return {
|
|
78
|
+
kind: "fenced",
|
|
79
|
+
cause: error,
|
|
80
|
+
senderLeafIndex: committerLeafIndex,
|
|
81
|
+
proposals: captured.proposals,
|
|
82
|
+
};
|
|
83
|
+
return isMissingProposalReference(error)
|
|
84
|
+
? { kind: "missing_proposal" }
|
|
85
|
+
: { kind: "authentication_mismatch" };
|
|
86
|
+
}
|
|
87
|
+
const capturedCommit = capture.take();
|
|
88
|
+
if (result.kind !== "newState")
|
|
89
|
+
return { kind: "rejected", reason: "authorization_or_components" };
|
|
90
|
+
if (result.actionTaken === "reject")
|
|
91
|
+
return {
|
|
92
|
+
kind: "rejected",
|
|
93
|
+
reason: "authorization_or_components",
|
|
94
|
+
rejection: { reason: "admin-policy" },
|
|
95
|
+
};
|
|
96
|
+
try {
|
|
97
|
+
const violation = validateCommitLegality({
|
|
98
|
+
parentState: parent,
|
|
99
|
+
resultingState: result.newState,
|
|
100
|
+
proposals: capturedCommit.proposals,
|
|
101
|
+
committerLeafIndex: capturedCommit.committerLeafIndex,
|
|
102
|
+
});
|
|
103
|
+
if (violation)
|
|
104
|
+
return {
|
|
105
|
+
kind: "rejected",
|
|
106
|
+
reason: "authorization_or_components",
|
|
107
|
+
rejection: { reason: violation.reason, detail: violation.detail },
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return { kind: "deferred", reason: "temporary_refusal" };
|
|
112
|
+
}
|
|
113
|
+
return { kind: "resolved", result };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* A commit that references (by `ProposalRef`) a proposal the state it is
|
|
117
|
+
* applied to has not staged. ts-mls signals this with a `ValidationError`
|
|
118
|
+
* "Could not find proposal with supplied reference".
|
|
119
|
+
*/
|
|
120
|
+
export function isMissingProposalReference(error) {
|
|
121
|
+
return (error instanceof ValidationError &&
|
|
122
|
+
error.message.includes("Could not find proposal with supplied reference"));
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* ts-mls's "this device lost its own path secrets" failure: a commit that
|
|
126
|
+
* authenticated against the state it is applied to, but whose `UpdatePath`
|
|
127
|
+
* encrypts no path secret to any private key that state holds. ts-mls throws
|
|
128
|
+
* `InternalError("No overlap between provided private keys and update path")`
|
|
129
|
+
* from `applyUpdatePathSecret` — after the framing (membership tag, signature)
|
|
130
|
+
* was verified, so the commit is genuine at that parent. Replaying a commit of
|
|
131
|
+
* the replaying leaf itself (an `UpdatePath` never encrypts to its committer)
|
|
132
|
+
* or any later commit encrypted to keys such a commit installed raises it.
|
|
133
|
+
*/
|
|
134
|
+
export function isNoOverlapError(error) {
|
|
135
|
+
return (error instanceof InternalError &&
|
|
136
|
+
error.message.includes("No overlap between provided private keys and update path"));
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* ts-mls's `ValidationError("Could not find common ancestor")`, thrown by
|
|
140
|
+
* `applyUpdatePathSecret` (via `firstMatchAncestor`) at the same point as
|
|
141
|
+
* {@link isNoOverlapError} — after the framing was verified — when the
|
|
142
|
+
* committer's filtered direct path holds no ancestor of the applying leaf. For
|
|
143
|
+
* a commit of another leaf their lowest common ancestor is always on it (the
|
|
144
|
+
* applying leaf keeps its copath resolution non-empty; a commit removing it
|
|
145
|
+
* returns before the path is applied), so it arises only for a commit of the
|
|
146
|
+
* applying leaf itself whose filtered direct path is empty: a sole member's own
|
|
147
|
+
* commit. Its own-leaf meaning is the caller's to check.
|
|
148
|
+
*/
|
|
149
|
+
export function isNoCommonAncestorError(error) {
|
|
150
|
+
return (error instanceof ValidationError &&
|
|
151
|
+
error.message.includes("Could not find common ancestor"));
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* The {@link isNoCommonAncestorError} errors {@link classifyOwnCommitPathLoss}
|
|
155
|
+
* attributed to the applying leaf's own commit. The error object itself is
|
|
156
|
+
* what every replay path surfaces (a `fenced` cause, an `unreadable`'s
|
|
157
|
+
* `errors`), and the client sees only that object — never the committer —
|
|
158
|
+
* so the own-leaf verdict travels with its identity.
|
|
159
|
+
*/
|
|
160
|
+
const ownCommitPathLoss = new WeakSet();
|
|
161
|
+
/**
|
|
162
|
+
* Whether `error`, thrown applying a commit whose authenticated committer is
|
|
163
|
+
* `committerLeafIndex` to a state whose own leaf is `ownLeafIndex`, is the
|
|
164
|
+
* sole-member shape of lost own path secrets: an
|
|
165
|
+
* {@link isNoCommonAncestorError} of the applying leaf's own commit. Records
|
|
166
|
+
* the verdict on the error so {@link isLostPathSecretsError} recognises it
|
|
167
|
+
* wherever it is surfaced. The same error from a foreign committer is not
|
|
168
|
+
* (`false`, unrecorded): it carries no evidence of lost path secrets.
|
|
169
|
+
* `committerLeafIndex` is the admin callback's capture, so `undefined` (the
|
|
170
|
+
* callback never ran: the framing did not verify) never matches.
|
|
171
|
+
*/
|
|
172
|
+
export function classifyOwnCommitPathLoss(error, committerLeafIndex, ownLeafIndex) {
|
|
173
|
+
if (!isNoCommonAncestorError(error) || committerLeafIndex !== ownLeafIndex)
|
|
174
|
+
return false;
|
|
175
|
+
ownCommitPathLoss.add(error);
|
|
176
|
+
return true;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* This device lost its own path secrets (AC-HIST-4): {@link isNoOverlapError},
|
|
180
|
+
* or an {@link isNoCommonAncestorError} that {@link classifyOwnCommitPathLoss}
|
|
181
|
+
* attributed to the applying leaf's own commit (a sole member's). The
|
|
182
|
+
* predicate the client fences on.
|
|
183
|
+
*/
|
|
184
|
+
export function isLostPathSecretsError(error) {
|
|
185
|
+
return (isNoOverlapError(error) ||
|
|
186
|
+
(error instanceof ValidationError && ownCommitPathLoss.has(error)));
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Seam (`branchAwareFence`), LD-1: the fence error of a held opaque candidate
|
|
190
|
+
* rebuilt from the message its record kept (a decision taken on a later pass
|
|
191
|
+
* or after a reload no longer has the thrown error object). The result is an
|
|
192
|
+
* error {@link isLostPathSecretsError} accepts: ts-mls's own
|
|
193
|
+
* `InternalError` class for the no-overlap message, and for the sole-member
|
|
194
|
+
* shape (`Could not find common ancestor`) a `ValidationError` registered as
|
|
195
|
+
* an own-commit path loss, the same way {@link classifyOwnCommitPathLoss}
|
|
196
|
+
* registers the thrown one. A plain `Error` with the same message is no
|
|
197
|
+
* lost-path-secrets error (the client's `recordedFencingError` is one), which
|
|
198
|
+
* is why the client predicate stays the engine's.
|
|
199
|
+
*/
|
|
200
|
+
export function reconstructLostPathSecretsError(message) {
|
|
201
|
+
if (message.includes("Could not find common ancestor")) {
|
|
202
|
+
const error = new ValidationError(message);
|
|
203
|
+
ownCommitPathLoss.add(error);
|
|
204
|
+
return error;
|
|
205
|
+
}
|
|
206
|
+
const noOverlap = "No overlap between provided private keys and update path";
|
|
207
|
+
// ts-mls's InternalError prefixes its own text to the message it is given, so
|
|
208
|
+
// the recorded message (which has it) is cut back to the failure's own text.
|
|
209
|
+
const at = message.indexOf(noOverlap);
|
|
210
|
+
return new InternalError(at >= 0 ? message.slice(at) : `${noOverlap}: ${message}`);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* The member sender a framed Commit's PLAINTEXT framing names: the leaf index
|
|
214
|
+
* of a member-sent `PublicMessage`, `undefined` for every other shape — a
|
|
215
|
+
* `PrivateMessage` encrypts its sender, so its framing names none. Framing is
|
|
216
|
+
* attacker-controlled: a member can wire any commit either way. So this is no
|
|
217
|
+
* sender attribution on its own; its only caller is
|
|
218
|
+
* {@link authenticatedSenderOf}, as the fallback for a resolution that never
|
|
219
|
+
* ran `processMessage`.
|
|
220
|
+
*/
|
|
221
|
+
export function senderLeafIndexOf(message) {
|
|
222
|
+
return message.wireformat === wireformats.mls_public_message &&
|
|
223
|
+
message.publicMessage.content.sender.senderType === senderTypes.member
|
|
224
|
+
? message.publicMessage.content.sender.leafIndex
|
|
225
|
+
: undefined;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The authenticated member sender of a Commit resolved against its parent:
|
|
229
|
+
* `processMessage`'s `senderLeafIndex` — read from the verified plaintext
|
|
230
|
+
* framing of a `PublicMessage` and from the decrypted sender data of a
|
|
231
|
+
* `PrivateMessage` alike, so an edge's sender never depends on how its commit
|
|
232
|
+
* was framed on the wire (ADR-016 "Framing independence"). The framing is the
|
|
233
|
+
* fallback only when the resolution produced no sender: the CONV-04
|
|
234
|
+
* short-circuit for our own already-applied commits (a synthesized result
|
|
235
|
+
* that never ran `processMessage`; Marmot frames its own commits as
|
|
236
|
+
* `PublicMessage`), and a record persisted before senders were (`result`
|
|
237
|
+
* absent). `undefined` for a non-member (external) sender — which cannot
|
|
238
|
+
* equivocate, so its edge earns no credit and raises no report.
|
|
239
|
+
*
|
|
240
|
+
* Every site that attributes an edge, a chain link, a recorded history-tree
|
|
241
|
+
* edge or a branch's tip committer derives its sender here (a source scan
|
|
242
|
+
* pins {@link senderLeafIndexOf} to this one call site).
|
|
243
|
+
*/
|
|
244
|
+
export function authenticatedSenderOf(result, message) {
|
|
245
|
+
return result?.senderLeafIndex ?? senderLeafIndexOf(message);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The tip committer of a branch whose tip commit was authored by
|
|
249
|
+
* `senderLeafIndex` (its {@link authenticatedSenderOf}) at `parent`: that
|
|
250
|
+
* leaf's credential pubkey in `parent`, or empty bytes when it cannot be
|
|
251
|
+
* resolved — the derivation every candidate's `tipCommitter` uses, in pool
|
|
252
|
+
* replay and tree-fed re-convergence alike (seam, epic-marmot-client S20:
|
|
253
|
+
* shared with removal candidates, whose tombstone tree no longer holds the
|
|
254
|
+
* sender).
|
|
255
|
+
*/
|
|
256
|
+
export function tipCommitterOf(parent, senderLeafIndex) {
|
|
257
|
+
if (senderLeafIndex === undefined)
|
|
258
|
+
return new Uint8Array();
|
|
259
|
+
try {
|
|
260
|
+
return hexToBytes(getCredentialPubkey(getCredentialFromLeafIndex(parent.ratchetTree, senderLeafIndex)));
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
return new Uint8Array();
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Seam (`equivocationCredit`): the membership facts of one equivocation node —
|
|
268
|
+
* every occupied leaf index of `state`'s ratchet tree with its hex leaf
|
|
269
|
+
* signature key and, when the credential parses, its hex account pubkey. Shared
|
|
270
|
+
* by pool replay and the tree-fed sites so both resolve the same
|
|
271
|
+
* {@link EquivocationCreditInput} for the same node.
|
|
272
|
+
*/
|
|
273
|
+
export function equivocationNodeContextOf(state) {
|
|
274
|
+
const members = new Map();
|
|
275
|
+
const accounts = new Map();
|
|
276
|
+
state.ratchetTree.forEach((node, nodeIndex) => {
|
|
277
|
+
if (node?.nodeType !== nodeTypes.leaf || nodeIndex % 2 !== 0)
|
|
278
|
+
return;
|
|
279
|
+
const leafIndex = nodeIndex / 2;
|
|
280
|
+
members.set(leafIndex, bytesToHex(node.leaf.signaturePublicKey));
|
|
281
|
+
try {
|
|
282
|
+
accounts.set(leafIndex, getCredentialPubkey(node.leaf.credential));
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
/* not a Marmot account identity: no report for this leaf */
|
|
286
|
+
}
|
|
287
|
+
});
|
|
288
|
+
return { members, accounts };
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Seam (`equivocationCredit`): the hex leaf signature key of a commit's member
|
|
292
|
+
* sender in the commit's `parent` state, or `undefined` when the sender is not
|
|
293
|
+
* a member or its leaf is blank there (such an edge earns no credit).
|
|
294
|
+
*/
|
|
295
|
+
export function senderLeafKeyOf(parent, senderLeafIndex) {
|
|
296
|
+
if (senderLeafIndex === undefined)
|
|
297
|
+
return undefined;
|
|
298
|
+
const node = parent.ratchetTree[senderLeafIndex * 2];
|
|
299
|
+
return node?.nodeType === nodeTypes.leaf
|
|
300
|
+
? bytesToHex(node.leaf.signaturePublicKey)
|
|
301
|
+
: undefined;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Seam (key rotation, lineage clause of ADR-016 D2 rule 4): the signature-key
|
|
305
|
+
* successions the commit `parent` → `child` made at its own committer's leaf
|
|
306
|
+
* (`senderLeafIndex`), the only fact the credit lineage reads. Empty when the
|
|
307
|
+
* sender is unknown, nothing rotated, or the key change was made by another
|
|
308
|
+
* leaf (an Update proposal, a Remove plus re-Add): none of those extends the
|
|
309
|
+
* keys a leaf's later edges are credited under.
|
|
310
|
+
*
|
|
311
|
+
* @internal
|
|
312
|
+
*/
|
|
313
|
+
export function committerSuccessionsOf(parent, child, senderLeafIndex) {
|
|
314
|
+
if (senderLeafIndex === undefined)
|
|
315
|
+
return [];
|
|
316
|
+
return leafKeySuccessions(parent, child).filter((succession) => succession.leafIndex === senderLeafIndex && succession.source === "commit");
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Seam (`removalFinality`, ADR-017 R-1, architecture.md SC-R8): the leaves the
|
|
320
|
+
* commit `parent` → `child` removes, each as occupied in `parent` — every index
|
|
321
|
+
* `s` where `parent` holds a leaf with signature key `K` and `child` holds no
|
|
322
|
+
* leaf with key `K` at `s`, except the indices {@link leafKeySuccessions}
|
|
323
|
+
* reports (the same leaf continuing under a new key: a rotation is not a
|
|
324
|
+
* removal). A same-key self-update removes nothing; a Remove plus an Add at one
|
|
325
|
+
* index removes the old occupant. `child` may be the `removedFromGroup`
|
|
326
|
+
* tombstone of a commit that removed the processing device (its ratchet tree
|
|
327
|
+
* is the proposal-applied one). Strictly ascending by `leafIndex`, keys
|
|
328
|
+
* lowercase hex. Total: `undefined` (unknown, never evidence) when either
|
|
329
|
+
* state is unavailable or malformed. With {@link opaqueRemovalFactsOf} the only
|
|
330
|
+
* producer of `CandidatePathEdge.removed`.
|
|
331
|
+
*
|
|
332
|
+
* @internal
|
|
333
|
+
*/
|
|
334
|
+
export function edgeRemovalFactsOf(parent, child) {
|
|
335
|
+
try {
|
|
336
|
+
const parentTree = parent?.ratchetTree;
|
|
337
|
+
const childTree = child?.ratchetTree;
|
|
338
|
+
if (!Array.isArray(parentTree) || !Array.isArray(childTree))
|
|
339
|
+
return undefined;
|
|
340
|
+
const succeeded = new Set(leafKeySuccessions(parent, child).map((succession) => succession.leafIndex));
|
|
341
|
+
const removed = [];
|
|
342
|
+
for (let nodeIndex = 0; nodeIndex < parentTree.length; nodeIndex += 2) {
|
|
343
|
+
const leafKey = leafKeyAt(parentTree, nodeIndex);
|
|
344
|
+
if (leafKey === undefined)
|
|
345
|
+
continue;
|
|
346
|
+
const leafIndex = nodeIndex / 2;
|
|
347
|
+
if (leafKeyAt(childTree, nodeIndex) === leafKey || succeeded.has(leafIndex))
|
|
348
|
+
continue;
|
|
349
|
+
removed.push({ leafIndex, leafKey });
|
|
350
|
+
}
|
|
351
|
+
return removed;
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
return undefined;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Seam (`removalFinality`, ADR-017 R-2, architecture.md SC-R8): the removal
|
|
359
|
+
* facts of an opaque head — a commit this device cannot apply, so it has no
|
|
360
|
+
* child state — read from the resolved `proposals` the admin callback captured
|
|
361
|
+
* at its held `parent`: `(s, K_P[s])` for every Remove of `s` (and every
|
|
362
|
+
* `self_remove`, whose target is its sender: it blanks the sender's leaf as a
|
|
363
|
+
* Remove does, so R-1 on the unseen child would report it too). `undefined`
|
|
364
|
+
* (the fence then fails closed) for (i) no captured proposals, (ii) an Add in
|
|
365
|
+
* the same commit whose key equals `K_P[s]` of one of its targets (the leaf
|
|
366
|
+
* would reappear under the same key at some index), (iii) an unavailable
|
|
367
|
+
* parent, and for a target the parent holds no leaf at. Whenever it yields a
|
|
368
|
+
* set it equals {@link edgeRemovalFactsOf} on the unseen child. Strictly
|
|
369
|
+
* ascending by `leafIndex`. Total.
|
|
370
|
+
*
|
|
371
|
+
* @internal
|
|
372
|
+
*/
|
|
373
|
+
export function opaqueRemovalFactsOf(parent, proposals) {
|
|
374
|
+
try {
|
|
375
|
+
const tree = parent?.ratchetTree;
|
|
376
|
+
if (!Array.isArray(tree) || !Array.isArray(proposals))
|
|
377
|
+
return undefined;
|
|
378
|
+
const targets = new Set();
|
|
379
|
+
const addedKeys = new Set();
|
|
380
|
+
for (const entry of proposals) {
|
|
381
|
+
const proposal = entry.proposal;
|
|
382
|
+
if (proposal.proposalType === defaultProposalTypes.remove) {
|
|
383
|
+
if (!("remove" in proposal))
|
|
384
|
+
return undefined;
|
|
385
|
+
targets.add(Number(proposal.remove.removed));
|
|
386
|
+
}
|
|
387
|
+
else if (proposal.proposalType === selfRemoveProposalType) {
|
|
388
|
+
if (entry.senderLeafIndex === undefined)
|
|
389
|
+
return undefined;
|
|
390
|
+
targets.add(Number(entry.senderLeafIndex));
|
|
391
|
+
}
|
|
392
|
+
else if (proposal.proposalType === defaultProposalTypes.add) {
|
|
393
|
+
if (!("add" in proposal))
|
|
394
|
+
return undefined;
|
|
395
|
+
addedKeys.add(bytesToHex(proposal.add.keyPackage.leafNode.signaturePublicKey));
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const removed = [];
|
|
399
|
+
for (const leafIndex of [...targets].sort((a, b) => a - b)) {
|
|
400
|
+
if (!Number.isSafeInteger(leafIndex) || leafIndex < 0)
|
|
401
|
+
return undefined;
|
|
402
|
+
const leafKey = leafKeyAt(tree, leafIndex * 2);
|
|
403
|
+
if (leafKey === undefined || addedKeys.has(leafKey))
|
|
404
|
+
return undefined;
|
|
405
|
+
removed.push({ leafIndex, leafKey });
|
|
406
|
+
}
|
|
407
|
+
return removed;
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/** The lowercase hex signature key of the leaf node at `nodeIndex`, or `undefined` for a blank or non-leaf node. */
|
|
414
|
+
function leafKeyAt(tree, nodeIndex) {
|
|
415
|
+
const node = tree[nodeIndex];
|
|
416
|
+
if (node?.nodeType !== nodeTypes.leaf)
|
|
417
|
+
return undefined;
|
|
418
|
+
const key = node.leaf.signaturePublicKey;
|
|
419
|
+
if (!(key instanceof Uint8Array))
|
|
420
|
+
throw new TypeError("malformed leaf key");
|
|
421
|
+
return bytesToHex(key);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Seam (`removalFinality`): the {@link EdgeFacts} of the commit `parent` →
|
|
425
|
+
* `child` by `senderLeafIndex`. Total (each part is).
|
|
426
|
+
*
|
|
427
|
+
* @internal
|
|
428
|
+
*/
|
|
429
|
+
export function edgeFactsOf(parent, child, senderLeafIndex) {
|
|
430
|
+
let senderKey;
|
|
431
|
+
let successions = [];
|
|
432
|
+
try {
|
|
433
|
+
senderKey = senderLeafKeyOf(parent, senderLeafIndex);
|
|
434
|
+
successions = committerSuccessionsOf(parent, child, senderLeafIndex);
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
/* malformed state: no key, no succession (fail-closed) */
|
|
438
|
+
}
|
|
439
|
+
return { removed: edgeRemovalFactsOf(parent, child), senderKey, successions };
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* Seam (key rotation): the per-edge succession facts of a credit input at the
|
|
443
|
+
* tree-fed sites, hex commit digest → {@link committerSuccessionsOf}, for every
|
|
444
|
+
* edge of `paths` that a later edge of the same path follows (the credit of an
|
|
445
|
+
* edge depends on the successions of the edges BEFORE it, so the last edge's
|
|
446
|
+
* own is never read). `stateOf` resolves a confirmation tag to the state the
|
|
447
|
+
* site holds for it; an edge whose parent or child state it cannot resolve (or
|
|
448
|
+
* whose child is a virtual `removal:` / `terminal:` / `opaque:` leaf) gets no
|
|
449
|
+
* fact, which fails closed to the pre-key-rotation credit for its successors.
|
|
450
|
+
*
|
|
451
|
+
* @internal
|
|
452
|
+
*/
|
|
453
|
+
export async function successionFactsOf(paths, stateOf) {
|
|
454
|
+
const into = new Map();
|
|
455
|
+
const done = new Set();
|
|
456
|
+
for (const path of paths) {
|
|
457
|
+
for (let i = 0; i + 1 < path.length; i++) {
|
|
458
|
+
const edge = path[i];
|
|
459
|
+
const digest = bytesToHex(edge.commitDigest);
|
|
460
|
+
if (edge.senderLeafIndex === undefined ||
|
|
461
|
+
edge.childId.includes(":") ||
|
|
462
|
+
done.has(digest))
|
|
463
|
+
continue;
|
|
464
|
+
done.add(digest);
|
|
465
|
+
const parent = await stateOf(edge.parentId);
|
|
466
|
+
const child = await stateOf(edge.childId);
|
|
467
|
+
if (parent === undefined || child === undefined)
|
|
468
|
+
continue;
|
|
469
|
+
const facts = committerSuccessionsOf(parent, child, edge.senderLeafIndex);
|
|
470
|
+
if (facts.length > 0)
|
|
471
|
+
into.set(digest, facts);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return into;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Convergence fork recovery (Marmot v2 `protocol-core/convergence.md`):
|
|
478
|
+
* rebuilds candidate branches by replaying retained applied commits plus
|
|
479
|
+
* competing commits, scores them with the pure {@link selectCanonicalBranch}
|
|
480
|
+
* core, and reports the canonical branch so the caller can rewind.
|
|
481
|
+
*
|
|
482
|
+
* This is the stateful "candidate branch construction" layer that
|
|
483
|
+
* `convergence.ts` deliberately leaves out. It holds no engine state of its own;
|
|
484
|
+
* branch tip/chain bookkeeping is per-call. Mirrors darkmatter
|
|
485
|
+
* `cgka-engine/src/fork_recovery.rs`.
|
|
486
|
+
*/
|
|
487
|
+
export class ForkRecovery {
|
|
488
|
+
#ciphersuite;
|
|
489
|
+
#peeler;
|
|
490
|
+
#policy;
|
|
491
|
+
/**
|
|
492
|
+
* The engine's ts-mls `ClientConfig`, threaded into every candidate replay
|
|
493
|
+
* and witness decrypt below — the same config ingest applies the commits
|
|
494
|
+
* with (AC-VENDOR-6). Without it a candidate is replayed under ts-mls's
|
|
495
|
+
* default `compareKeyPackageToLeafNode`, which can refuse a commit the
|
|
496
|
+
* live path accepted (a same-account Add under a signature-key-only
|
|
497
|
+
* comparator) and silently drop it as a candidate: the competing branch is
|
|
498
|
+
* then never built, and a same-epoch fork never converges.
|
|
499
|
+
*/
|
|
500
|
+
#clientConfig;
|
|
501
|
+
/**
|
|
502
|
+
* Seam (epic-marmot-client S20): a commit that removes the local leaf is a
|
|
503
|
+
* branch candidate (its own tip: tip epoch one past its parent, its digest,
|
|
504
|
+
* its committer) instead of being dropped because its `removedFromGroup`
|
|
505
|
+
* tombstone repeats the parent's confirmation tag. Off by default: upstream
|
|
506
|
+
* behaviour.
|
|
507
|
+
*/
|
|
508
|
+
#removalCandidates;
|
|
509
|
+
/**
|
|
510
|
+
* Seam (epic-marmot-rewind-takeover-stale-leaf-snapshot, ADR-016): every
|
|
511
|
+
* candidate carries its `path` from the fork root, and selection credits
|
|
512
|
+
* depth by other fork-member leaves at equivocation nodes — a node where one
|
|
513
|
+
* leaf authored two or more child commits — reporting each equivocation.
|
|
514
|
+
* Off by default: no path, the 3-argument selection, no report (upstream
|
|
515
|
+
* behaviour).
|
|
516
|
+
*/
|
|
517
|
+
#equivocationCredit;
|
|
518
|
+
/**
|
|
519
|
+
* Seam (`branchAwareFence`, spec epic-marmot-branch-aware-own-leaf-fence,
|
|
520
|
+
* ADR-016 D6): a fenced pool-replay commit is an opaque candidate, decided
|
|
521
|
+
* against the processable branches (`opaqueCouldWin`) instead of fencing
|
|
522
|
+
* before any selection. Takes effect only together with `equivocationCredit`
|
|
523
|
+
* (the candidate paths and node contexts it scores over exist only then).
|
|
524
|
+
* Off by default: the fence-before-selection of today, byte for byte.
|
|
525
|
+
*/
|
|
526
|
+
#branchAwareFence;
|
|
527
|
+
/**
|
|
528
|
+
* Seam (`branchAwareFence`), OQ-1: the hidden-credit policy every
|
|
529
|
+
* `opaqueCouldWin` call of this instance scores with. `conservative` unless
|
|
530
|
+
* the owner chose `anchored-zero`; read only while the seam is on, so an
|
|
531
|
+
* unknown value is ignored seam-off and rejected seam-on (construction).
|
|
532
|
+
*/
|
|
533
|
+
#hiddenCreditPolicy;
|
|
534
|
+
/**
|
|
535
|
+
* Seam (`removalFinality`, ADR-017, architecture.md SC-R2 / SC-R6): the
|
|
536
|
+
* effective value `removalFinality === true && equivocationCredit`, computed
|
|
537
|
+
* once. While it holds, every candidate-path edge carries its removal facts
|
|
538
|
+
* from edge creation (R-1; the removal leaf on its tombstone), phase 1 is
|
|
539
|
+
* structural ({@link phaseOneNodesOf}), every credit input carries the flag,
|
|
540
|
+
* and a removal decision reports `decisiveRule: "removal_finality"`. Off by
|
|
541
|
+
* default: ADR-016 byte for byte.
|
|
542
|
+
*/
|
|
543
|
+
#removalFinality;
|
|
544
|
+
/**
|
|
545
|
+
* Seam (`removalFinality`) at the fourth selection site (the opaque fence):
|
|
546
|
+
* additionally requires `branchAwareFence` effective. Opaque heads then carry
|
|
547
|
+
* their R-2 facts ({@link opaqueRemovalFactsOf}).
|
|
548
|
+
*/
|
|
549
|
+
#removalFinalityFence;
|
|
550
|
+
constructor(ciphersuite, peeler, policy = DEFAULT_CONVERGENCE_POLICY, clientConfig, options) {
|
|
551
|
+
this.#removalCandidates = options?.removalCandidates === true;
|
|
552
|
+
this.#equivocationCredit = options?.equivocationCredit === true;
|
|
553
|
+
this.#branchAwareFence =
|
|
554
|
+
options?.branchAwareFence === true && this.#equivocationCredit;
|
|
555
|
+
this.#removalFinality =
|
|
556
|
+
options?.removalFinality === true && this.#equivocationCredit;
|
|
557
|
+
this.#removalFinalityFence = this.#removalFinality && this.#branchAwareFence;
|
|
558
|
+
this.#hiddenCreditPolicy = this.#branchAwareFence
|
|
559
|
+
? normalizeHiddenCreditPolicy(options?.hiddenCreditPolicy)
|
|
560
|
+
: DEFAULT_HIDDEN_CREDIT_POLICY;
|
|
561
|
+
this.#ciphersuite = ciphersuite;
|
|
562
|
+
this.#peeler = peeler;
|
|
563
|
+
this.#policy = policy;
|
|
564
|
+
this.#clientConfig = clientConfig;
|
|
565
|
+
}
|
|
566
|
+
/** The `commit_digest` (SHA-256 of the MLS message bytes) for a commit. */
|
|
567
|
+
#commitDigestOf(message) {
|
|
568
|
+
return commitDigest(encode(mlsMessageEncoder, message));
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Builds every candidate branch reachable by replaying the commit `pool` from
|
|
572
|
+
* the retained `root` state (`convergence.md` "Candidate branches").
|
|
573
|
+
*
|
|
574
|
+
* `knownNextStates` (CONV-04) maps a candidate commit's hex `commitDigest` to
|
|
575
|
+
* a {@link KnownNextState} — the state already known to result from applying
|
|
576
|
+
* it, plus the confirmation tag of the parent it was applied to — supplied by
|
|
577
|
+
* {@link resolveFork} for commits on our own already-applied canonical path
|
|
578
|
+
* (`RetainedHistoryStore` already holds their resulting state; see
|
|
579
|
+
* `resolveFork`'s doc comment for why replaying them via `processMessage`
|
|
580
|
+
* cannot work). The short-circuit is taken only at the DFS node that IS that
|
|
581
|
+
* recorded parent, so an own commit's branch is buildable exactly like any
|
|
582
|
+
* other candidate's without reprocessing it, while a same-epoch node on a
|
|
583
|
+
* competing fork can never adopt it.
|
|
584
|
+
*/
|
|
585
|
+
async #buildBranches(root, pool, encrypted, witnessEnvelopes, callback, knownNextStates = new Map(), terminalCandidates = new Map(), callbackFor, undecryptable = new Set(), undecryptableSaturated = false, witnessMessages = []) {
|
|
586
|
+
const forkEpoch = Number(root.groupContext.epoch);
|
|
587
|
+
const branches = [];
|
|
588
|
+
const tips = new Map();
|
|
589
|
+
const chains = new Map();
|
|
590
|
+
const edges = [];
|
|
591
|
+
const edgeFacts = new Map();
|
|
592
|
+
const resolved = new Set();
|
|
593
|
+
const missing = new Set();
|
|
594
|
+
const removals = [];
|
|
595
|
+
const fenced = new Map();
|
|
596
|
+
const rejected = new Map();
|
|
597
|
+
// Seam (`branchAwareFence`): the fenced candidates' scoring input, and the
|
|
598
|
+
// ids of `encrypted` envelopes some explored state decrypted (those are
|
|
599
|
+
// not hidden edges).
|
|
600
|
+
const opaque = {
|
|
601
|
+
drafts: new Map(),
|
|
602
|
+
contexts: new Map(),
|
|
603
|
+
senderKeys: new Map(),
|
|
604
|
+
successions: new Map(),
|
|
605
|
+
fromEncrypted: new Map(),
|
|
606
|
+
undecryptable: 0,
|
|
607
|
+
saturated: undecryptableSaturated,
|
|
608
|
+
};
|
|
609
|
+
const peeledIds = new Set();
|
|
610
|
+
// Seam (S20): pristine snapshots of every node a removal can hang off —
|
|
611
|
+
// the root now, each child as its edge is captured — so a removal's
|
|
612
|
+
// parent is never read back after siblings were explored from it.
|
|
613
|
+
const snapshots = new Map();
|
|
614
|
+
if (this.#removalCandidates)
|
|
615
|
+
snapshots.set(bytesToHex(root.confirmationTag), serializeClientState(root));
|
|
616
|
+
let counter = 0;
|
|
617
|
+
// Seam (`equivocationCredit`): the candidate-path edge of `message` applied
|
|
618
|
+
// to `parent` by `senderLeafIndex` (its authenticated sender). Built only
|
|
619
|
+
// with the seam on, so the default path is upstream's.
|
|
620
|
+
// Seam (`removalFinality`): `removed` is the edge's fact, set at creation
|
|
621
|
+
// (before the recursion explores the child) only while the seam is
|
|
622
|
+
// effective and only when resolvable: `edgeRemovalFactsOf(parent, child)`
|
|
623
|
+
// for an edge with a child state (a removal leaf's is its tombstone), the
|
|
624
|
+
// caller's R-2 facts for an opaque head; absent for a disband terminal.
|
|
625
|
+
const withPath = this.#equivocationCredit;
|
|
626
|
+
const edgeOf = (parent, message, senderLeafIndex, childId, removed) => ({
|
|
627
|
+
parentId: bytesToHex(parent.confirmationTag),
|
|
628
|
+
childId,
|
|
629
|
+
commitDigest: this.#commitDigestOf(message),
|
|
630
|
+
senderLeafIndex,
|
|
631
|
+
...(this.#removalFinality && removed !== undefined ? { removed } : {}),
|
|
632
|
+
});
|
|
633
|
+
// WIRE-03/CONV-01 (D-04/D-09): wrap the callback once so the commit's own
|
|
634
|
+
// proposals are captured for validateCommitLegality at the point a
|
|
635
|
+
// candidate edge would be created — the same shared adapter the inbound
|
|
636
|
+
// seam (ingest.ts) uses, so neither seam can drift from the other.
|
|
637
|
+
const witnessesAt = async (state) => [
|
|
638
|
+
...(await collectWitnessesAt({
|
|
639
|
+
peeler: this.#peeler,
|
|
640
|
+
ciphersuite: this.#ciphersuite,
|
|
641
|
+
clientConfig: this.#clientConfig,
|
|
642
|
+
state,
|
|
643
|
+
witnessEnvelopes,
|
|
644
|
+
callback,
|
|
645
|
+
})),
|
|
646
|
+
...(witnessMessages.length === 0
|
|
647
|
+
? []
|
|
648
|
+
: await collectMessageWitnessesAt({
|
|
649
|
+
ciphersuite: this.#ciphersuite,
|
|
650
|
+
clientConfig: this.#clientConfig,
|
|
651
|
+
state,
|
|
652
|
+
witnessMessages,
|
|
653
|
+
callback,
|
|
654
|
+
})),
|
|
655
|
+
];
|
|
656
|
+
const candidatesAt = async (state, logicalEpoch) => {
|
|
657
|
+
const epoch = Math.max(Number(state.groupContext.epoch), logicalEpoch);
|
|
658
|
+
const out = [];
|
|
659
|
+
const seenDigests = new Set();
|
|
660
|
+
const add = (m) => {
|
|
661
|
+
// Marmot v2 frames its commits as MLS PublicMessage (wire-format.ts),
|
|
662
|
+
// but a candidate is whatever framed message sits at this fork epoch —
|
|
663
|
+
// a PrivateMessage commit included (peeled from `encrypted`).
|
|
664
|
+
const e = framedEpoch(m);
|
|
665
|
+
if (e === undefined || Number(e) !== epoch)
|
|
666
|
+
return;
|
|
667
|
+
const d = bytesToHex(this.#commitDigestOf(m));
|
|
668
|
+
if (!seenDigests.has(d)) {
|
|
669
|
+
seenDigests.add(d);
|
|
670
|
+
out.push(m);
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
for (const m of pool)
|
|
674
|
+
add(m);
|
|
675
|
+
for (const [index, envelope] of encrypted.entries()) {
|
|
676
|
+
try {
|
|
677
|
+
const r = await this.#peeler.peelGroupMessages([envelope], state);
|
|
678
|
+
if (this.#branchAwareFence && r.read.length > 0)
|
|
679
|
+
peeledIds.add(this.#peeler.idOf(envelope));
|
|
680
|
+
for (const pair of r.read) {
|
|
681
|
+
add(pair.message);
|
|
682
|
+
if (this.#branchAwareFence) {
|
|
683
|
+
const d = bytesToHex(this.#commitDigestOf(pair.message));
|
|
684
|
+
const known = opaque.fromEncrypted.get(d);
|
|
685
|
+
if (known === undefined)
|
|
686
|
+
opaque.fromEncrypted.set(d, {
|
|
687
|
+
indices: [index],
|
|
688
|
+
message: pair.message,
|
|
689
|
+
});
|
|
690
|
+
else if (!known.indices.includes(index))
|
|
691
|
+
known.indices.push(index);
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
catch {
|
|
696
|
+
/* not decryptable under this state */
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return out;
|
|
700
|
+
};
|
|
701
|
+
// Seam (`branchAwareFence`), LD-3: records the fenced commit `message`
|
|
702
|
+
// found at `state` (the node `N`) as an opaque candidate. `N`'s node
|
|
703
|
+
// context is retained here, with the parent states of `chain` (the path to
|
|
704
|
+
// `N`): the replay holds them now, and the selection chains need not
|
|
705
|
+
// (`N` is no chain link's parent when it has no processable child).
|
|
706
|
+
const collectOpaque = (digest, state, message, senderLeafIndex, chain, path, proposals) => {
|
|
707
|
+
for (const held of [state, ...chain.map((link) => link.parent)]) {
|
|
708
|
+
const tag = bytesToHex(held.confirmationTag);
|
|
709
|
+
if (!opaque.contexts.has(tag))
|
|
710
|
+
opaque.contexts.set(tag, equivocationNodeContextOf(held));
|
|
711
|
+
}
|
|
712
|
+
for (const link of chain) {
|
|
713
|
+
const key = senderLeafKeyOf(link.parent, link.senderLeafIndex);
|
|
714
|
+
const linkDigest = bytesToHex(this.#commitDigestOf(link.message));
|
|
715
|
+
if (key !== undefined)
|
|
716
|
+
opaque.senderKeys.set(linkDigest, key);
|
|
717
|
+
// Equivalent to the facts `chainStatesAndKeys` reads from the same links (a fenced
|
|
718
|
+
// node is a candidate tip, so its path is a processable chain); kept so the opaque
|
|
719
|
+
// input is self-contained, like its `senderKeys`.
|
|
720
|
+
const facts = committerSuccessionsOf(link.parent, link.child, link.senderLeafIndex);
|
|
721
|
+
if (facts.length > 0)
|
|
722
|
+
opaque.successions.set(linkDigest, facts);
|
|
723
|
+
}
|
|
724
|
+
const headKey = senderLeafKeyOf(state, senderLeafIndex);
|
|
725
|
+
if (headKey !== undefined)
|
|
726
|
+
opaque.senderKeys.set(digest, headKey);
|
|
727
|
+
opaque.drafts.set(digest, {
|
|
728
|
+
headEdge: edgeOf(state, message, senderLeafIndex, `opaque:${digest}`, this.#removalFinalityFence && proposals !== undefined
|
|
729
|
+
? opaqueRemovalFactsOf(state, proposals)
|
|
730
|
+
: undefined),
|
|
731
|
+
pathToParent: path,
|
|
732
|
+
parentEpoch: forkEpoch + chain.length,
|
|
733
|
+
headCommitter: tipCommitterOf(state, senderLeafIndex),
|
|
734
|
+
});
|
|
735
|
+
};
|
|
736
|
+
const explore = async (state, tipMessage, seen, chain, witnesses, path) => {
|
|
737
|
+
const accumulated = [...witnesses, ...(await witnessesAt(state))];
|
|
738
|
+
let extended = false;
|
|
739
|
+
let branchDeferred = false;
|
|
740
|
+
for (const message of await candidatesAt(state, forkEpoch + chain.length)) {
|
|
741
|
+
// Candidate commits are framed (private or public); skip anything else.
|
|
742
|
+
if (message.wireformat !== wireformats.mls_private_message &&
|
|
743
|
+
message.wireformat !== wireformats.mls_public_message)
|
|
744
|
+
continue;
|
|
745
|
+
const known = knownNextStates.get(bytesToHex(this.#commitDigestOf(message)));
|
|
746
|
+
// The short-circuit is valid ONLY at the exact parent this commit was
|
|
747
|
+
// recorded against. `candidatesAt` matches purely on framed epoch, so
|
|
748
|
+
// an unqualified digest hit would also fire at a same-epoch node on a
|
|
749
|
+
// COMPETING branch and graft our canonical chain onto it (CR-01). When
|
|
750
|
+
// the parent does not match we fall through to the normal replay path,
|
|
751
|
+
// where our own commit fails to process against a foreign parent and is
|
|
752
|
+
// dropped as a candidate — which is the correct outcome.
|
|
753
|
+
//
|
|
754
|
+
// CR-04: reusing a recorded state must NOT also skip the legality gate.
|
|
755
|
+
// `ours` comes from `RetainedHistoryStore`, which `GroupRegistry`
|
|
756
|
+
// rebuilds on load straight from the persisted history tree — the exact
|
|
757
|
+
// pre-upgrade edge class `#treeResolution` explicitly refuses to
|
|
758
|
+
// grandfather. This commit cannot be replayed (see below), so its
|
|
759
|
+
// proposals are read off the wire instead: inline entries plus the
|
|
760
|
+
// parent's staged proposal for each `ProposalRef`. When that
|
|
761
|
+
// reconstruction is not possible (a `PrivateMessage` commit, whose
|
|
762
|
+
// content is encrypted) we deliberately fall through to the ordinary
|
|
763
|
+
// replay path rather than dropping the candidate — replay yields both
|
|
764
|
+
// the proposals and the same legality gate, and only fails for a commit
|
|
765
|
+
// this leaf authored, which Marmot never wires as a `PrivateMessage`.
|
|
766
|
+
const knownAtThisParent = known !== undefined &&
|
|
767
|
+
known.parentTag === bytesToHex(state.confirmationTag);
|
|
768
|
+
const resolution = await resolveCandidateParent({
|
|
769
|
+
ciphersuite: this.#ciphersuite,
|
|
770
|
+
clientConfig: this.#clientConfig,
|
|
771
|
+
parent: state,
|
|
772
|
+
message,
|
|
773
|
+
// A candidate is judged against the state it is replayed on, never
|
|
774
|
+
// the caller's current tip: the admin/authorization rules read the
|
|
775
|
+
// tree and admin set they are built over, and the tip may already
|
|
776
|
+
// have applied a competing commit (a removal, an admin change) that
|
|
777
|
+
// makes the same proposal illegal there.
|
|
778
|
+
callback: callbackFor ? callbackFor(state) : callback,
|
|
779
|
+
known: knownAtThisParent ? known : undefined,
|
|
780
|
+
});
|
|
781
|
+
switch (resolution.kind) {
|
|
782
|
+
case "deferred":
|
|
783
|
+
branchDeferred = true;
|
|
784
|
+
continue;
|
|
785
|
+
case "missing_proposal":
|
|
786
|
+
missing.add(bytesToHex(this.#commitDigestOf(message)));
|
|
787
|
+
continue;
|
|
788
|
+
case "fenced": {
|
|
789
|
+
// Not a dropped candidate: this device lost its own path secrets.
|
|
790
|
+
const digest = bytesToHex(this.#commitDigestOf(message));
|
|
791
|
+
if (!fenced.has(digest)) {
|
|
792
|
+
fenced.set(digest, resolution.cause);
|
|
793
|
+
if (this.#branchAwareFence)
|
|
794
|
+
collectOpaque(digest, state, message, resolution.senderLeafIndex, chain, path, resolution.proposals);
|
|
795
|
+
}
|
|
796
|
+
continue;
|
|
797
|
+
}
|
|
798
|
+
case "rejected": {
|
|
799
|
+
const digest = bytesToHex(this.#commitDigestOf(message));
|
|
800
|
+
// Fixed reason order, so the reason does not depend on traversal order.
|
|
801
|
+
const rank = (r) => REJECTION_ORDER.indexOf(r.reason);
|
|
802
|
+
const known = rejected.get(digest);
|
|
803
|
+
if (resolution.rejection !== undefined &&
|
|
804
|
+
(known === undefined || rank(resolution.rejection) < rank(known)))
|
|
805
|
+
rejected.set(digest, resolution.rejection);
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
case "authentication_mismatch":
|
|
809
|
+
continue;
|
|
810
|
+
case "resolved":
|
|
811
|
+
break;
|
|
812
|
+
}
|
|
813
|
+
resolved.add(bytesToHex(this.#commitDigestOf(message)));
|
|
814
|
+
const next = resolution.result;
|
|
815
|
+
const sender = authenticatedSenderOf(next, message);
|
|
816
|
+
const tag = bytesToHex(next.newState.confirmationTag);
|
|
817
|
+
if (this.#removalCandidates &&
|
|
818
|
+
next.newState.groupActiveState.kind === "removedFromGroup") {
|
|
819
|
+
// Seam (S20): the commit removes the local leaf. Its tombstone keeps
|
|
820
|
+
// this node's epoch and tag, so it is never explored further and
|
|
821
|
+
// never a tree edge — but it IS a branch, scored exactly as a member
|
|
822
|
+
// scores the same commit: one epoch past this node, its digest, its
|
|
823
|
+
// committer.
|
|
824
|
+
const parentTag = bytesToHex(state.confirmationTag);
|
|
825
|
+
const tipEpoch = forkEpoch + chain.length + 1;
|
|
826
|
+
// Seam (`removalFinality`): R-1 on the tombstone (ADR-017 I4).
|
|
827
|
+
const removalFacts = this.#removalFinality
|
|
828
|
+
? edgeFactsOf(state, next.newState, sender)
|
|
829
|
+
: undefined;
|
|
830
|
+
const branch = {
|
|
831
|
+
id: `branch-${counter++}`,
|
|
832
|
+
forkEpoch,
|
|
833
|
+
tipEpoch,
|
|
834
|
+
tipDigest: this.#commitDigestOf(message),
|
|
835
|
+
tipCommitter: tipCommitterOf(state, sender),
|
|
836
|
+
appWitnesses: accumulated.filter((w) => isWitnessEligible(w, forkEpoch, tipEpoch, this.#policy)),
|
|
837
|
+
...(withPath
|
|
838
|
+
? {
|
|
839
|
+
path: [
|
|
840
|
+
...path,
|
|
841
|
+
edgeOf(state, message, sender, `removal:${bytesToHex(this.#commitDigestOf(message))}`, removalFacts?.removed),
|
|
842
|
+
],
|
|
843
|
+
}
|
|
844
|
+
: {}),
|
|
845
|
+
};
|
|
846
|
+
tips.set(branch, next.newState);
|
|
847
|
+
chains.set(branch, [
|
|
848
|
+
...chain,
|
|
849
|
+
{
|
|
850
|
+
parent: state,
|
|
851
|
+
message,
|
|
852
|
+
child: next.newState,
|
|
853
|
+
senderLeafIndex: sender,
|
|
854
|
+
},
|
|
855
|
+
]);
|
|
856
|
+
branches.push(branch);
|
|
857
|
+
const parentSnapshot = snapshots.get(parentTag);
|
|
858
|
+
if (parentSnapshot !== undefined)
|
|
859
|
+
removals.push({
|
|
860
|
+
parentTag,
|
|
861
|
+
parentSnapshot,
|
|
862
|
+
message,
|
|
863
|
+
senderLeafIndex: sender,
|
|
864
|
+
...(removalFacts === undefined ? {} : { facts: removalFacts }),
|
|
865
|
+
});
|
|
866
|
+
extended = true;
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
if (seen.has(tag)) {
|
|
870
|
+
const digest = this.#commitDigestOf(message);
|
|
871
|
+
const terminal = terminalCandidates.get(bytesToHex(digest));
|
|
872
|
+
if (terminal) {
|
|
873
|
+
const branch = {
|
|
874
|
+
id: `branch-${counter++}`,
|
|
875
|
+
forkEpoch,
|
|
876
|
+
tipEpoch: forkEpoch + chain.length + 1,
|
|
877
|
+
tipDigest: digest,
|
|
878
|
+
tipCommitter: hexToBytes(terminal.actorPubkey),
|
|
879
|
+
appWitnesses: accumulated,
|
|
880
|
+
...(withPath
|
|
881
|
+
? {
|
|
882
|
+
path: [
|
|
883
|
+
...path,
|
|
884
|
+
edgeOf(state, message, sender, `terminal:${bytesToHex(digest)}`),
|
|
885
|
+
],
|
|
886
|
+
}
|
|
887
|
+
: {}),
|
|
888
|
+
};
|
|
889
|
+
tips.set(branch, next.newState);
|
|
890
|
+
chains.set(branch, [
|
|
891
|
+
...chain,
|
|
892
|
+
{
|
|
893
|
+
parent: state,
|
|
894
|
+
message,
|
|
895
|
+
child: next.newState,
|
|
896
|
+
senderLeafIndex: sender,
|
|
897
|
+
},
|
|
898
|
+
]);
|
|
899
|
+
branches.push(branch);
|
|
900
|
+
}
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
extended = true;
|
|
904
|
+
// Snapshot the child now, before recursing — exploring its children
|
|
905
|
+
// would zero this state's consumed secrets in place (ts-mls), corrupting
|
|
906
|
+
// a snapshot taken afterward.
|
|
907
|
+
const commitBytes = encode(mlsMessageEncoder, message);
|
|
908
|
+
edges.push({
|
|
909
|
+
parentTag: bytesToHex(state.confirmationTag),
|
|
910
|
+
childTag: tag,
|
|
911
|
+
childEpoch: Number(next.newState.groupContext.epoch),
|
|
912
|
+
commitBytes,
|
|
913
|
+
commitDigest: commitDigest(commitBytes),
|
|
914
|
+
childSnapshot: serializeClientState(next.newState),
|
|
915
|
+
senderLeafIndex: sender,
|
|
916
|
+
});
|
|
917
|
+
// Seam (`removalFinality`): the edge's facts, before the recursion.
|
|
918
|
+
const facts = this.#removalFinality
|
|
919
|
+
? edgeFactsOf(state, next.newState, sender)
|
|
920
|
+
: undefined;
|
|
921
|
+
if (facts !== undefined)
|
|
922
|
+
edgeFacts.set(bytesToHex(commitDigest(commitBytes)), facts);
|
|
923
|
+
if (this.#removalCandidates)
|
|
924
|
+
snapshots.set(tag, edges[edges.length - 1].childSnapshot);
|
|
925
|
+
await explore(next.newState, message, new Set([...seen, tag]), [
|
|
926
|
+
...chain,
|
|
927
|
+
{
|
|
928
|
+
parent: state,
|
|
929
|
+
message,
|
|
930
|
+
child: next.newState,
|
|
931
|
+
senderLeafIndex: sender,
|
|
932
|
+
},
|
|
933
|
+
], accumulated, withPath
|
|
934
|
+
? [
|
|
935
|
+
...path,
|
|
936
|
+
edgeOf(state, message, sender, tag, facts?.removed),
|
|
937
|
+
]
|
|
938
|
+
: path);
|
|
939
|
+
}
|
|
940
|
+
if (!extended && !branchDeferred && tipMessage !== undefined) {
|
|
941
|
+
// A removed receiver's ts-mls tombstone retains its parent epoch even
|
|
942
|
+
// though the authenticated Commit is one edge past the fork root.
|
|
943
|
+
const tipEpoch = Math.max(Number(state.groupContext.epoch), forkEpoch + chain.length);
|
|
944
|
+
const branch = {
|
|
945
|
+
id: `branch-${counter++}`,
|
|
946
|
+
forkEpoch,
|
|
947
|
+
tipEpoch,
|
|
948
|
+
tipDigest: this.#commitDigestOf(tipMessage),
|
|
949
|
+
tipCommitter: (() => {
|
|
950
|
+
// The tip link's authenticated sender (the chain's last link
|
|
951
|
+
// applied `tipMessage`), resolved in its own parent's tree.
|
|
952
|
+
const last = chain.at(-1);
|
|
953
|
+
return last === undefined
|
|
954
|
+
? new Uint8Array()
|
|
955
|
+
: tipCommitterOf(last.parent, last.senderLeafIndex);
|
|
956
|
+
})(),
|
|
957
|
+
// Drop witnesses at/before the fork epoch or outside the retained
|
|
958
|
+
// app-payload window for this candidate's tip, so stale or pre-fork
|
|
959
|
+
// app payloads cannot influence branch scores.
|
|
960
|
+
appWitnesses: accumulated.filter((w) => isWitnessEligible(w, forkEpoch, tipEpoch, this.#policy)),
|
|
961
|
+
...(withPath ? { path } : {}),
|
|
962
|
+
};
|
|
963
|
+
tips.set(branch, state);
|
|
964
|
+
chains.set(branch, chain);
|
|
965
|
+
branches.push(branch);
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
await explore(root, undefined, new Set([bytesToHex(root.confirmationTag)]), [], [], []);
|
|
969
|
+
if (opaque.drafts.size > 0) {
|
|
970
|
+
const hidden = new Set();
|
|
971
|
+
for (const envelope of encrypted) {
|
|
972
|
+
const id = this.#peeler.idOf(envelope);
|
|
973
|
+
if (!peeledIds.has(id))
|
|
974
|
+
hidden.add(id);
|
|
975
|
+
}
|
|
976
|
+
// The group's persisted undecryptable set (Design Decision 3a): an id
|
|
977
|
+
// some explored state decrypted is no hidden edge.
|
|
978
|
+
for (const id of undecryptable)
|
|
979
|
+
if (!peeledIds.has(id))
|
|
980
|
+
hidden.add(id);
|
|
981
|
+
opaque.undecryptable = hidden.size;
|
|
982
|
+
}
|
|
983
|
+
return {
|
|
984
|
+
branches,
|
|
985
|
+
tips,
|
|
986
|
+
chains,
|
|
987
|
+
edges,
|
|
988
|
+
edgeFacts,
|
|
989
|
+
awaitingProposal: new Set([...missing].filter((d) => !resolved.has(d))),
|
|
990
|
+
removals,
|
|
991
|
+
fenced,
|
|
992
|
+
rejected: new Map([...rejected].filter(([digest]) => !resolved.has(digest))),
|
|
993
|
+
opaque,
|
|
994
|
+
};
|
|
995
|
+
}
|
|
996
|
+
/**
|
|
997
|
+
* Resolves a fork at `forkEpoch` (`convergence.md`): rebuilds candidate
|
|
998
|
+
* branches by replaying retained applied commits plus the competing `pool`,
|
|
999
|
+
* selects the canonical branch, and reports it when it differs from the
|
|
1000
|
+
* caller's current tip. The caller applies the rewind (state + lifecycle).
|
|
1001
|
+
*/
|
|
1002
|
+
async resolveFork(params) {
|
|
1003
|
+
const { forkEpoch, pool, encrypted = [], witnessEnvelopes = [], witnessMessages = [], currentState, retained, adminCallback, adminCallbackFor, terminalCandidates = new Map(), knownCandidates = new Map(), undecryptable = new Set(), undecryptableSaturated = false, holdCouldWin = false, } = params;
|
|
1004
|
+
const root = retained.stateAt(forkEpoch);
|
|
1005
|
+
if (!root)
|
|
1006
|
+
return { outcome: "skip" };
|
|
1007
|
+
const currentTipEpoch = Number(currentState.groupContext.epoch);
|
|
1008
|
+
const retainedLinks = retained.appliedLinksBetween?.(forkEpoch, currentTipEpoch);
|
|
1009
|
+
const ours = retainedLinks
|
|
1010
|
+
? retainedLinks.map((link) => link.message)
|
|
1011
|
+
: retained.appliedCommitsBetween(forkEpoch, currentTipEpoch);
|
|
1012
|
+
if (ours.length === 0 && pool.length === 0)
|
|
1013
|
+
return { outcome: "skip" };
|
|
1014
|
+
// CONV-04: every commit in `ours` already applied on our own canonical
|
|
1015
|
+
// branch, so `RetainedHistoryStore` already holds the exact state it
|
|
1016
|
+
// produced — `record()` stores both the parent and the resulting state
|
|
1017
|
+
// for every applied commit (own-authored via `confirmPublished`, or
|
|
1018
|
+
// inbound via `ctx.recordCommit`, through the identical recording path).
|
|
1019
|
+
// `#buildBranches` uses this instead of replaying these commits through
|
|
1020
|
+
// `processMessage`, which cannot reprocess a commit whose committer leaf
|
|
1021
|
+
// is the replaying leaf itself (RFC 9420: an `UpdatePath` never encrypts a
|
|
1022
|
+
// path secret to its own committer). Each state is cloned via a
|
|
1023
|
+
// serialize/deserialize round trip before handing it into the DFS —
|
|
1024
|
+
// continued exploration from a state consumes/derives further secrets on
|
|
1025
|
+
// it, and the original must stay untouched since it is the same object
|
|
1026
|
+
// `RetainedHistoryStore` (and possibly the live engine) still holds.
|
|
1027
|
+
// The recorded PARENT is captured alongside the resulting state so
|
|
1028
|
+
// `#buildBranches` can only take the short-circuit at the node that
|
|
1029
|
+
// actually produced this child — see {@link KnownNextState}.
|
|
1030
|
+
const knownNextStates = new Map(knownCandidates);
|
|
1031
|
+
for (const [index, msg] of ours.entries()) {
|
|
1032
|
+
const structural = retainedLinks?.[index];
|
|
1033
|
+
if (!structural?.ownCommitStamp)
|
|
1034
|
+
continue;
|
|
1035
|
+
const sourceEpoch = Number(structural
|
|
1036
|
+
? Number(structural.parentState.groupContext.epoch)
|
|
1037
|
+
: framedEpoch(msg));
|
|
1038
|
+
if (!Number.isFinite(sourceEpoch))
|
|
1039
|
+
continue;
|
|
1040
|
+
const parent = structural?.parentState ?? retained.stateAt(sourceEpoch);
|
|
1041
|
+
const next = structural?.resultingState ?? retained.stateAt(sourceEpoch + 1);
|
|
1042
|
+
if (!parent || !next)
|
|
1043
|
+
continue;
|
|
1044
|
+
knownNextStates.set(bytesToHex(this.#commitDigestOf(msg)), {
|
|
1045
|
+
parentTag: bytesToHex(parent.confirmationTag),
|
|
1046
|
+
state: deserializeClientState(serializeClientState(next)),
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
const { branches, tips, chains, edges, edgeFacts, awaitingProposal, removals, fenced, rejected, opaque, } = await this.#buildBranches(root, [...ours, ...pool], encrypted, witnessEnvelopes, adminCallback, knownNextStates, terminalCandidates, adminCallbackFor, this.#branchAwareFence ? undecryptable : new Set(), this.#branchAwareFence && undecryptableSaturated, witnessMessages);
|
|
1050
|
+
const rejectedReport = rejected.size > 0 ? { rejected } : {};
|
|
1051
|
+
// A replay that found this device's own path secrets lost decides nothing:
|
|
1052
|
+
// no branch built from this state can be trusted, and the client fences.
|
|
1053
|
+
// Seam (`branchAwareFence`): not before selection — each fenced commit is
|
|
1054
|
+
// decided against the processable branches below.
|
|
1055
|
+
if (!this.#branchAwareFence && fenced.size > 0)
|
|
1056
|
+
return { outcome: "skip", awaitingProposal, fenced, ...rejectedReport };
|
|
1057
|
+
// Seam (`branchAwareFence`): the per-digest decision. The processable
|
|
1058
|
+
// selection below has a winner exactly when some processable branch is
|
|
1059
|
+
// eligible, which is all the decision reads of it (no eligible branch:
|
|
1060
|
+
// every fenced commit fences); the decision needs no more than the
|
|
1061
|
+
// processable set, so it runs first and the early exits can carry it.
|
|
1062
|
+
const opaqueDecision = this.#branchAwareFence && fenced.size > 0
|
|
1063
|
+
? this.#decideOpaque({
|
|
1064
|
+
currentTipEpoch,
|
|
1065
|
+
root,
|
|
1066
|
+
branches,
|
|
1067
|
+
chains: [...chains.values()],
|
|
1068
|
+
fenced,
|
|
1069
|
+
opaque,
|
|
1070
|
+
holdCouldWin,
|
|
1071
|
+
})
|
|
1072
|
+
: undefined;
|
|
1073
|
+
const opaqueReport = opaqueDecision
|
|
1074
|
+
? {
|
|
1075
|
+
...(opaqueDecision.skipped.size > 0
|
|
1076
|
+
? {
|
|
1077
|
+
opaqueSkipped: opaqueDecision.skipped,
|
|
1078
|
+
opaqueHeld: new Map([...opaqueDecision.skipped].flatMap((digest) => {
|
|
1079
|
+
const draft = opaque.drafts.get(digest);
|
|
1080
|
+
return draft === undefined
|
|
1081
|
+
? []
|
|
1082
|
+
: [
|
|
1083
|
+
[
|
|
1084
|
+
digest,
|
|
1085
|
+
{
|
|
1086
|
+
parentTag: draft.headEdge.parentId,
|
|
1087
|
+
parentEpoch: draft.parentEpoch,
|
|
1088
|
+
senderLeafIndex: draft.headEdge.senderLeafIndex,
|
|
1089
|
+
cause: fenced.get(digest),
|
|
1090
|
+
...(draft.headEdge.removed === undefined
|
|
1091
|
+
? {}
|
|
1092
|
+
: { removed: draft.headEdge.removed }),
|
|
1093
|
+
},
|
|
1094
|
+
],
|
|
1095
|
+
];
|
|
1096
|
+
})),
|
|
1097
|
+
}
|
|
1098
|
+
: {}),
|
|
1099
|
+
...(opaqueDecision.fromEncrypted.size > 0
|
|
1100
|
+
? { opaqueEncrypted: opaqueDecision.fromEncrypted }
|
|
1101
|
+
: {}),
|
|
1102
|
+
}
|
|
1103
|
+
: {};
|
|
1104
|
+
if (branches.length === 0) {
|
|
1105
|
+
if (opaqueDecision !== undefined && opaqueDecision.fenced.size > 0)
|
|
1106
|
+
return {
|
|
1107
|
+
outcome: "skip",
|
|
1108
|
+
awaitingProposal,
|
|
1109
|
+
fenced: opaqueDecision.fenced,
|
|
1110
|
+
...rejectedReport,
|
|
1111
|
+
...(opaqueDecision.equivocations.length > 0
|
|
1112
|
+
? { equivocations: opaqueDecision.equivocations }
|
|
1113
|
+
: {}),
|
|
1114
|
+
...opaqueReport,
|
|
1115
|
+
};
|
|
1116
|
+
return {
|
|
1117
|
+
outcome: "skip",
|
|
1118
|
+
awaitingProposal,
|
|
1119
|
+
...rejectedReport,
|
|
1120
|
+
...opaqueReport,
|
|
1121
|
+
};
|
|
1122
|
+
}
|
|
1123
|
+
// Seam (`removalFinality`): the edges' facts, present only while the seam is effective.
|
|
1124
|
+
const edgeFactsReport = this.#removalFinality ? { edgeFacts } : {};
|
|
1125
|
+
// Seam (`equivocationCredit`): two-phase selection — the credit input is
|
|
1126
|
+
// resolved only when the candidate tree holds a candidate node. A node
|
|
1127
|
+
// whose state no chain link holds is left out of `nodes` (the core then
|
|
1128
|
+
// resolves it by today's ordering, per node); `senderKeys` covers every
|
|
1129
|
+
// chain edge, so deep cross-subtree evidence is key-checked.
|
|
1130
|
+
// Seam (`removalFinality`): with the seam effective phase 1 is structural
|
|
1131
|
+
// (every branching node of the candidate tree, ADR-017 R-6), and the input
|
|
1132
|
+
// carries the flag.
|
|
1133
|
+
const nodes = this.#equivocationCredit
|
|
1134
|
+
? phaseOneNodesOf(this.#removalFinality, currentTipEpoch, branches, this.#policy)
|
|
1135
|
+
: [];
|
|
1136
|
+
const selection = nodes.length === 0
|
|
1137
|
+
? undefined
|
|
1138
|
+
: selectCanonicalBranchCredited(currentTipEpoch, branches, this.#policy, creditInputFromChains(nodes.map(({ nodeId }) => nodeId), root, [...chains.values()], this.#removalFinality));
|
|
1139
|
+
const winner = selection === undefined
|
|
1140
|
+
? selectCanonicalBranch(currentTipEpoch, branches, this.#policy)
|
|
1141
|
+
: selection.winner;
|
|
1142
|
+
const equivocations = mergeEquivocations(selection?.equivocations ?? [], opaqueDecision?.equivocations ?? []);
|
|
1143
|
+
const report = equivocations.length > 0 ? { equivocations } : {};
|
|
1144
|
+
// Seam (`branchAwareFence`): a fenced commit that could win fences the
|
|
1145
|
+
// group exactly as today — nothing is selected or applied.
|
|
1146
|
+
if (opaqueDecision !== undefined && opaqueDecision.fenced.size > 0)
|
|
1147
|
+
return {
|
|
1148
|
+
outcome: "skip",
|
|
1149
|
+
awaitingProposal,
|
|
1150
|
+
fenced: opaqueDecision.fenced,
|
|
1151
|
+
...rejectedReport,
|
|
1152
|
+
...report,
|
|
1153
|
+
...opaqueReport,
|
|
1154
|
+
};
|
|
1155
|
+
const winnerTip = winner ? tips.get(winner) : undefined;
|
|
1156
|
+
if (!winner || !winnerTip)
|
|
1157
|
+
return {
|
|
1158
|
+
outcome: "superseded",
|
|
1159
|
+
edges,
|
|
1160
|
+
...edgeFactsReport,
|
|
1161
|
+
awaitingProposal,
|
|
1162
|
+
...rejectedReport,
|
|
1163
|
+
removals,
|
|
1164
|
+
...report,
|
|
1165
|
+
...opaqueReport,
|
|
1166
|
+
};
|
|
1167
|
+
const winnerScore = scoreBranch(winner, this.#policy);
|
|
1168
|
+
const runner = branches
|
|
1169
|
+
.filter((candidate) => candidate !== winner)
|
|
1170
|
+
.map((candidate) => scoreBranch(candidate, this.#policy))
|
|
1171
|
+
.sort((a, b) => compareBranchScores(b, a))[0];
|
|
1172
|
+
// Seam (`removalFinality`), SC-R5: the rule changed the local outcome at a
|
|
1173
|
+
// rule node on the winner's path. Nothing is reported or notified for it.
|
|
1174
|
+
const decisiveRule = selection?.decidedByRemoval
|
|
1175
|
+
? "removal_finality"
|
|
1176
|
+
: selection?.decidedByCredit
|
|
1177
|
+
? "equivocation_credit"
|
|
1178
|
+
: runner
|
|
1179
|
+
? winnerScore.effectiveCommitDepth !== runner.effectiveCommitDepth
|
|
1180
|
+
? "effective_commit_depth"
|
|
1181
|
+
: winnerScore.witnessQuorumMet !== runner.witnessQuorumMet
|
|
1182
|
+
? "witness_quorum_met"
|
|
1183
|
+
: winnerScore.appWitnessScore !== runner.appWitnessScore
|
|
1184
|
+
? "app_witness_score"
|
|
1185
|
+
: bytesToHex(winnerScore.tipCommitter) !==
|
|
1186
|
+
bytesToHex(runner.tipCommitter)
|
|
1187
|
+
? "tip_committer"
|
|
1188
|
+
: "tip_digest"
|
|
1189
|
+
: "only_candidate";
|
|
1190
|
+
const decision = {
|
|
1191
|
+
selectedBranchId: bytesToHex(winnerTip.confirmationTag),
|
|
1192
|
+
selectedTipDigest: bytesToHex(winner.tipDigest),
|
|
1193
|
+
selectedTipCommitter: bytesToHex(winnerScore.tipCommitter),
|
|
1194
|
+
decisiveRule,
|
|
1195
|
+
score: winnerScore,
|
|
1196
|
+
};
|
|
1197
|
+
const selectedTerminal = terminalCandidates.get(bytesToHex(winner.tipDigest));
|
|
1198
|
+
if (!selectedTerminal &&
|
|
1199
|
+
// Seam (S20): a removal's tombstone repeats its parent's tag — never "already current".
|
|
1200
|
+
!(this.#removalCandidates &&
|
|
1201
|
+
winnerTip.groupActiveState.kind === "removedFromGroup") &&
|
|
1202
|
+
bytesToHex(winnerTip.confirmationTag) ===
|
|
1203
|
+
bytesToHex(currentState.confirmationTag))
|
|
1204
|
+
return {
|
|
1205
|
+
outcome: "superseded",
|
|
1206
|
+
edges,
|
|
1207
|
+
...edgeFactsReport,
|
|
1208
|
+
awaitingProposal,
|
|
1209
|
+
...rejectedReport,
|
|
1210
|
+
removals,
|
|
1211
|
+
winnerTip,
|
|
1212
|
+
decision,
|
|
1213
|
+
selectedTerminal,
|
|
1214
|
+
...report,
|
|
1215
|
+
...opaqueReport,
|
|
1216
|
+
};
|
|
1217
|
+
return {
|
|
1218
|
+
outcome: "recovered",
|
|
1219
|
+
winnerTip,
|
|
1220
|
+
winnerChain: chains.get(winner) ?? [],
|
|
1221
|
+
edges,
|
|
1222
|
+
...edgeFactsReport,
|
|
1223
|
+
awaitingProposal,
|
|
1224
|
+
...rejectedReport,
|
|
1225
|
+
removals,
|
|
1226
|
+
decision,
|
|
1227
|
+
selectedTerminal,
|
|
1228
|
+
...report,
|
|
1229
|
+
...opaqueReport,
|
|
1230
|
+
...(() => {
|
|
1231
|
+
const tipLink = (chains.get(winner) ?? []).at(-1);
|
|
1232
|
+
const found = this.#branchAwareFence && tipLink !== undefined
|
|
1233
|
+
? opaque.fromEncrypted.get(bytesToHex(this.#commitDigestOf(tipLink.message)))
|
|
1234
|
+
: undefined;
|
|
1235
|
+
return found === undefined ? {} : { opaqueTipEnvelope: found };
|
|
1236
|
+
})(),
|
|
1237
|
+
result: {
|
|
1238
|
+
kind: "newState",
|
|
1239
|
+
newState: winnerTip,
|
|
1240
|
+
actionTaken: "accept",
|
|
1241
|
+
consumed: [],
|
|
1242
|
+
senderLeafIndex: undefined,
|
|
1243
|
+
aad: new Uint8Array(),
|
|
1244
|
+
},
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Seam (`branchAwareFence`): decides each fenced pool commit against the
|
|
1249
|
+
* processable `branches` (ADR-016 D6). A commit fences (the group is fenced
|
|
1250
|
+
* as today) when no processable branch is eligible, when its committer is
|
|
1251
|
+
* unknown, or when `opaqueCouldWin` says its best case `o*` — appended last,
|
|
1252
|
+
* so ties go to it — would be selected; otherwise it is skipped. `U` is the
|
|
1253
|
+
* interim count of {@link OpaqueInput.undecryptable}, the depth bound and (per
|
|
1254
|
+
* the instance's OQ-1 policy) the hidden-credit bound `H`.
|
|
1255
|
+
*
|
|
1256
|
+
* The credit input holds the node context of every state the replay held on
|
|
1257
|
+
* a candidate path and of every fenced parent `N` (LD-3), and the sender key
|
|
1258
|
+
* of every visible edge and head edge; a context missing there would drop a
|
|
1259
|
+
* node to today's ordering silently. `equivocations` is the report of the
|
|
1260
|
+
* candidate tree with the opaque head edges in it (each `o*` is an extra
|
|
1261
|
+
* candidate whose path ends at its head edge): the device's own commit and a
|
|
1262
|
+
* clone's head edge at one node are the direct equivocation by its leaf.
|
|
1263
|
+
*/
|
|
1264
|
+
#decideOpaque(params) {
|
|
1265
|
+
const { currentTipEpoch, root, branches, chains, fenced, opaque } = params;
|
|
1266
|
+
const verdicts = decideOpaqueDrafts({
|
|
1267
|
+
policy: this.#policy,
|
|
1268
|
+
currentTipEpoch,
|
|
1269
|
+
branches,
|
|
1270
|
+
fenced,
|
|
1271
|
+
drafts: opaque.drafts,
|
|
1272
|
+
undecryptable: opaque.undecryptable,
|
|
1273
|
+
undecryptableSaturated: opaque.saturated,
|
|
1274
|
+
credit: creditInputOf(root, chains, opaque, this.#removalFinalityFence),
|
|
1275
|
+
hiddenCreditPolicy: this.#hiddenCreditPolicy,
|
|
1276
|
+
ownLeafIndex: Number(root.privatePath.leafIndex),
|
|
1277
|
+
});
|
|
1278
|
+
// Batch settle: while more of the caller's batch follows, a could-win
|
|
1279
|
+
// candidate that can be held (its committer is known) is held, not fenced.
|
|
1280
|
+
let decided = verdicts;
|
|
1281
|
+
if (params.holdCouldWin === true && verdicts.fenced.size > 0) {
|
|
1282
|
+
const fencedNow = new Map();
|
|
1283
|
+
const skipped = new Set(verdicts.skipped);
|
|
1284
|
+
for (const [digest, cause] of verdicts.fenced) {
|
|
1285
|
+
if (opaque.drafts.get(digest)?.headEdge.senderLeafIndex === undefined)
|
|
1286
|
+
fencedNow.set(digest, cause);
|
|
1287
|
+
else
|
|
1288
|
+
skipped.add(digest);
|
|
1289
|
+
}
|
|
1290
|
+
decided = { ...verdicts, fenced: fencedNow, skipped };
|
|
1291
|
+
}
|
|
1292
|
+
const fromEncrypted = new Map();
|
|
1293
|
+
for (const digest of [...decided.fenced.keys(), ...decided.skipped]) {
|
|
1294
|
+
const found = opaque.fromEncrypted.get(digest);
|
|
1295
|
+
if (found !== undefined)
|
|
1296
|
+
fromEncrypted.set(digest, found);
|
|
1297
|
+
}
|
|
1298
|
+
return { ...decided, fromEncrypted };
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
/** Seam (`branchAwareFence`), OQ-1: the shipped default of the hidden-credit policy. */
|
|
1302
|
+
export const DEFAULT_HIDDEN_CREDIT_POLICY = "conservative";
|
|
1303
|
+
/**
|
|
1304
|
+
* Seam (`branchAwareFence`), OQ-1: the hidden-credit policy an owner asked for.
|
|
1305
|
+
* `undefined` is the {@link DEFAULT_HIDDEN_CREDIT_POLICY}; exactly the two
|
|
1306
|
+
* {@link HiddenCreditPolicy} values are accepted; anything else is a
|
|
1307
|
+
* `TypeError` (a misspelt policy must not silently become the default).
|
|
1308
|
+
*/
|
|
1309
|
+
export function normalizeHiddenCreditPolicy(value) {
|
|
1310
|
+
if (value === undefined)
|
|
1311
|
+
return DEFAULT_HIDDEN_CREDIT_POLICY;
|
|
1312
|
+
if (value === "conservative" || value === "anchored-zero")
|
|
1313
|
+
return value;
|
|
1314
|
+
throw new TypeError(`invalid hiddenCreditPolicy: ${String(value)} (expected "conservative" or "anchored-zero")`);
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Seam (`branchAwareFence`): the per-digest fence decision of ADR-016 D6, one
|
|
1318
|
+
* function for every site that holds an opaque candidate — pool replay
|
|
1319
|
+
* ({@link ForkRecovery}) and the tree-fed sites of `MarmotGroupEngine` (the
|
|
1320
|
+
* removal parent and the tree sweep) — so the sites cannot drift apart. A
|
|
1321
|
+
* `drafts` entry fences when no processable `branch` is eligible, when its
|
|
1322
|
+
* committer is unknown (`headEdge.senderLeafIndex`), or when `opaqueCouldWin`
|
|
1323
|
+
* says its best case `o*` (appended last, so ties go to it) would be selected;
|
|
1324
|
+
* otherwise it is skipped. Every `fenced` digest is decided; `undecryptable`
|
|
1325
|
+
* is `U`, the depth bound and the hidden-credit bound `H` (`H = U` under the
|
|
1326
|
+
* default `conservative` policy; `hiddenCreditPolicy` and `ownLeafIndex` select
|
|
1327
|
+
* the OQ-1 alternative, see {@link HiddenCreditPolicy}). Candidates sharing (parent node, sender) are one
|
|
1328
|
+
* group, scored once at its best case (the minimal digest among all `drafts` of
|
|
1329
|
+
* the group, held members included) and decided together. `equivocations` is
|
|
1330
|
+
* the report of the candidate tree with every opaque head edge in it. Pure
|
|
1331
|
+
* given its inputs.
|
|
1332
|
+
*
|
|
1333
|
+
* Seam (`removalFinality`, architecture.md SC-R7, AC-HOLD-2): with
|
|
1334
|
+
* `credit.removalFinality` a group of two or more heads is a direct
|
|
1335
|
+
* equivocation the device sees, so every head of it is scored with
|
|
1336
|
+
* `headEquivocated` (anchored at its parent node) and the group fences iff ANY
|
|
1337
|
+
* head could win: the heads differ by digest and by their removal facts, and a
|
|
1338
|
+
* sibling's facts count at the parent's ancestors, so one representative is
|
|
1339
|
+
* sound only at the root (AR-R15). A group of one, and every group without the
|
|
1340
|
+
* flag, keeps the minimal-digest representative.
|
|
1341
|
+
* @internal
|
|
1342
|
+
*/
|
|
1343
|
+
export function decideOpaqueDrafts(params) {
|
|
1344
|
+
const { policy, currentTipEpoch, branches, fenced, drafts, credit } = params;
|
|
1345
|
+
const anyEligible = branches.some((branch) => isBranchEligible(currentTipEpoch, branch, policy));
|
|
1346
|
+
const candidates = new Map();
|
|
1347
|
+
for (const [digest, draft] of drafts)
|
|
1348
|
+
candidates.set(digest, {
|
|
1349
|
+
...draft,
|
|
1350
|
+
hiddenDepthBound: params.undecryptable,
|
|
1351
|
+
hiddenCreditBound: params.undecryptable,
|
|
1352
|
+
});
|
|
1353
|
+
const decided = {
|
|
1354
|
+
fenced: new Map(),
|
|
1355
|
+
skipped: new Set(),
|
|
1356
|
+
};
|
|
1357
|
+
// Collapse (Design Decision 6, AC-PERS-10): candidates sharing a parent node
|
|
1358
|
+
// and an authenticated sender are scored once, at the group's best case. Its
|
|
1359
|
+
// members share the committer, so the best case is the minimal digest: at
|
|
1360
|
+
// `U = 0` the head digests decide and two heads of one sender can straddle
|
|
1361
|
+
// the digest they compete with, and the lower one governs; at `U >= 1` the
|
|
1362
|
+
// hidden tip is minimal anyway. Every member of the group gets the verdict
|
|
1363
|
+
// of that representative, whether it is being decided now or only held (the
|
|
1364
|
+
// `drafts` hold the group's held members too). Digests are fixed-width
|
|
1365
|
+
// lowercase hex, so their string order is their byte order.
|
|
1366
|
+
const groupKeyOf = (digest) => {
|
|
1367
|
+
const edge = candidates.get(digest)?.headEdge;
|
|
1368
|
+
return edge === undefined || edge.senderLeafIndex === undefined
|
|
1369
|
+
? undefined
|
|
1370
|
+
: `${edge.parentId}:${edge.senderLeafIndex}`;
|
|
1371
|
+
};
|
|
1372
|
+
const lowest = new Map();
|
|
1373
|
+
for (const digest of candidates.keys()) {
|
|
1374
|
+
const key = groupKeyOf(digest);
|
|
1375
|
+
if (key === undefined)
|
|
1376
|
+
continue;
|
|
1377
|
+
const known = lowest.get(key);
|
|
1378
|
+
if (known === undefined || digest < known)
|
|
1379
|
+
lowest.set(key, digest);
|
|
1380
|
+
}
|
|
1381
|
+
const verdicts = new Map();
|
|
1382
|
+
// Seam (`removalFinality`): the group's members, for the per-head OR.
|
|
1383
|
+
const flagged = credit.removalFinality === true;
|
|
1384
|
+
const members = new Map();
|
|
1385
|
+
if (flagged)
|
|
1386
|
+
for (const digest of candidates.keys()) {
|
|
1387
|
+
const key = groupKeyOf(digest);
|
|
1388
|
+
if (key !== undefined)
|
|
1389
|
+
members.set(key, [...(members.get(key) ?? []), digest]);
|
|
1390
|
+
}
|
|
1391
|
+
const groupVerdicts = new Map();
|
|
1392
|
+
for (const [digest, cause] of fenced) {
|
|
1393
|
+
const candidate = candidates.get(digest);
|
|
1394
|
+
let fence = !anyEligible ||
|
|
1395
|
+
params.undecryptableSaturated === true ||
|
|
1396
|
+
candidate === undefined ||
|
|
1397
|
+
candidate.headEdge.senderLeafIndex === undefined;
|
|
1398
|
+
const key = fence ? undefined : groupKeyOf(digest);
|
|
1399
|
+
const group = key === undefined ? undefined : members.get(key);
|
|
1400
|
+
if (!fence && group !== undefined && group.length >= 2) {
|
|
1401
|
+
if (!groupVerdicts.has(key))
|
|
1402
|
+
groupVerdicts.set(key, group.some((member) => opaqueCouldWin(currentTipEpoch, branches, candidates.get(member), policy, credit, {
|
|
1403
|
+
hiddenCreditPolicy: params.hiddenCreditPolicy,
|
|
1404
|
+
ownLeafIndex: params.ownLeafIndex,
|
|
1405
|
+
headEquivocated: true,
|
|
1406
|
+
})));
|
|
1407
|
+
fence = groupVerdicts.get(key);
|
|
1408
|
+
}
|
|
1409
|
+
else if (!fence) {
|
|
1410
|
+
const representative = lowest.get(key);
|
|
1411
|
+
if (!verdicts.has(representative))
|
|
1412
|
+
verdicts.set(representative, opaqueCouldWin(currentTipEpoch, branches, candidates.get(representative), policy, credit, {
|
|
1413
|
+
hiddenCreditPolicy: params.hiddenCreditPolicy,
|
|
1414
|
+
ownLeafIndex: params.ownLeafIndex,
|
|
1415
|
+
}));
|
|
1416
|
+
fence = verdicts.get(representative);
|
|
1417
|
+
}
|
|
1418
|
+
if (fence)
|
|
1419
|
+
decided.fenced.set(digest, cause);
|
|
1420
|
+
else
|
|
1421
|
+
decided.skipped.add(digest);
|
|
1422
|
+
}
|
|
1423
|
+
const equivocations = selectCanonicalBranchCredited(currentTipEpoch, [...branches, ...[...candidates.values()].map(opaqueBestCase)], policy, credit).equivocations;
|
|
1424
|
+
return { ...decided, equivocations };
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Seam (`branchAwareFence`): the union of two equivocation reports, one entry
|
|
1428
|
+
* per (node, leaf), in the order selection reports them (epoch, node tag, leaf
|
|
1429
|
+
* index), the commit digests of a shared entry unioned and sorted. The first
|
|
1430
|
+
* argument alone when the second adds nothing.
|
|
1431
|
+
*/
|
|
1432
|
+
function mergeEquivocations(a, b) {
|
|
1433
|
+
if (b.length === 0)
|
|
1434
|
+
return a;
|
|
1435
|
+
const seen = new Map();
|
|
1436
|
+
for (const e of [...a, ...b]) {
|
|
1437
|
+
const key = `${e.nodeTag}:${e.leafIndex}`;
|
|
1438
|
+
const known = seen.get(key);
|
|
1439
|
+
// One entry per (node, leaf): the digests of both reports are unioned, so
|
|
1440
|
+
// an opaque head's digest is never lost behind the processable commits'.
|
|
1441
|
+
seen.set(key, known === undefined
|
|
1442
|
+
? e
|
|
1443
|
+
: {
|
|
1444
|
+
...known,
|
|
1445
|
+
commitDigests: [
|
|
1446
|
+
...new Set([...known.commitDigests, ...e.commitDigests]),
|
|
1447
|
+
].sort(),
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
return [...seen.values()].sort((x, y) => x.epoch - y.epoch ||
|
|
1451
|
+
(x.nodeTag < y.nodeTag ? -1 : x.nodeTag > y.nodeTag ? 1 : 0) ||
|
|
1452
|
+
x.leafIndex - y.leafIndex);
|
|
1453
|
+
}
|
|
1454
|
+
/**
|
|
1455
|
+
* Seam (`equivocationCredit`): the pool-replay {@link EquivocationCreditInput}
|
|
1456
|
+
* — membership of each candidate node `nodeIds` names whose state the `root`
|
|
1457
|
+
* or a chain link's parent holds (others are left out: per-node fallback) and,
|
|
1458
|
+
* for every chain edge, the sender's leaf signature key in the edge's parent
|
|
1459
|
+
* state.
|
|
1460
|
+
*/
|
|
1461
|
+
function creditInputFromChains(nodeIds, root, chains, removalFinality) {
|
|
1462
|
+
const { statesById, senderKeys, successions } = chainStatesAndKeys(root, chains);
|
|
1463
|
+
const nodes = new Map();
|
|
1464
|
+
for (const nodeId of nodeIds) {
|
|
1465
|
+
const state = statesById.get(nodeId);
|
|
1466
|
+
if (state !== undefined)
|
|
1467
|
+
nodes.set(nodeId, equivocationNodeContextOf(state));
|
|
1468
|
+
}
|
|
1469
|
+
return {
|
|
1470
|
+
nodes,
|
|
1471
|
+
senderKeys,
|
|
1472
|
+
successions,
|
|
1473
|
+
...(removalFinality ? { removalFinality: true } : {}),
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* The states `root` and the chains' link parents hold, by hex confirmation
|
|
1478
|
+
* tag, and the sender's leaf signature key of every chain edge by hex commit
|
|
1479
|
+
* digest — the facts {@link creditInputFromChains} resolves from — and, by the
|
|
1480
|
+
* same digest, the signature-key successions the edge made at its own
|
|
1481
|
+
* committer's leaf ({@link committerSuccessionsOf}; the link holds both states).
|
|
1482
|
+
*/
|
|
1483
|
+
function chainStatesAndKeys(root, chains) {
|
|
1484
|
+
const statesById = new Map([
|
|
1485
|
+
[bytesToHex(root.confirmationTag), root],
|
|
1486
|
+
]);
|
|
1487
|
+
const senderKeys = new Map();
|
|
1488
|
+
const successions = new Map();
|
|
1489
|
+
for (const chain of chains)
|
|
1490
|
+
for (const link of chain) {
|
|
1491
|
+
const parentId = bytesToHex(link.parent.confirmationTag);
|
|
1492
|
+
if (!statesById.has(parentId))
|
|
1493
|
+
statesById.set(parentId, link.parent);
|
|
1494
|
+
const key = senderLeafKeyOf(link.parent, link.senderLeafIndex);
|
|
1495
|
+
const digest = bytesToHex(commitDigest(encode(mlsMessageEncoder, link.message)));
|
|
1496
|
+
if (key !== undefined)
|
|
1497
|
+
senderKeys.set(digest, key);
|
|
1498
|
+
if (!successions.has(digest)) {
|
|
1499
|
+
const facts = committerSuccessionsOf(link.parent, link.child, link.senderLeafIndex);
|
|
1500
|
+
if (facts.length > 0)
|
|
1501
|
+
successions.set(digest, facts);
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
return { statesById, senderKeys, successions };
|
|
1505
|
+
}
|
|
1506
|
+
/**
|
|
1507
|
+
* Seam (`branchAwareFence`): the {@link EquivocationCreditInput} the opaque
|
|
1508
|
+
* candidates are scored over — a node context for every state the replay held
|
|
1509
|
+
* on a path (the chains' parents and `root`) and, taking precedence, the
|
|
1510
|
+
* contexts retained for the fenced parents and their paths (LD-3), and the
|
|
1511
|
+
* sender key of every chain edge and head edge. More nodes than selection's
|
|
1512
|
+
* two-phase input names: a context for a node without an equivocation changes
|
|
1513
|
+
* nothing, and the anchoring bound may need one where nothing is anchored yet.
|
|
1514
|
+
*/
|
|
1515
|
+
function creditInputOf(root, chains, opaque, removalFinality) {
|
|
1516
|
+
const { statesById, senderKeys, successions } = chainStatesAndKeys(root, chains);
|
|
1517
|
+
const nodes = new Map(opaque.contexts);
|
|
1518
|
+
for (const [id, state] of statesById)
|
|
1519
|
+
if (!nodes.has(id))
|
|
1520
|
+
nodes.set(id, equivocationNodeContextOf(state));
|
|
1521
|
+
for (const [digest, key] of opaque.senderKeys)
|
|
1522
|
+
if (!senderKeys.has(digest))
|
|
1523
|
+
senderKeys.set(digest, key);
|
|
1524
|
+
for (const [digest, facts] of opaque.successions)
|
|
1525
|
+
if (!successions.has(digest))
|
|
1526
|
+
successions.set(digest, facts);
|
|
1527
|
+
return {
|
|
1528
|
+
nodes,
|
|
1529
|
+
senderKeys,
|
|
1530
|
+
successions,
|
|
1531
|
+
...(removalFinality ? { removalFinality: true } : {}),
|
|
1532
|
+
};
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Collects the {@link AppWitness}es that decrypt against a single candidate
|
|
1536
|
+
* `state` (`convergence.md` "App-payload witnesses"): each witness envelope is
|
|
1537
|
+
* peeled and processed, and an authenticated application message contributes a
|
|
1538
|
+
* witness keyed by the sender's account pubkey. Seam: the witness is credited
|
|
1539
|
+
* at the epoch the message was SENT in (its framing), not at the epoch of the
|
|
1540
|
+
* state that happened to decrypt it, so a payload sent at or before a fork root
|
|
1541
|
+
* that a post-root snapshot still decrypts (`historicalReceiverData`) is not a
|
|
1542
|
+
* witness for the branch (`isWitnessEligible`: strictly after the fork) and one
|
|
1543
|
+
* message is not credited once per node it decrypts on. Used by both
|
|
1544
|
+
* the pool-replay branch builder ({@link ForkRecovery}) and the tree-fed
|
|
1545
|
+
* re-convergence pass, which gathers witnesses per retained fork-branch node.
|
|
1546
|
+
*/
|
|
1547
|
+
export async function collectWitnessesAt(params) {
|
|
1548
|
+
const { peeler, ciphersuite, clientConfig, state, witnessEnvelopes, callback } = params;
|
|
1549
|
+
const out = [];
|
|
1550
|
+
for (const envelope of witnessEnvelopes) {
|
|
1551
|
+
try {
|
|
1552
|
+
const decrypted = await peeler.peelGroupMessages([envelope], state);
|
|
1553
|
+
for (const pair of decrypted.read) {
|
|
1554
|
+
if (pair.message.wireformat !== wireformats.mls_private_message)
|
|
1555
|
+
continue;
|
|
1556
|
+
const r = await processMessage({
|
|
1557
|
+
context: {
|
|
1558
|
+
cipherSuite: ciphersuite,
|
|
1559
|
+
authService: marmotAuthService,
|
|
1560
|
+
externalPsks: {},
|
|
1561
|
+
clientConfig,
|
|
1562
|
+
},
|
|
1563
|
+
state,
|
|
1564
|
+
message: pair.message,
|
|
1565
|
+
callback,
|
|
1566
|
+
});
|
|
1567
|
+
if (r.kind === "applicationMessage" &&
|
|
1568
|
+
r.senderLeafIndex !== undefined) {
|
|
1569
|
+
const credential = getCredentialFromLeafIndex(state.ratchetTree, r.senderLeafIndex);
|
|
1570
|
+
const sentIn = framedEpoch(pair.message);
|
|
1571
|
+
out.push({
|
|
1572
|
+
epoch: sentIn === undefined
|
|
1573
|
+
? Number(state.groupContext.epoch)
|
|
1574
|
+
: Number(sentIn),
|
|
1575
|
+
sender: hexToBytes(getCredentialPubkey(credential)),
|
|
1576
|
+
});
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
catch {
|
|
1581
|
+
/* not a witness on this state */
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
return out;
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* Presents an MLS message as its own envelope, so {@link collectWitnessesAt}
|
|
1588
|
+
* weighs it without a transport layer.
|
|
1589
|
+
*/
|
|
1590
|
+
const MESSAGE_WITNESS_PEELER = {
|
|
1591
|
+
peelGroupMessages: async (messages) => ({
|
|
1592
|
+
read: messages.map((message) => ({ envelope: message, message })),
|
|
1593
|
+
unreadable: [],
|
|
1594
|
+
}),
|
|
1595
|
+
wrapGroupMessage: () => {
|
|
1596
|
+
throw new Error("a persisted witness message is never re-wrapped");
|
|
1597
|
+
},
|
|
1598
|
+
idOf: () => {
|
|
1599
|
+
throw new Error("a persisted witness message has no transport id");
|
|
1600
|
+
},
|
|
1601
|
+
};
|
|
1602
|
+
/**
|
|
1603
|
+
* {@link collectWitnessesAt} for application messages the history tree kept
|
|
1604
|
+
* across a restart (`GroupHistoryTree#witnesses`): the tree holds the MLS
|
|
1605
|
+
* message, not the transport envelope it arrived in, so there is nothing to
|
|
1606
|
+
* peel — each message is processed against `state` directly.
|
|
1607
|
+
*/
|
|
1608
|
+
export function collectMessageWitnessesAt(params) {
|
|
1609
|
+
const { witnessMessages, ...rest } = params;
|
|
1610
|
+
return collectWitnessesAt({
|
|
1611
|
+
...rest,
|
|
1612
|
+
peeler: MESSAGE_WITNESS_PEELER,
|
|
1613
|
+
witnessEnvelopes: [...witnessMessages],
|
|
1614
|
+
});
|
|
1615
|
+
}
|