@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,1150 @@
|
|
|
1
|
+
/** @module @category Core - Convergence */
|
|
2
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
3
|
+
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
4
|
+
import { isAppPayloadExpired } from "./retained-history.js";
|
|
5
|
+
/**
|
|
6
|
+
* The default Marmot convergence policy — profile version 1 (`convergence.md`).
|
|
7
|
+
* Groups without explicit policy bytes MUST treat this as active.
|
|
8
|
+
*/
|
|
9
|
+
export const DEFAULT_CONVERGENCE_POLICY = {
|
|
10
|
+
policyVersion: 1,
|
|
11
|
+
maxRewindCommits: 5,
|
|
12
|
+
appPayloadPastEpochLimit: 5,
|
|
13
|
+
settlementQuiescenceMs: 1000,
|
|
14
|
+
maxConvergencePassMs: 5000,
|
|
15
|
+
witnessQuorumSendersPerEpoch: 2,
|
|
16
|
+
witnessQuorumEpochs: 1,
|
|
17
|
+
maxWitnessOverrideDepth: 1,
|
|
18
|
+
};
|
|
19
|
+
/** Supplies the pinned v1 pass bound when decoding/configuring older policy input. */
|
|
20
|
+
export function normalizeConvergencePolicy(policy) {
|
|
21
|
+
return {
|
|
22
|
+
...policy,
|
|
23
|
+
maxConvergencePassMs: policy.maxConvergencePassMs ??
|
|
24
|
+
DEFAULT_CONVERGENCE_POLICY.maxConvergencePassMs,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Validates the witness-override invariant: a witness-quorum boost must never be
|
|
29
|
+
* able to push a branch past the rollback horizon, so
|
|
30
|
+
* `maxWitnessOverrideDepth <= maxRewindCommits`. Throws on violation.
|
|
31
|
+
*/
|
|
32
|
+
export function validateConvergencePolicy(policy) {
|
|
33
|
+
if (policy.maxWitnessOverrideDepth > policy.maxRewindCommits) {
|
|
34
|
+
throw new Error(`Convergence policy invalid: max_witness_override_depth ` +
|
|
35
|
+
`(${policy.maxWitnessOverrideDepth}) exceeds max_rewind_commits ` +
|
|
36
|
+
`(${policy.maxRewindCommits})`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Whether an app-payload witness counts toward a candidate branch's score
|
|
41
|
+
* (`convergence.md` "App-payload witnesses", `retained-history.md`
|
|
42
|
+
* "App-payload retention"). A witness MUST decrypt strictly after the branch's
|
|
43
|
+
* `forkEpoch` (a message at/before the fork is not a witness for any candidate)
|
|
44
|
+
* AND be inside the retained app-payload window evaluated with the candidate's
|
|
45
|
+
* `tipEpoch` as the reference tip. Stale or pre-fork app payloads MUST NOT
|
|
46
|
+
* influence branch selection.
|
|
47
|
+
*/
|
|
48
|
+
export function isWitnessEligible(witness, forkEpoch, tipEpoch, policy) {
|
|
49
|
+
return (witness.epoch > forkEpoch &&
|
|
50
|
+
!isAppPayloadExpired(witness.epoch, tipEpoch, policy.appPayloadPastEpochLimit));
|
|
51
|
+
}
|
|
52
|
+
function witnessesByEpoch(witnesses) {
|
|
53
|
+
const byEpoch = new Map();
|
|
54
|
+
for (const witness of witnesses) {
|
|
55
|
+
let senders = byEpoch.get(witness.epoch);
|
|
56
|
+
if (!senders) {
|
|
57
|
+
senders = new Set();
|
|
58
|
+
byEpoch.set(witness.epoch, senders);
|
|
59
|
+
}
|
|
60
|
+
senders.add(bytesToHex(witness.sender));
|
|
61
|
+
}
|
|
62
|
+
return byEpoch;
|
|
63
|
+
}
|
|
64
|
+
function witnessQuorumMet(witnesses, policy) {
|
|
65
|
+
if (policy.witnessQuorumSendersPerEpoch === 0 ||
|
|
66
|
+
policy.witnessQuorumEpochs === 0)
|
|
67
|
+
return false;
|
|
68
|
+
let qualifyingEpochs = 0;
|
|
69
|
+
for (const senders of witnessesByEpoch(witnesses).values()) {
|
|
70
|
+
if (senders.size >= policy.witnessQuorumSendersPerEpoch)
|
|
71
|
+
qualifyingEpochs++;
|
|
72
|
+
}
|
|
73
|
+
return qualifyingEpochs >= policy.witnessQuorumEpochs;
|
|
74
|
+
}
|
|
75
|
+
function appWitnessScore(witnesses, policy) {
|
|
76
|
+
let score = 0;
|
|
77
|
+
for (const senders of witnessesByEpoch(witnesses).values()) {
|
|
78
|
+
score += Math.min(senders.size, policy.witnessQuorumSendersPerEpoch);
|
|
79
|
+
}
|
|
80
|
+
return score;
|
|
81
|
+
}
|
|
82
|
+
function witnessDepthBoost(branch, policy) {
|
|
83
|
+
return witnessQuorumMet(branch.appWitnesses, policy)
|
|
84
|
+
? policy.maxWitnessOverrideDepth
|
|
85
|
+
: 0;
|
|
86
|
+
}
|
|
87
|
+
/** Computes the {@link BranchScore} for a candidate under a policy. */
|
|
88
|
+
export function scoreBranch(branch, policy) {
|
|
89
|
+
const validCommitDepth = Math.max(0, branch.tipEpoch - branch.forkEpoch);
|
|
90
|
+
return {
|
|
91
|
+
validCommitDepth,
|
|
92
|
+
effectiveCommitDepth: validCommitDepth + witnessDepthBoost(branch, policy),
|
|
93
|
+
witnessQuorumMet: witnessQuorumMet(branch.appWitnesses, policy),
|
|
94
|
+
appWitnessScore: appWitnessScore(branch.appWitnesses, policy),
|
|
95
|
+
tipDigest: branch.tipDigest,
|
|
96
|
+
tipCommitter: branch.tipCommitter ?? new Uint8Array(),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Lexicographic comparison over raw bytes (a<b → -1, a>b → 1, equal → 0). */
|
|
100
|
+
function compareBytes(a, b) {
|
|
101
|
+
const n = Math.min(a.length, b.length);
|
|
102
|
+
for (let i = 0; i < n; i++) {
|
|
103
|
+
if (a[i] !== b[i])
|
|
104
|
+
return a[i] < b[i] ? -1 : 1;
|
|
105
|
+
}
|
|
106
|
+
return a.length - b.length;
|
|
107
|
+
}
|
|
108
|
+
function cmpNum(a, b) {
|
|
109
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Compares two branch scores per `convergence.md` "Branch selection": higher
|
|
113
|
+
* effectiveCommitDepth, then witness quorum beats none, then higher
|
|
114
|
+
* rawCommitDepth, then higher appWitnessScore, then LOWER tipDigest. Returns a
|
|
115
|
+
* positive number when `a` ranks above `b` (so the canonical branch is the
|
|
116
|
+
* maximum under this ordering).
|
|
117
|
+
*/
|
|
118
|
+
export function compareBranchScores(a, b) {
|
|
119
|
+
return (cmpNum(a.effectiveCommitDepth, b.effectiveCommitDepth) ||
|
|
120
|
+
cmpNum(Number(a.witnessQuorumMet), Number(b.witnessQuorumMet)) ||
|
|
121
|
+
cmpNum(a.validCommitDepth, b.validCommitDepth) ||
|
|
122
|
+
cmpNum(a.appWitnessScore, b.appWitnessScore) ||
|
|
123
|
+
// Lower authenticated account identity wins, matching MDK.
|
|
124
|
+
compareBytes(b.tipCommitter, a.tipCommitter) ||
|
|
125
|
+
// Lower tip digest wins, so invert the byte comparison.
|
|
126
|
+
compareBytes(b.tipDigest, a.tipDigest));
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* A branch is eligible only inside the rollback horizon:
|
|
130
|
+
* `currentTipEpoch - forkEpoch <= maxRewindCommits` (`convergence.md`
|
|
131
|
+
* "Eligibility").
|
|
132
|
+
*
|
|
133
|
+
* This predicate is intentionally horizon-only and takes no retained anchor.
|
|
134
|
+
* `convergence.md` lists a second eligibility rule — "a branch that needs a
|
|
135
|
+
* retained state older than the retained anchor MUST NOT be selected" — but that
|
|
136
|
+
* guard is deliberately kept **separate** from this predicate, mirroring the
|
|
137
|
+
* reference engine's two-layer structure (`is_branch_eligible` is horizon-only;
|
|
138
|
+
* the anchor check lives in candidate admission + late-commit classification,
|
|
139
|
+
* always anchor-first). Keeping the anchor out of here lets the predicate be
|
|
140
|
+
* reused for horizon-only purposes (e.g. eligibility counts) and keeps it a pure
|
|
141
|
+
* function of policy + branch, with no dependency on retained-store state. The
|
|
142
|
+
* anchor guard is applied operationally: {@link classifyLateCommit} emits
|
|
143
|
+
* `beyond_anchor` for a sub-anchor commit (ingest), and fork recovery cannot
|
|
144
|
+
* build a branch whose `forkEpoch` state is no longer retained.
|
|
145
|
+
*/
|
|
146
|
+
export function isBranchEligible(currentTipEpoch, branch, policy) {
|
|
147
|
+
return (Math.max(0, currentTipEpoch - branch.forkEpoch) <= policy.maxRewindCommits);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Selects the canonical branch from candidates: filters to eligible branches and
|
|
151
|
+
* returns the maximum under {@link compareBranchScores}. On a full tie the later
|
|
152
|
+
* candidate wins (matching Rust `max_by`). Returns undefined if none eligible.
|
|
153
|
+
*
|
|
154
|
+
* Seam (`equivocationCredit`): with `credit` present this returns
|
|
155
|
+
* {@link selectCanonicalBranchCredited}'s winner; without it the body below runs
|
|
156
|
+
* unchanged.
|
|
157
|
+
*/
|
|
158
|
+
export function selectCanonicalBranch(currentTipEpoch, candidates, policy, credit) {
|
|
159
|
+
if (credit !== undefined)
|
|
160
|
+
return selectCanonicalBranchCredited(currentTipEpoch, candidates, policy, credit).winner;
|
|
161
|
+
let best;
|
|
162
|
+
let bestScore;
|
|
163
|
+
for (const candidate of candidates) {
|
|
164
|
+
if (!isBranchEligible(currentTipEpoch, candidate, policy))
|
|
165
|
+
continue;
|
|
166
|
+
const score = scoreBranch(candidate, policy);
|
|
167
|
+
if (bestScore === undefined || compareBranchScores(score, bestScore) >= 0) {
|
|
168
|
+
best = candidate;
|
|
169
|
+
bestScore = score;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return best;
|
|
173
|
+
}
|
|
174
|
+
function sameEdge(a, b) {
|
|
175
|
+
return (a.parentId === b.parentId &&
|
|
176
|
+
a.senderLeafIndex === b.senderLeafIndex &&
|
|
177
|
+
compareBytes(a.commitDigest, b.commitDigest) === 0);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Builds `T` over the eligible candidates, or `undefined` when it cannot be
|
|
181
|
+
* built consistently: no eligible candidate, an eligible candidate without a
|
|
182
|
+
* (non-empty, chained) `path`, eligible candidates that disagree on the root or
|
|
183
|
+
* on `forkEpoch`, or two paths that disagree on the edge reaching one node.
|
|
184
|
+
* `undefined` sends selection to the byte-identical fallback.
|
|
185
|
+
*
|
|
186
|
+
* Seam (`removalFinality`): with `readRemoved`, the copies of one edge merge their `removed` facts (architecture.md
|
|
187
|
+
* SC-R1): `edgeTo` keeps a present copy over an absent one, independent of visiting order, and two present copies that
|
|
188
|
+
* differ as sets of leaves make `T` unbuildable. Without it `removed` is never read.
|
|
189
|
+
*/
|
|
190
|
+
function candidateTreeOf(currentTipEpoch, candidates, policy, readRemoved = false) {
|
|
191
|
+
const eligible = [];
|
|
192
|
+
candidates.forEach((candidate, index) => {
|
|
193
|
+
if (isBranchEligible(currentTipEpoch, candidate, policy))
|
|
194
|
+
eligible.push({ candidate, index });
|
|
195
|
+
});
|
|
196
|
+
if (eligible.length === 0)
|
|
197
|
+
return undefined;
|
|
198
|
+
const forkEpoch = eligible[0].candidate.forkEpoch;
|
|
199
|
+
const rootId = eligible[0].candidate.path?.[0]?.parentId;
|
|
200
|
+
if (rootId === undefined)
|
|
201
|
+
return undefined;
|
|
202
|
+
const children = new Map();
|
|
203
|
+
const edgeTo = new Map();
|
|
204
|
+
const depth = new Map([[rootId, 0]]);
|
|
205
|
+
const tipsAt = new Map();
|
|
206
|
+
for (const entry of eligible) {
|
|
207
|
+
const path = entry.candidate.path;
|
|
208
|
+
if (path === undefined ||
|
|
209
|
+
path.length === 0 ||
|
|
210
|
+
path[0].parentId !== rootId ||
|
|
211
|
+
entry.candidate.forkEpoch !== forkEpoch)
|
|
212
|
+
return undefined;
|
|
213
|
+
for (let i = 0; i < path.length; i++) {
|
|
214
|
+
const edge = path[i];
|
|
215
|
+
if (i > 0 && edge.parentId !== path[i - 1].childId)
|
|
216
|
+
return undefined;
|
|
217
|
+
if (edge.childId === rootId || edge.childId === edge.parentId)
|
|
218
|
+
return undefined;
|
|
219
|
+
if (depth.get(edge.parentId) !== i)
|
|
220
|
+
return undefined;
|
|
221
|
+
const known = edgeTo.get(edge.childId);
|
|
222
|
+
if (known !== undefined) {
|
|
223
|
+
if (!sameEdge(known, edge))
|
|
224
|
+
return undefined;
|
|
225
|
+
if (readRemoved && edge.removed !== undefined) {
|
|
226
|
+
if (known.removed === undefined)
|
|
227
|
+
edgeTo.set(edge.childId, edge);
|
|
228
|
+
else if (!sameRemoved(known.removed, edge.removed))
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
edgeTo.set(edge.childId, edge);
|
|
234
|
+
depth.set(edge.childId, i + 1);
|
|
235
|
+
const siblings = children.get(edge.parentId);
|
|
236
|
+
if (siblings === undefined)
|
|
237
|
+
children.set(edge.parentId, [edge.childId]);
|
|
238
|
+
else
|
|
239
|
+
siblings.push(edge.childId);
|
|
240
|
+
}
|
|
241
|
+
const tip = path[path.length - 1].childId;
|
|
242
|
+
const atTip = tipsAt.get(tip);
|
|
243
|
+
if (atTip === undefined)
|
|
244
|
+
tipsAt.set(tip, [entry]);
|
|
245
|
+
else
|
|
246
|
+
atTip.push(entry);
|
|
247
|
+
}
|
|
248
|
+
// Two child edges of one node carrying the same commit cannot both be valid.
|
|
249
|
+
for (const childIds of children.values()) {
|
|
250
|
+
const digests = new Set(childIds.map((id) => bytesToHex(edgeTo.get(id).commitDigest)));
|
|
251
|
+
if (digests.size !== childIds.length)
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
return { rootId, forkEpoch, children, edgeTo, depth, tipsAt };
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The child subtrees of `nodeId` (SC-3 rule 1): one entry per child edge `e`
|
|
258
|
+
* of the node, holding `e` and the edges of `sub(e)` — `e` together with every
|
|
259
|
+
* edge of `T` below `e.childId`. Distinct child edges have disjoint subtrees.
|
|
260
|
+
*/
|
|
261
|
+
function childSubtreesOf(tree, nodeId) {
|
|
262
|
+
const below = (id) => (tree.children.get(id) ?? []).flatMap((childId) => [
|
|
263
|
+
tree.edgeTo.get(childId),
|
|
264
|
+
...below(childId),
|
|
265
|
+
]);
|
|
266
|
+
return (tree.children.get(nodeId) ?? []).map((childId) => ({
|
|
267
|
+
direct: tree.edgeTo.get(childId),
|
|
268
|
+
edges: [tree.edgeTo.get(childId), ...below(childId)],
|
|
269
|
+
}));
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The anchored child edges of `nodeId` (SC-3 rule 1): child id → sender `s`
|
|
273
|
+
* for every child edge `e` of the node whose defined sender `s` is carried by
|
|
274
|
+
* an evidence edge (per `isEvidence`) in some other child subtree `sub(e')`,
|
|
275
|
+
* `e' ≠ e`. `Excl(N, e)` is `{s}` exactly for these edges; `Eq(N)` is the set
|
|
276
|
+
* of their senders. A child edge is evidence for its own sender by
|
|
277
|
+
* construction, so two child edges by one sender anchor each other (`EqDirect`).
|
|
278
|
+
*/
|
|
279
|
+
function anchoredChildrenAt(tree, nodeId, isEvidence) {
|
|
280
|
+
const subtrees = childSubtreesOf(tree, nodeId);
|
|
281
|
+
const sendersOf = subtrees.map(({ direct, edges }) => {
|
|
282
|
+
const senders = new Set();
|
|
283
|
+
for (const edge of edges)
|
|
284
|
+
if (edge.senderLeafIndex !== undefined &&
|
|
285
|
+
isEvidence(edge, edge === direct))
|
|
286
|
+
senders.add(edge.senderLeafIndex);
|
|
287
|
+
return senders;
|
|
288
|
+
});
|
|
289
|
+
const anchored = new Map();
|
|
290
|
+
subtrees.forEach(({ direct }, i) => {
|
|
291
|
+
const head = direct.senderLeafIndex;
|
|
292
|
+
if (head === undefined)
|
|
293
|
+
return;
|
|
294
|
+
if (sendersOf.some((senders, j) => j !== i && senders.has(head)))
|
|
295
|
+
anchored.set(direct.childId, head);
|
|
296
|
+
});
|
|
297
|
+
return anchored;
|
|
298
|
+
}
|
|
299
|
+
/** The distinct values of `anchored`, ascending. */
|
|
300
|
+
function sendersOfAnchored(anchored) {
|
|
301
|
+
return [...new Set(anchored.values())].sort(cmpNum);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* The direct equivocations at `nodeId` (`EqDirect`, SC-3 rule 1): each defined
|
|
305
|
+
* sender leaf index carried by two or more child edges of the node itself,
|
|
306
|
+
* mapped to those edges' hex commit digests, ascending.
|
|
307
|
+
*/
|
|
308
|
+
function directEquivocatorsAt(tree, nodeId) {
|
|
309
|
+
const bySender = new Map();
|
|
310
|
+
for (const childId of tree.children.get(nodeId) ?? []) {
|
|
311
|
+
const edge = tree.edgeTo.get(childId);
|
|
312
|
+
if (edge.senderLeafIndex === undefined)
|
|
313
|
+
continue;
|
|
314
|
+
const digests = bySender.get(edge.senderLeafIndex);
|
|
315
|
+
const digest = bytesToHex(edge.commitDigest);
|
|
316
|
+
if (digests === undefined)
|
|
317
|
+
bySender.set(edge.senderLeafIndex, [digest]);
|
|
318
|
+
else
|
|
319
|
+
digests.push(digest);
|
|
320
|
+
}
|
|
321
|
+
const out = new Map();
|
|
322
|
+
for (const [leafIndex, digests] of bySender)
|
|
323
|
+
if (digests.length >= 2)
|
|
324
|
+
out.set(leafIndex, [...digests].sort());
|
|
325
|
+
return out;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Every candidate node of `T` (SC-3 rule 1, phase 1): a node with some child
|
|
329
|
+
* edge whose defined sender index is carried by an edge in another child
|
|
330
|
+
* subtree of the node, keys unchecked; with those child edges' sender indices
|
|
331
|
+
* ascending, in (depth, node id) order.
|
|
332
|
+
*/
|
|
333
|
+
function candidateNodesIn(tree) {
|
|
334
|
+
const out = [];
|
|
335
|
+
for (const nodeId of tree.children.keys()) {
|
|
336
|
+
const leafIndices = sendersOfAnchored(anchoredChildrenAt(tree, nodeId, () => true));
|
|
337
|
+
if (leafIndices.length > 0)
|
|
338
|
+
out.push({ nodeId, leafIndices });
|
|
339
|
+
}
|
|
340
|
+
return out.sort((a, b) => cmpNum(tree.depth.get(a.nodeId), tree.depth.get(b.nodeId)) ||
|
|
341
|
+
(a.nodeId < b.nodeId ? -1 : a.nodeId > b.nodeId ? 1 : 0));
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Resolves candidate node `nodeId` against `credit` (SC-3 rules 1 and 3b).
|
|
345
|
+
* An edge in a child subtree is evidence for its sender `s` when it is the
|
|
346
|
+
* subtree's direct child edge (its sender is resolved against the node's own
|
|
347
|
+
* tree), or when `s` is occupied at the node and the edge's sender key equals
|
|
348
|
+
* the node's key at `s` — an edge whose key is unresolved is never evidence.
|
|
349
|
+
* `undefined` — the node is then resolved by today's ordering, with nothing
|
|
350
|
+
* reported — when `credit` lacks the node, when no child edge is anchored
|
|
351
|
+
* after the key clause (`Eq(N)` empty), or when an index of `Eq(N)` lacks
|
|
352
|
+
* membership or account there.
|
|
353
|
+
*
|
|
354
|
+
* Seam (`branchAwareFence`): `forced` names child edges of the node that
|
|
355
|
+
* {@link opaqueCouldWin}'s anchoring bound treats as anchored although no
|
|
356
|
+
* visible edge anchors them (a hidden edge by their sender could). A forced
|
|
357
|
+
* edge anchors only when its defined sender is occupied at the node with an
|
|
358
|
+
* account — a hidden edge by anyone else is no evidence (key clause). Absent,
|
|
359
|
+
* the function is unchanged.
|
|
360
|
+
*/
|
|
361
|
+
function resolveNode(tree, nodeId, credit, forced) {
|
|
362
|
+
const context = credit.nodes.get(nodeId);
|
|
363
|
+
if (context === undefined)
|
|
364
|
+
return undefined;
|
|
365
|
+
const anchored = anchoredChildrenAt(tree, nodeId, (edge, direct) => {
|
|
366
|
+
if (direct)
|
|
367
|
+
return true;
|
|
368
|
+
const key = context.members.get(edge.senderLeafIndex);
|
|
369
|
+
return (key !== undefined &&
|
|
370
|
+
credit.senderKeys.get(bytesToHex(edge.commitDigest)) === key);
|
|
371
|
+
});
|
|
372
|
+
if (forced !== undefined)
|
|
373
|
+
for (const childId of forced) {
|
|
374
|
+
const sender = tree.edgeTo.get(childId)?.senderLeafIndex;
|
|
375
|
+
if (sender !== undefined &&
|
|
376
|
+
context.members.has(sender) &&
|
|
377
|
+
context.accounts.has(sender) &&
|
|
378
|
+
!anchored.has(childId))
|
|
379
|
+
anchored.set(childId, sender);
|
|
380
|
+
}
|
|
381
|
+
if (anchored.size === 0)
|
|
382
|
+
return undefined;
|
|
383
|
+
for (const leafIndex of anchored.values())
|
|
384
|
+
if (!context.members.has(leafIndex) || !context.accounts.has(leafIndex))
|
|
385
|
+
return undefined;
|
|
386
|
+
return { anchored, direct: directEquivocatorsAt(tree, nodeId), context };
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Seam (`equivocationCredit`), phase 1: the candidate nodes of the candidate
|
|
390
|
+
* tree `T` — the union of the eligible candidates' {@link BranchCandidate.path}s
|
|
391
|
+
* — each a node with some child edge whose defined sender leaf index is also
|
|
392
|
+
* carried by an edge in another child subtree of the node (keys unchecked),
|
|
393
|
+
* with those child edges' sender indices ascending. Ordered by distance from
|
|
394
|
+
* the shared root, then node id.
|
|
395
|
+
*
|
|
396
|
+
* This is a superset of the equivocation nodes: phase 2 applies the key clause
|
|
397
|
+
* and may still resolve a node by today's ordering (SC-3 rule 3b — no context,
|
|
398
|
+
* no anchored child edge after the key clause, or an equivocator without
|
|
399
|
+
* membership there). Empty
|
|
400
|
+
* exactly when {@link selectCanonicalBranchCredited} falls back globally (rule
|
|
401
|
+
* 3a): no eligible candidate, or `T` cannot be built — an eligible candidate
|
|
402
|
+
* without a non-empty chained path, eligible paths with different roots or
|
|
403
|
+
* `forkEpoch`s, two paths disagreeing on the edge into one node, or two child
|
|
404
|
+
* edges of one node with one digest (see `candidateTreeOf`) — or `T` has no
|
|
405
|
+
* candidate node. Pure: the shell resolves an {@link EquivocationCreditInput}
|
|
406
|
+
* only when this is non-empty, and needs node contexts for these nodes and
|
|
407
|
+
* sender keys for every edge below them.
|
|
408
|
+
*/
|
|
409
|
+
export function equivocationNodesOf(currentTipEpoch, candidates, policy) {
|
|
410
|
+
const tree = candidateTreeOf(currentTipEpoch, candidates, policy);
|
|
411
|
+
return tree === undefined ? [] : candidateNodesIn(tree);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Credited depth of `entry` at equivocation node `nodeId` (ADR-016 D2, SC-3
|
|
415
|
+
* rule 2): the edges of its path from the child edge `e` leaving the node to
|
|
416
|
+
* its tip whose sender is a defined leaf outside `Excl(N, e)` — the sender of
|
|
417
|
+
* `e` when `e` is anchored, else nobody — that occupies the same index at the
|
|
418
|
+
* node with the same leaf signature key. An equivocator's edges are thus
|
|
419
|
+
* discounted only inside the child subtree it heads. A candidate whose tip is
|
|
420
|
+
* the node itself earns 0.
|
|
421
|
+
*
|
|
422
|
+
* Lineage clause (key rotation, `successions`): the key a sender's edges are
|
|
423
|
+
* credited under is its key at the node until one of ITS OWN edges, credited
|
|
424
|
+
* under that key, carries a `commit`-source succession of that very leaf away
|
|
425
|
+
* from it (the committer's UpdatePath leaf: a device that rotated its own key);
|
|
426
|
+
* the sender's later edges on this path are then credited under the new key.
|
|
427
|
+
* Nothing else extends the keys: a key change delivered by an Update proposal
|
|
428
|
+
* (the committer is another leaf), a Remove plus re-Add at the index (a
|
|
429
|
+
* `key_package` leaf, no succession), or a succession of another leaf leaves the
|
|
430
|
+
* credited key where it was, so the sender's later edges earn 0 as before. A
|
|
431
|
+
* missing fact leaves it there too (fail-closed). With `successions` absent the
|
|
432
|
+
* credited key never moves: the credit is the one of ADR-016 D2 rule 4.
|
|
433
|
+
*/
|
|
434
|
+
function creditAt(nodeId, entry, anchored, node, senderKeys, successions) {
|
|
435
|
+
const path = entry.candidate.path;
|
|
436
|
+
const from = path.findIndex((edge) => edge.parentId === nodeId);
|
|
437
|
+
if (from < 0)
|
|
438
|
+
return 0;
|
|
439
|
+
const excluded = anchored.get(path[from].childId);
|
|
440
|
+
const creditedKey = new Map();
|
|
441
|
+
let credit = 0;
|
|
442
|
+
for (let i = from; i < path.length; i++) {
|
|
443
|
+
const sender = path[i].senderLeafIndex;
|
|
444
|
+
if (sender === undefined || sender === excluded)
|
|
445
|
+
continue;
|
|
446
|
+
const nodeKey = node.members.get(sender);
|
|
447
|
+
if (nodeKey === undefined)
|
|
448
|
+
continue;
|
|
449
|
+
const held = creditedKey.get(sender) ?? nodeKey;
|
|
450
|
+
const digest = bytesToHex(path[i].commitDigest);
|
|
451
|
+
if (senderKeys.get(digest) !== held)
|
|
452
|
+
continue;
|
|
453
|
+
credit++;
|
|
454
|
+
const next = successions
|
|
455
|
+
?.get(digest)
|
|
456
|
+
?.find((s) => s.source === "commit" &&
|
|
457
|
+
s.leafIndex === sender &&
|
|
458
|
+
s.fromKey === held &&
|
|
459
|
+
s.toKey !== held)?.toKey;
|
|
460
|
+
if (next !== undefined)
|
|
461
|
+
creditedKey.set(sender, next);
|
|
462
|
+
}
|
|
463
|
+
return credit;
|
|
464
|
+
}
|
|
465
|
+
// ---------------------------------------------------------------------------
|
|
466
|
+
// Seam (`removalFinality`): ADR-017 R-3 to R-7 (architecture.md SC-R1 to SC-R5).
|
|
467
|
+
// Read only when `credit.removalFinality === true`; every function below is
|
|
468
|
+
// pure and total over plain data. The test trace sink (`traceRemovalFinality`)
|
|
469
|
+
// is the only module state, and no result ever reads it.
|
|
470
|
+
// ---------------------------------------------------------------------------
|
|
471
|
+
/**
|
|
472
|
+
* Two present `removed` facts are equal (SC-R1): the same set of (`leafIndex`, `leafKey`) pairs. Order and duplicates
|
|
473
|
+
* are ignored, so copies that differ only there merge; I1 (ascending, no duplicates) stays the producer contract.
|
|
474
|
+
*/
|
|
475
|
+
function sameRemoved(a, b) {
|
|
476
|
+
const pairs = (facts) => new Set(facts.map((leaf) => `${leaf.leafIndex}\u0000${leaf.leafKey}`));
|
|
477
|
+
const left = pairs(a);
|
|
478
|
+
const right = pairs(b);
|
|
479
|
+
return left.size === right.size && [...left].every((p) => right.has(p));
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* Seam (`removalFinality`): every node of `T` with at least two child edges, ordered by (depth, node id) — the
|
|
483
|
+
* structural phase 1 of ADR-017 (architecture.md SC-R3). `[]` exactly when `T` cannot be built (nothing eligible
|
|
484
|
+
* included, or two present `removed` facts of one edge differ) or no node branches; a node with one child edge is
|
|
485
|
+
* never a rule node, and a tip at a node competes there as a zero-length entry. Shells call {@link phaseOneNodesOf}.
|
|
486
|
+
*/
|
|
487
|
+
export function branchingNodesOf(currentTipEpoch, candidates, policy) {
|
|
488
|
+
const tree = candidateTreeOf(currentTipEpoch, candidates, policy, true);
|
|
489
|
+
if (tree === undefined)
|
|
490
|
+
return [];
|
|
491
|
+
return [...tree.children]
|
|
492
|
+
.filter(([, childIds]) => childIds.length >= 2)
|
|
493
|
+
.map(([nodeId]) => ({ nodeId }))
|
|
494
|
+
.sort((a, b) => cmpNum(tree.depth.get(a.nodeId), tree.depth.get(b.nodeId)) ||
|
|
495
|
+
(a.nodeId < b.nodeId ? -1 : a.nodeId > b.nodeId ? 1 : 0));
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Seam (`removalFinality`): the only phase-1 entry point for shells (architecture.md SC-R3): with the seam effective
|
|
499
|
+
* the structural {@link branchingNodesOf}, else ADR-016's {@link equivocationNodesOf}. Empty means "call the
|
|
500
|
+
* 3-argument {@link selectCanonicalBranch}" in both cases.
|
|
501
|
+
*/
|
|
502
|
+
export function phaseOneNodesOf(effective, currentTipEpoch, candidates, policy) {
|
|
503
|
+
return effective
|
|
504
|
+
? branchingNodesOf(currentTipEpoch, candidates, policy)
|
|
505
|
+
: equivocationNodesOf(currentTipEpoch, candidates, policy);
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* The regime of `nodeId` for the rule, or `undefined` when R-6 (b) or (c) fails: `ctx(N)` is absent, or an anchored
|
|
509
|
+
* sender lacks membership or account there. Reads context presence and the anchored senders directly
|
|
510
|
+
* (architecture.md Implementation Constraint 0): `resolveNode` is also `undefined` when nothing is anchored, and a
|
|
511
|
+
* rule node with no anchoring is valid. `forced` is {@link resolveNode}'s; a forced edge always qualifies, so an
|
|
512
|
+
* unresolvable node has a visible key-checked anchored sender.
|
|
513
|
+
*/
|
|
514
|
+
function ruleRegimeOf(tree, nodeId, credit, forced) {
|
|
515
|
+
const context = credit.nodes.get(nodeId);
|
|
516
|
+
if (context === undefined)
|
|
517
|
+
return undefined;
|
|
518
|
+
const node = resolveNode(tree, nodeId, credit, forced);
|
|
519
|
+
if (node !== undefined)
|
|
520
|
+
return { anchored: node.anchored, context };
|
|
521
|
+
const visible = anchoredChildrenAt(tree, nodeId, (edge, direct) => {
|
|
522
|
+
if (direct)
|
|
523
|
+
return true;
|
|
524
|
+
const key = context.members.get(edge.senderLeafIndex);
|
|
525
|
+
return (key !== undefined &&
|
|
526
|
+
credit.senderKeys.get(bytesToHex(edge.commitDigest)) === key);
|
|
527
|
+
});
|
|
528
|
+
return visible.size === 0 ? { anchored: new Map(), context } : undefined;
|
|
529
|
+
}
|
|
530
|
+
/** The merged tree edges from the root to `nodeId`, root→node. */
|
|
531
|
+
function treePathTo(tree, nodeId) {
|
|
532
|
+
const out = [];
|
|
533
|
+
for (let id = nodeId; id !== tree.rootId;) {
|
|
534
|
+
const edge = tree.edgeTo.get(id);
|
|
535
|
+
out.push(edge);
|
|
536
|
+
id = edge.parentId;
|
|
537
|
+
}
|
|
538
|
+
return out.reverse();
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Seam (`removalFinality`), ADR-017 R-3: the credited-lineage walk, one step per edge of `path` from the child edge
|
|
542
|
+
* leaving `nodeId` to the end (`[]` when `path` does not leave the node). It is `creditAt`'s walk, implemented once
|
|
543
|
+
* more without editing `creditAt`: an edge is credited iff its sender is defined, outside `Excl(N, e)`, a member at
|
|
544
|
+
* `N`, and the edge is signed under the sender's lineage key; the lineage moves only on a credited edge carrying a
|
|
545
|
+
* `commit`-source succession of its own sender away from that key. A property pins that `creditAt` equals the number
|
|
546
|
+
* of credited steps. The walk depends only on the path prefix, so every candidate through an edge agrees.
|
|
547
|
+
*/
|
|
548
|
+
function creditedKeyAt(nodeId, path, regime, credit) {
|
|
549
|
+
const from = path.findIndex((edge) => edge.parentId === nodeId);
|
|
550
|
+
if (from < 0)
|
|
551
|
+
return [];
|
|
552
|
+
const excluded = regime.anchored.get(path[from].childId);
|
|
553
|
+
const held = new Map();
|
|
554
|
+
const steps = [];
|
|
555
|
+
for (let i = from; i < path.length; i++) {
|
|
556
|
+
const keys = new Map(held);
|
|
557
|
+
const sender = path[i].senderLeafIndex;
|
|
558
|
+
const nodeKey = sender === undefined || sender === excluded
|
|
559
|
+
? undefined
|
|
560
|
+
: regime.context.members.get(sender);
|
|
561
|
+
const key = nodeKey === undefined ? undefined : (held.get(sender) ?? nodeKey);
|
|
562
|
+
const digest = bytesToHex(path[i].commitDigest);
|
|
563
|
+
const credited = key !== undefined && credit.senderKeys.get(digest) === key;
|
|
564
|
+
if (credited) {
|
|
565
|
+
const next = credit.successions
|
|
566
|
+
?.get(digest)
|
|
567
|
+
?.find((s) => s.source === "commit" &&
|
|
568
|
+
s.leafIndex === sender &&
|
|
569
|
+
s.fromKey === key &&
|
|
570
|
+
s.toKey !== key)?.toKey;
|
|
571
|
+
if (next !== undefined)
|
|
572
|
+
held.set(sender, next);
|
|
573
|
+
}
|
|
574
|
+
steps.push({ credited, keys });
|
|
575
|
+
}
|
|
576
|
+
return steps;
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* `Rm`, inertness and the preference at `nodeId` (ADR-017 R-3 to R-5, R-7). A removal edge `x ∈ sub(e)` is inert
|
|
580
|
+
* iff its author is `Excl(N, e)`'s leaf (R-4, subtree-local); a fact `(s, K')` of a non-inert `x` counts iff `s` is a
|
|
581
|
+
* member at `N` and `K'` is `s`'s lineage key where the walk reaches `x` (R-3). Reads only the merged tree entries
|
|
582
|
+
* (SC-R1 I6); an absent fact counts nothing.
|
|
583
|
+
*/
|
|
584
|
+
function removalFactsAt(tree, nodeId, credit, regime) {
|
|
585
|
+
const counts = (leaf, lineage) => {
|
|
586
|
+
const nodeKey = regime.context.members.get(leaf.leafIndex);
|
|
587
|
+
return (nodeKey !== undefined &&
|
|
588
|
+
leaf.leafKey === (lineage.get(leaf.leafIndex) ?? nodeKey));
|
|
589
|
+
};
|
|
590
|
+
const rem = new Map();
|
|
591
|
+
const preferred = new Set();
|
|
592
|
+
for (const { direct, edges } of childSubtreesOf(tree, nodeId)) {
|
|
593
|
+
const excluded = regime.anchored.get(direct.childId);
|
|
594
|
+
const removes = new Set();
|
|
595
|
+
for (const x of edges) {
|
|
596
|
+
if (x.removed === undefined)
|
|
597
|
+
continue;
|
|
598
|
+
if (x.senderLeafIndex !== undefined && x.senderLeafIndex === excluded)
|
|
599
|
+
continue;
|
|
600
|
+
const walk = creditedKeyAt(nodeId, treePathTo(tree, x.childId), regime, credit);
|
|
601
|
+
const lineage = walk[walk.length - 1].keys;
|
|
602
|
+
for (const leaf of x.removed)
|
|
603
|
+
if (counts(leaf, lineage))
|
|
604
|
+
removes.add(leaf.leafIndex);
|
|
605
|
+
}
|
|
606
|
+
rem.set(direct.childId, removes);
|
|
607
|
+
}
|
|
608
|
+
const union = new Set([...rem.values()].flatMap((s) => [...s]));
|
|
609
|
+
for (const { direct } of childSubtreesOf(tree, nodeId)) {
|
|
610
|
+
const author = direct.senderLeafIndex;
|
|
611
|
+
if (author !== undefined &&
|
|
612
|
+
!regime.anchored.has(direct.childId) &&
|
|
613
|
+
!union.has(author) &&
|
|
614
|
+
direct.removed?.some((leaf) => counts(leaf, new Map())) === true)
|
|
615
|
+
preferred.add(direct.childId);
|
|
616
|
+
}
|
|
617
|
+
return { regime, credit, rem, union, preferred };
|
|
618
|
+
}
|
|
619
|
+
/** `Rm(N, e)`: the union of `rem_N(e')` over the sibling child edges `e' ≠ e`. */
|
|
620
|
+
function rmOf(facts, childId) {
|
|
621
|
+
const out = new Set();
|
|
622
|
+
for (const [id, removes] of facts.rem)
|
|
623
|
+
if (id !== childId)
|
|
624
|
+
for (const s of removes)
|
|
625
|
+
out.add(s);
|
|
626
|
+
return out;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* ADR-017 R-6 (e), the node-local guard: every candidate through `nodeId` (tips in `sub(N)` and at `N`), except
|
|
630
|
+
* `exempt`, has `tipEpoch - epoch(N) <= maxRewindCommits`. A function of the tips below `N` only.
|
|
631
|
+
*/
|
|
632
|
+
function guardHoldsAt(tree, nodeId, policy, exempt) {
|
|
633
|
+
const epoch = tree.forkEpoch + tree.depth.get(nodeId);
|
|
634
|
+
const within = (id) => (tree.tipsAt.get(id) ?? []).every(({ candidate }) => candidate === exempt ||
|
|
635
|
+
candidate.tipEpoch - epoch <= policy.maxRewindCommits) && (tree.children.get(id) ?? []).every(within);
|
|
636
|
+
return within(nodeId);
|
|
637
|
+
}
|
|
638
|
+
/**
|
|
639
|
+
* Seam (`removalFinality`), ADR-017 R-6: the removal facts of `nodeId` if it is a rule node under `regime`, else
|
|
640
|
+
* `undefined` (the node then resolves as ADR-016). (a) two or more child edges; (b), (c) `regime` exists
|
|
641
|
+
* ({@link ruleRegimeOf}); (d) `⋃Rm(N, ·)` is non-empty; (e) the guard, over every candidate but `exempt`.
|
|
642
|
+
*/
|
|
643
|
+
function removalNodeOf(tree, nodeId, credit, regime, policy, exempt) {
|
|
644
|
+
if ((tree.children.get(nodeId) ?? []).length < 2)
|
|
645
|
+
return undefined;
|
|
646
|
+
const facts = removalFactsAt(tree, nodeId, credit, regime);
|
|
647
|
+
if (facts.union.size === 0)
|
|
648
|
+
return undefined;
|
|
649
|
+
if (!guardHoldsAt(tree, nodeId, policy, exempt))
|
|
650
|
+
return undefined;
|
|
651
|
+
return facts;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Seam (`removalFinality`), ADR-017 R-5: `finality_N(entry)`, the edges of its path from the child edge `e` leaving
|
|
655
|
+
* `nodeId` to its tip that `creditAt` credits at `N` and whose author is not in `Rm(N, e)`. A tip at `N` earns 0;
|
|
656
|
+
* `finality_N <= credit_N` by construction.
|
|
657
|
+
*/
|
|
658
|
+
function finalityAt(nodeId, entry, facts) {
|
|
659
|
+
const path = entry.candidate.path;
|
|
660
|
+
const steps = creditedKeyAt(nodeId, path, facts.regime, facts.credit);
|
|
661
|
+
if (steps.length === 0)
|
|
662
|
+
return 0;
|
|
663
|
+
const from = path.length - steps.length;
|
|
664
|
+
const rm = rmOf(facts, path[from].childId);
|
|
665
|
+
return steps.filter((step, i) => step.credited && !rm.has(path[from + i].senderLeafIndex)).length;
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Seam (`removalFinality`), ADR-017 R-7: the representative at rule node `nodeId` over `entries` (its children's
|
|
669
|
+
* representatives and the tips at it), with `extra` added to an entry's finality (the fence's hidden-credit bound):
|
|
670
|
+
* maximal `finality_N`; then, if some kept entry's child edge is preferred, only those; then `maxOf` (today's
|
|
671
|
+
* `legacyMax` in input order). The one rule function of selection and of the fence's cascade.
|
|
672
|
+
*/
|
|
673
|
+
function ruleKeptAt(nodeId, entries, facts, extra, maxOf) {
|
|
674
|
+
const finality = entries.map((entry) => finalityAt(nodeId, entry, facts) + (extra.get(entry) ?? 0));
|
|
675
|
+
const top = Math.max(...finality);
|
|
676
|
+
const kept = entries.filter((_, i) => finality[i] === top);
|
|
677
|
+
const preferred = kept.filter((entry) => {
|
|
678
|
+
const direct = entry.candidate.path.find((e) => e.parentId === nodeId);
|
|
679
|
+
return direct !== undefined && facts.preferred.has(direct.childId);
|
|
680
|
+
});
|
|
681
|
+
return maxOf(preferred.length > 0 ? preferred : kept);
|
|
682
|
+
}
|
|
683
|
+
let removalTraceSink;
|
|
684
|
+
/**
|
|
685
|
+
* Seam (`removalFinality`) test seam: runs `run` and hands `sink` the per-node outcome of every flagged
|
|
686
|
+
* {@link selectCanonicalBranchCredited} call made inside it. Synchronous and scoped; no production caller sets a
|
|
687
|
+
* sink, and no result ever depends on one.
|
|
688
|
+
* @internal
|
|
689
|
+
*/
|
|
690
|
+
export function traceRemovalFinality(sink, run) {
|
|
691
|
+
const previous = removalTraceSink;
|
|
692
|
+
removalTraceSink = sink;
|
|
693
|
+
try {
|
|
694
|
+
return run();
|
|
695
|
+
}
|
|
696
|
+
finally {
|
|
697
|
+
removalTraceSink = previous;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Seam (`removalFinality`) test seam: what the rule sees at `nodeId` of the flagged candidate tree under its visible
|
|
702
|
+
* regime — the rule-node verdict, the guard, `⋃Rm`, `Rm(N, e)`, the preferred edges and, per eligible candidate
|
|
703
|
+
* through the node, `creditAt`, the number of steps the R-3 walk credits and `finality_N`. `undefined` when the tree
|
|
704
|
+
* cannot be built, the node is not in it, or R-6 (b) / (c) fails there.
|
|
705
|
+
* @internal
|
|
706
|
+
*/
|
|
707
|
+
export function removalFinalityProbeOf(currentTipEpoch, candidates, policy, credit, nodeId) {
|
|
708
|
+
const tree = candidateTreeOf(currentTipEpoch, candidates, policy, true);
|
|
709
|
+
if (tree === undefined || !tree.depth.has(nodeId))
|
|
710
|
+
return undefined;
|
|
711
|
+
const regime = ruleRegimeOf(tree, nodeId, credit);
|
|
712
|
+
if (regime === undefined)
|
|
713
|
+
return undefined;
|
|
714
|
+
const facts = removalFactsAt(tree, nodeId, credit, regime);
|
|
715
|
+
const childIds = tree.children.get(nodeId) ?? [];
|
|
716
|
+
const through = [];
|
|
717
|
+
candidates.forEach((candidate, index) => {
|
|
718
|
+
if (!isBranchEligible(currentTipEpoch, candidate, policy))
|
|
719
|
+
return;
|
|
720
|
+
const path = candidate.path ?? [];
|
|
721
|
+
if (path.some((e) => e.parentId === nodeId || e.childId === nodeId))
|
|
722
|
+
through.push({ candidate, index });
|
|
723
|
+
});
|
|
724
|
+
return {
|
|
725
|
+
ruleNode: removalNodeOf(tree, nodeId, credit, regime, policy) !== undefined,
|
|
726
|
+
guard: guardHoldsAt(tree, nodeId, policy),
|
|
727
|
+
union: [...facts.union].sort(cmpNum),
|
|
728
|
+
rm: new Map(childIds.map((id) => [id, [...rmOf(facts, id)].sort(cmpNum)])),
|
|
729
|
+
preferred: [...facts.preferred].sort(),
|
|
730
|
+
entries: through.map((entry) => ({
|
|
731
|
+
candidate: entry.candidate,
|
|
732
|
+
credit: creditAt(nodeId, entry, regime.anchored, regime.context, credit.senderKeys, credit.successions),
|
|
733
|
+
walkCredited: creditedKeyAt(nodeId, entry.candidate.path, regime, credit).filter((s) => s.credited).length,
|
|
734
|
+
finality: finalityAt(nodeId, entry, facts),
|
|
735
|
+
})),
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Seam (`equivocationCredit`), phase 2: canonical selection with other-leaf
|
|
740
|
+
* credited depth at equivocation nodes (ADR-016 D1–D3, architecture.md SC-3).
|
|
741
|
+
*
|
|
742
|
+
* Global fallback (rule 3a) — the unmodified 3-argument
|
|
743
|
+
* {@link selectCanonicalBranch} over `candidates` (`legacyMax`), with an empty
|
|
744
|
+
* report — whenever {@link equivocationNodesOf} is empty (its doc lists every
|
|
745
|
+
* structural trigger), and likewise when no candidate node is resolvable.
|
|
746
|
+
* Per-node fallback (rule 3b): a candidate node that `credit` lacks, with no
|
|
747
|
+
* anchored child edge after the key clause (`Eq(N)` empty), or where an index
|
|
748
|
+
* of `Eq(N)` lacks membership or account, is resolved by today's ordering and
|
|
749
|
+
* reports nothing; resolvable nodes elsewhere keep credit. Otherwise `T` is
|
|
750
|
+
* resolved bottom-up: a node's representative is `legacyMax` over its
|
|
751
|
+
* children's representatives (and any candidate whose tip is the node) in input
|
|
752
|
+
* order; at a resolvable equivocation node only the representatives with
|
|
753
|
+
* maximal credit compete, so a credit tie keeps today's ordering. Credit is
|
|
754
|
+
* head-anchored (rule 2): a leaf heading a child subtree of the node while
|
|
755
|
+
* also committing in another earns nothing inside the subtree it heads, but
|
|
756
|
+
* its commits deep in a subtree headed by another leaf earn as any other's. Only direct equivocations (`EqDirect`, two child
|
|
757
|
+
* edges of one node by one leaf) are reported; cross-subtree-only evidence
|
|
758
|
+
* feeds credit but is never reported (AC-FLAG-3, AR-8). `decidedByCredit`:
|
|
759
|
+
* credit changed the local outcome at a resolvable node on the winner's path.
|
|
760
|
+
* Pure, total and deterministic: `winner` is `undefined` exactly when no
|
|
761
|
+
* candidate is eligible.
|
|
762
|
+
*
|
|
763
|
+
* Seam (`removalFinality`, ADR-017): with `credit.removalFinality`, `T` merges
|
|
764
|
+
* the edges' `removed` facts, and at every rule node (R-6: two or more child
|
|
765
|
+
* edges, a context, an ADR-016-resolvable anchoring, a counting non-inert
|
|
766
|
+
* removal, and the node-local guard) the node's ADR-016 choice is replaced by
|
|
767
|
+
* the rule's ({@link CanonicalSelection.decidedByRemoval} records a change);
|
|
768
|
+
* the 3a fallback then needs no resolvable equivocation node and no rule node.
|
|
769
|
+
* The report and `decidedByCredit` are ADR-016's. Without the flag nothing of
|
|
770
|
+
* this runs and the result has no `decidedByRemoval` key.
|
|
771
|
+
*/
|
|
772
|
+
export function selectCanonicalBranchCredited(currentTipEpoch, candidates, policy, credit) {
|
|
773
|
+
const legacyMax = (xs) => selectCanonicalBranch(currentTipEpoch, [...xs], policy);
|
|
774
|
+
// Seam (`removalFinality`): `decidedByRemoval` exists exactly when the flag does.
|
|
775
|
+
const flagged = credit.removalFinality === true;
|
|
776
|
+
const fallback = () => ({
|
|
777
|
+
winner: legacyMax(candidates),
|
|
778
|
+
equivocations: [],
|
|
779
|
+
decidedByCredit: false,
|
|
780
|
+
...(flagged ? { decidedByRemoval: false } : {}),
|
|
781
|
+
});
|
|
782
|
+
// Rule 3a: byte-identical global fallback.
|
|
783
|
+
const tree = candidateTreeOf(currentTipEpoch, candidates, policy, flagged);
|
|
784
|
+
if (tree === undefined)
|
|
785
|
+
return fallback();
|
|
786
|
+
const resolved = new Map();
|
|
787
|
+
for (const { nodeId } of candidateNodesIn(tree)) {
|
|
788
|
+
const node = resolveNode(tree, nodeId, credit);
|
|
789
|
+
if (node !== undefined)
|
|
790
|
+
resolved.set(nodeId, node);
|
|
791
|
+
}
|
|
792
|
+
// Seam (`removalFinality`): the rule nodes of `T` (ADR-017 R-6), each with its removal facts.
|
|
793
|
+
const ruleNodes = new Map();
|
|
794
|
+
if (flagged)
|
|
795
|
+
for (const [nodeId, childIds] of tree.children) {
|
|
796
|
+
if (childIds.length < 2)
|
|
797
|
+
continue;
|
|
798
|
+
const regime = ruleRegimeOf(tree, nodeId, credit);
|
|
799
|
+
const facts = regime && removalNodeOf(tree, nodeId, credit, regime, policy);
|
|
800
|
+
if (facts)
|
|
801
|
+
ruleNodes.set(nodeId, facts);
|
|
802
|
+
}
|
|
803
|
+
// Rule 3b with no resolvable node anywhere: the maximum of maxima is
|
|
804
|
+
// `legacyMax` itself, returned directly.
|
|
805
|
+
if (resolved.size === 0 && ruleNodes.size === 0)
|
|
806
|
+
return fallback();
|
|
807
|
+
// The maximum of `entries` under today's ordering, ties broken by input
|
|
808
|
+
// order exactly as `legacyMax` breaks them over the full list.
|
|
809
|
+
const maxOf = (entries) => {
|
|
810
|
+
const ordered = [...entries].sort((a, b) => a.index - b.index);
|
|
811
|
+
const best = legacyMax(ordered.map((e) => e.candidate));
|
|
812
|
+
for (let i = ordered.length - 1; i >= 0; i--)
|
|
813
|
+
if (ordered[i].candidate === best)
|
|
814
|
+
return ordered[i];
|
|
815
|
+
return ordered[ordered.length - 1];
|
|
816
|
+
};
|
|
817
|
+
// Seam (`removalFinality`), SC-R5: the node's ADR-016 choice `c` is bound, then mapped to the rule's `r` at a
|
|
818
|
+
// rule node; `r ≠ c` is recorded for `decidedByRemoval`.
|
|
819
|
+
const removalDecidedAt = new Set();
|
|
820
|
+
const ruled = (nodeId, entries, c) => {
|
|
821
|
+
const facts = ruleNodes.get(nodeId);
|
|
822
|
+
const r = facts === undefined ? c : ruleKeptAt(nodeId, entries, facts, new Map(), maxOf);
|
|
823
|
+
if (r.candidate !== c.candidate)
|
|
824
|
+
removalDecidedAt.add(nodeId);
|
|
825
|
+
if (flagged)
|
|
826
|
+
removalTraceSink?.({
|
|
827
|
+
nodeId,
|
|
828
|
+
ruleNode: facts !== undefined,
|
|
829
|
+
m: maxOf(entries).candidate,
|
|
830
|
+
c: c.candidate,
|
|
831
|
+
r: r.candidate,
|
|
832
|
+
});
|
|
833
|
+
return r;
|
|
834
|
+
};
|
|
835
|
+
const decidedAt = new Set();
|
|
836
|
+
const representativeOf = (nodeId) => {
|
|
837
|
+
const entries = [
|
|
838
|
+
...(tree.tipsAt.get(nodeId) ?? []),
|
|
839
|
+
...(tree.children.get(nodeId) ?? []).map(representativeOf),
|
|
840
|
+
];
|
|
841
|
+
const node = resolved.get(nodeId);
|
|
842
|
+
if (node === undefined)
|
|
843
|
+
return ruled(nodeId, entries, maxOf(entries));
|
|
844
|
+
const credits = entries.map((entry) => creditAt(nodeId, entry, node.anchored, node.context, credit.senderKeys, credit.successions));
|
|
845
|
+
const top = Math.max(...credits);
|
|
846
|
+
const kept = maxOf(entries.filter((_, i) => credits[i] === top));
|
|
847
|
+
if (kept.candidate !== maxOf(entries).candidate)
|
|
848
|
+
decidedAt.add(nodeId);
|
|
849
|
+
return ruled(nodeId, entries, kept);
|
|
850
|
+
};
|
|
851
|
+
const winner = representativeOf(tree.rootId).candidate;
|
|
852
|
+
const onWinnerPath = [
|
|
853
|
+
tree.rootId,
|
|
854
|
+
...(winner.path ?? []).map((edge) => edge.childId),
|
|
855
|
+
];
|
|
856
|
+
const equivocations = [];
|
|
857
|
+
for (const [nodeId, node] of resolved)
|
|
858
|
+
for (const [leafIndex, commitDigests] of node.direct)
|
|
859
|
+
equivocations.push({
|
|
860
|
+
nodeTag: nodeId,
|
|
861
|
+
epoch: tree.forkEpoch + tree.depth.get(nodeId),
|
|
862
|
+
leafIndex,
|
|
863
|
+
leafKey: node.context.members.get(leafIndex),
|
|
864
|
+
account: node.context.accounts.get(leafIndex),
|
|
865
|
+
commitDigests,
|
|
866
|
+
});
|
|
867
|
+
equivocations.sort((a, b) => cmpNum(a.epoch, b.epoch) ||
|
|
868
|
+
(a.nodeTag < b.nodeTag ? -1 : a.nodeTag > b.nodeTag ? 1 : 0) ||
|
|
869
|
+
cmpNum(a.leafIndex, b.leafIndex));
|
|
870
|
+
return {
|
|
871
|
+
winner,
|
|
872
|
+
equivocations,
|
|
873
|
+
decidedByCredit: onWinnerPath.some((nodeId) => decidedAt.has(nodeId)),
|
|
874
|
+
...(flagged
|
|
875
|
+
? {
|
|
876
|
+
decidedByRemoval: onWinnerPath.some((nodeId) => removalDecidedAt.has(nodeId)),
|
|
877
|
+
}
|
|
878
|
+
: {}),
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
const isBound = (n) => Number.isSafeInteger(n) && n >= 0;
|
|
882
|
+
/**
|
|
883
|
+
* Seam (`branchAwareFence`): the best case `o*` of an opaque candidate, a
|
|
884
|
+
* single candidate whose path ends at the head edge. Depth bound: its tip
|
|
885
|
+
* epoch is `parentEpoch + 1 + U`. Tiebreak: at `U >= 1` the hidden tip's
|
|
886
|
+
* committer and digest are unknown, so both are the empty (minimal) byte
|
|
887
|
+
* string and lower wins; at `U = 0` the tip is the head edge and its exact
|
|
888
|
+
* digest and committer are used. No witnesses (ADR-015). The credit bound is
|
|
889
|
+
* not a field of the candidate: {@link opaqueCouldWin} adds it in the credit
|
|
890
|
+
* contest. Its `forkEpoch` is `parentEpoch - pathToParent.length`, the epoch
|
|
891
|
+
* of the shared root.
|
|
892
|
+
*/
|
|
893
|
+
export function opaqueBestCase(opaque) {
|
|
894
|
+
const hidden = opaque.hiddenDepthBound >= 1;
|
|
895
|
+
return {
|
|
896
|
+
id: opaque.headEdge.childId,
|
|
897
|
+
forkEpoch: opaque.parentEpoch - opaque.pathToParent.length,
|
|
898
|
+
tipEpoch: opaque.parentEpoch + 1 + opaque.hiddenDepthBound,
|
|
899
|
+
tipDigest: hidden ? new Uint8Array() : opaque.headEdge.commitDigest,
|
|
900
|
+
tipCommitter: hidden
|
|
901
|
+
? new Uint8Array()
|
|
902
|
+
: (opaque.headCommitter ?? new Uint8Array()),
|
|
903
|
+
appWitnesses: [],
|
|
904
|
+
path: [...opaque.pathToParent, opaque.headEdge],
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Seam (`branchAwareFence`): whether the best case `o*` of `opaque` would be
|
|
909
|
+
* the selected branch among `processable` plus `o*` alone — the device fences
|
|
910
|
+
* on the opaque candidate iff this is `true` (or no processable candidate is
|
|
911
|
+
* eligible, which the caller decides). Pure, total and deterministic; reads no
|
|
912
|
+
* witnesses (the processable candidates' `appWitnesses` are ignored: ADR-015)
|
|
913
|
+
* and never anything hidden.
|
|
914
|
+
*
|
|
915
|
+
* `o*` is appended last, so an exact tie goes to the opaque side (LD-4).
|
|
916
|
+
* Without `credit`, or when the candidate tree cannot be built, the contest is
|
|
917
|
+
* today's ordering over the same field. With it, selection is the cascade of
|
|
918
|
+
* {@link selectCanonicalBranchCredited} with three bounds on `o*`:
|
|
919
|
+
*
|
|
920
|
+
* - depth: {@link opaqueBestCase}; credit: at every resolved node on `o*`'s
|
|
921
|
+
* path its visible credit plus `min(H, U)` (hidden edges earn at most 1
|
|
922
|
+
* each). Under `anchored-zero` an own-leaf head anchored at `N` has `H = 0`
|
|
923
|
+
* at `N` and at every node whose toward edge is anchored with the own leaf.
|
|
924
|
+
* - anchoring: hidden edges are evidence (ADR-016 D1), so when `U >= 1` a hidden
|
|
925
|
+
* edge by the sender of a visible child edge `h` at a node on the path
|
|
926
|
+
* anchors `h`: `h`'s sender then earns nothing inside `sub(h)`, and the node
|
|
927
|
+
* resolves by credit. The device cannot see the hidden senders, so at each
|
|
928
|
+
* node on the path (`N` included) the best case takes the better of the
|
|
929
|
+
* node's visible regime and the regime in which every child edge with a
|
|
930
|
+
* member sender, except the one on `o*`'s path, is anchored. The better of
|
|
931
|
+
* the two is needed: anchoring everything also switches a node that nothing
|
|
932
|
+
* anchors from today's ordering (where `o*`'s depth wins) to the credit
|
|
933
|
+
* contest (where it can lose), so a single forced regime is not conservative.
|
|
934
|
+
* The regimes of different nodes are independent, which relaxes "at most `U`
|
|
935
|
+
* distinct senders" (it may be tightened, never loosened). A third regime
|
|
936
|
+
* applies where a child edge is headed by a member without an account (a
|
|
937
|
+
* hidden edge by it anchors that head, and a node anchoring a sender without
|
|
938
|
+
* an account resolves by today's ordering): today's ordering at that node.
|
|
939
|
+
* The override acts in this function only; selection over `processable` is
|
|
940
|
+
* unchanged.
|
|
941
|
+
* - Soundness holds relative to the contexts supplied: a node of the path
|
|
942
|
+
* whose context `credit` lacks resolves by today's ordering, as in selection.
|
|
943
|
+
* The caller supplies a context for the parent of every `pathToParent` edge
|
|
944
|
+
* and for `N`, a sender key for every visible edge's digest (the head edge
|
|
945
|
+
* included), and consistent bounds (`H <= U`).
|
|
946
|
+
*
|
|
947
|
+
* Fails closed (`true`, the fence of today) on a bound that is not a
|
|
948
|
+
* non-negative safe integer and on an unknown policy value. `false` when `o*`
|
|
949
|
+
* is not eligible (the horizon is the one every member applies).
|
|
950
|
+
*
|
|
951
|
+
* Seam (`removalFinality`, ADR-017's fourth site, architecture.md SC-R7): with
|
|
952
|
+
* `credit.removalFinality` the head's merged `removed` fact is read (absent:
|
|
953
|
+
* `true`), every node is decided under the guard regimes — Gr (the rule,
|
|
954
|
+
* through the same rule function as selection, with `o*` at `u_r` hidden
|
|
955
|
+
* edges) and Ga (today's cascade) — combined with the anchoring regimes above,
|
|
956
|
+
* and `options.headEquivocated` anchors the head at `N` in every regime. Hidden
|
|
957
|
+
* edges carry no removal facts.
|
|
958
|
+
*/
|
|
959
|
+
export function opaqueCouldWin(currentTipEpoch, processable, opaque, policy, credit, options = {}) {
|
|
960
|
+
const depthBound = opaque.hiddenDepthBound;
|
|
961
|
+
const creditBound = opaque.hiddenCreditBound;
|
|
962
|
+
const creditPolicy = options.hiddenCreditPolicy ?? "conservative";
|
|
963
|
+
if (!isBound(depthBound) || !isBound(creditBound))
|
|
964
|
+
return true;
|
|
965
|
+
if (creditPolicy !== "conservative" && creditPolicy !== "anchored-zero")
|
|
966
|
+
return true;
|
|
967
|
+
const best = opaqueBestCase(opaque);
|
|
968
|
+
const field = [
|
|
969
|
+
...processable.map((c) => ({ ...c, appWitnesses: [] })),
|
|
970
|
+
best,
|
|
971
|
+
];
|
|
972
|
+
const byToday = () => selectCanonicalBranch(currentTipEpoch, field, policy) === best;
|
|
973
|
+
if (credit === undefined)
|
|
974
|
+
return byToday();
|
|
975
|
+
const flagged = credit.removalFinality === true;
|
|
976
|
+
const tree = candidateTreeOf(currentTipEpoch, field, policy, flagged);
|
|
977
|
+
if (tree === undefined)
|
|
978
|
+
return byToday();
|
|
979
|
+
if (!tree.edgeTo.has(opaque.headEdge.childId))
|
|
980
|
+
return false;
|
|
981
|
+
// Seam (`removalFinality`): unresolvable head facts (R-2 (i)-(iii)) fence.
|
|
982
|
+
if (flagged && tree.edgeTo.get(opaque.headEdge.childId).removed === undefined)
|
|
983
|
+
return true;
|
|
984
|
+
const resolved = new Map();
|
|
985
|
+
for (const nodeId of tree.children.keys()) {
|
|
986
|
+
const node = resolveNode(tree, nodeId, credit);
|
|
987
|
+
if (node !== undefined)
|
|
988
|
+
resolved.set(nodeId, node);
|
|
989
|
+
}
|
|
990
|
+
const parentId = opaque.headEdge.parentId;
|
|
991
|
+
const head = opaque.headEdge;
|
|
992
|
+
// Seam (`removalFinality`), SC-R7: a same-sender sibling head anchors the scored head at `N` in every regime.
|
|
993
|
+
const headForced = flagged && options.headEquivocated === true
|
|
994
|
+
? new Set([head.childId])
|
|
995
|
+
: undefined;
|
|
996
|
+
if (headForced !== undefined) {
|
|
997
|
+
const node = resolveNode(tree, parentId, credit, headForced);
|
|
998
|
+
if (node !== undefined)
|
|
999
|
+
resolved.set(parentId, node);
|
|
1000
|
+
}
|
|
1001
|
+
const ownAnchoredHead = creditPolicy === "anchored-zero" &&
|
|
1002
|
+
head.senderLeafIndex !== undefined &&
|
|
1003
|
+
head.senderLeafIndex === options.ownLeafIndex &&
|
|
1004
|
+
resolved.get(parentId)?.anchored.has(head.childId) === true;
|
|
1005
|
+
const hiddenCredit = Math.min(creditBound, depthBound);
|
|
1006
|
+
// The cascade of `selectCanonicalBranchCredited`, with `extra` added to an
|
|
1007
|
+
// entry's credit and `node` the regime of the node.
|
|
1008
|
+
const maxOf = (entries) => {
|
|
1009
|
+
const ordered = [...entries].sort((a, b) => a.index - b.index);
|
|
1010
|
+
const winner = selectCanonicalBranch(currentTipEpoch, ordered.map((e) => e.candidate), policy);
|
|
1011
|
+
for (let i = ordered.length - 1; i >= 0; i--)
|
|
1012
|
+
if (ordered[i].candidate === winner)
|
|
1013
|
+
return ordered[i];
|
|
1014
|
+
return ordered[ordered.length - 1];
|
|
1015
|
+
};
|
|
1016
|
+
const keptAt = (nodeId, entries, node, extra, rule) => {
|
|
1017
|
+
// Seam (`removalFinality`): at a rule node of the regime, the rule function of selection decides.
|
|
1018
|
+
if (rule !== undefined)
|
|
1019
|
+
return ruleKeptAt(nodeId, entries, rule, extra, maxOf);
|
|
1020
|
+
if (node === undefined)
|
|
1021
|
+
return maxOf(entries);
|
|
1022
|
+
const credits = entries.map((entry) => creditAt(nodeId, entry, node.anchored, node.context, credit.senderKeys, credit.successions) + (extra.get(entry) ?? 0));
|
|
1023
|
+
const top = Math.max(...credits);
|
|
1024
|
+
return maxOf(entries.filter((_, i) => credits[i] === top));
|
|
1025
|
+
};
|
|
1026
|
+
// Seam (`removalFinality`): the rule node at `nodeId` under the anchoring regime `forced` (resolveNode's), its guard
|
|
1027
|
+
// read over every candidate but `exempt`.
|
|
1028
|
+
const ruleAt = (nodeId, forced, exempt) => {
|
|
1029
|
+
const regime = ruleRegimeOf(tree, nodeId, credit, forced);
|
|
1030
|
+
return regime && removalNodeOf(tree, nodeId, credit, regime, policy, exempt);
|
|
1031
|
+
};
|
|
1032
|
+
const representativeOf = (nodeId) => keptAt(nodeId, [
|
|
1033
|
+
...(tree.tipsAt.get(nodeId) ?? []),
|
|
1034
|
+
...(tree.children.get(nodeId) ?? []).map(representativeOf),
|
|
1035
|
+
], resolved.get(nodeId), new Map(), flagged ? ruleAt(nodeId) : undefined);
|
|
1036
|
+
const entry = { candidate: best, index: field.length - 1 };
|
|
1037
|
+
const guardRegimesAt = (nodeId) => {
|
|
1038
|
+
const epoch = tree.forkEpoch + tree.depth.get(nodeId);
|
|
1039
|
+
const ur = Math.min(depthBound, policy.maxRewindCommits + epoch - opaque.parentEpoch - 1);
|
|
1040
|
+
const processable = guardHoldsAt(tree, nodeId, policy, best);
|
|
1041
|
+
const gr = processable && ur >= 0
|
|
1042
|
+
? {
|
|
1043
|
+
candidate: ur === depthBound
|
|
1044
|
+
? best
|
|
1045
|
+
: opaqueBestCase({ ...opaque, hiddenDepthBound: ur }),
|
|
1046
|
+
index: entry.index,
|
|
1047
|
+
}
|
|
1048
|
+
: undefined;
|
|
1049
|
+
return { ga: !processable || depthBound > ur, gr, ur };
|
|
1050
|
+
};
|
|
1051
|
+
const path = best.path;
|
|
1052
|
+
for (let i = path.length - 1; i >= 0; i--) {
|
|
1053
|
+
const nodeId = path[i].parentId;
|
|
1054
|
+
const towardId = path[i].childId;
|
|
1055
|
+
const others = [
|
|
1056
|
+
...(tree.tipsAt.get(nodeId) ?? []),
|
|
1057
|
+
...(tree.children.get(nodeId) ?? [])
|
|
1058
|
+
.filter((childId) => childId !== towardId)
|
|
1059
|
+
.map(representativeOf),
|
|
1060
|
+
];
|
|
1061
|
+
// Seam (`removalFinality`), SC-R7 guard regimes at this node. Gr (the rule): every processable candidate through
|
|
1062
|
+
// the node passes the guard and `u_r = min(U, h + epoch(N) - parentEpoch - 1) >= 0`; `o*` then has `u_r` hidden
|
|
1063
|
+
// edges. Ga (ADR-016, today's cascade): the processable guard fails or `U > u_r`.
|
|
1064
|
+
const guard = flagged ? guardRegimesAt(nodeId) : undefined;
|
|
1065
|
+
// Hidden credit at this node: under anchored-zero, an anchored own-leaf head
|
|
1066
|
+
// zeroes the own leaf's hidden edges only where the node's toward edge is
|
|
1067
|
+
// anchored with the own leaf as sender (always at `N`, D2 rule 2); above `N`
|
|
1068
|
+
// the clone's burst still earns up to `H`. `forced` names the anchoring
|
|
1069
|
+
// regime for the rule (`null`: the account-less regime, today's ordering).
|
|
1070
|
+
const winsUnder = (node, forced) => {
|
|
1071
|
+
const hpol = ownAnchoredHead &&
|
|
1072
|
+
node !== undefined &&
|
|
1073
|
+
node.anchored.get(towardId) === options.ownLeafIndex
|
|
1074
|
+
? 0
|
|
1075
|
+
: hiddenCredit;
|
|
1076
|
+
const wins = (o, extra, rule) => keptAt(nodeId, [...others, o], node, new Map([[o, extra]]), rule)
|
|
1077
|
+
.candidate === o.candidate;
|
|
1078
|
+
if (guard === undefined)
|
|
1079
|
+
return wins(entry, hpol);
|
|
1080
|
+
if (guard.ga && wins(entry, hpol))
|
|
1081
|
+
return true;
|
|
1082
|
+
if (guard.gr === undefined)
|
|
1083
|
+
return false;
|
|
1084
|
+
const rule = forced === null ? undefined : ruleAt(nodeId, forced, best);
|
|
1085
|
+
return wins(guard.gr, Math.min(hpol, guard.ur), rule);
|
|
1086
|
+
};
|
|
1087
|
+
if (winsUnder(resolved.get(nodeId), nodeId === parentId ? headForced : undefined))
|
|
1088
|
+
continue;
|
|
1089
|
+
if (depthBound < 1)
|
|
1090
|
+
return false;
|
|
1091
|
+
const siblingIds = (tree.children.get(nodeId) ?? []).filter((childId) => childId !== towardId);
|
|
1092
|
+
const forcedIds = new Set([
|
|
1093
|
+
...siblingIds,
|
|
1094
|
+
...(nodeId === parentId && headForced !== undefined ? headForced : []),
|
|
1095
|
+
]);
|
|
1096
|
+
const forced = resolveNode(tree, nodeId, credit, forcedIds);
|
|
1097
|
+
if (forced !== undefined && winsUnder(forced, forcedIds))
|
|
1098
|
+
continue;
|
|
1099
|
+
// Third regime: a hidden edge by a member without an account that heads
|
|
1100
|
+
// another child makes the node resolve by today's ordering.
|
|
1101
|
+
const context = credit.nodes.get(nodeId);
|
|
1102
|
+
const accountless = context !== undefined &&
|
|
1103
|
+
siblingIds.some((childId) => {
|
|
1104
|
+
const sender = tree.edgeTo.get(childId)?.senderLeafIndex;
|
|
1105
|
+
return (sender !== undefined &&
|
|
1106
|
+
context.members.has(sender) &&
|
|
1107
|
+
!context.accounts.has(sender));
|
|
1108
|
+
});
|
|
1109
|
+
if (accountless && winsUnder(undefined, null))
|
|
1110
|
+
continue;
|
|
1111
|
+
return false;
|
|
1112
|
+
}
|
|
1113
|
+
return true;
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Seam (`branchAwareFence`): selection over the processable candidates
|
|
1117
|
+
* (credited when `credit` is present, today's otherwise), then each opaque
|
|
1118
|
+
* candidate decided separately against them with {@link opaqueCouldWin}. With
|
|
1119
|
+
* no opaque candidate this is exactly the selection without the entry point.
|
|
1120
|
+
* Test seam: the engine's production sites decide through the shared per-digest
|
|
1121
|
+
* decision (`decideOpaqueDrafts`); this entry point is exported for the
|
|
1122
|
+
* property tests that pin the core against it.
|
|
1123
|
+
* @internal
|
|
1124
|
+
*/
|
|
1125
|
+
export function selectCanonicalBranchWithOpaque(currentTipEpoch, processable, opaque, policy, credit, options = {}) {
|
|
1126
|
+
const selection = credit === undefined
|
|
1127
|
+
? {
|
|
1128
|
+
winner: selectCanonicalBranch(currentTipEpoch, [...processable], policy),
|
|
1129
|
+
equivocations: [],
|
|
1130
|
+
decidedByCredit: false,
|
|
1131
|
+
}
|
|
1132
|
+
: selectCanonicalBranchCredited(currentTipEpoch, processable, policy, credit);
|
|
1133
|
+
return {
|
|
1134
|
+
selection,
|
|
1135
|
+
couldWin: opaque.map((o) => opaqueCouldWin(currentTipEpoch, processable, o, policy, credit, options)),
|
|
1136
|
+
};
|
|
1137
|
+
}
|
|
1138
|
+
/** Computes the `commit_digest`: SHA-256 (32 bytes) of the commit MLS bytes. */
|
|
1139
|
+
export function commitDigest(mlsBytes) {
|
|
1140
|
+
return sha256(mlsBytes);
|
|
1141
|
+
}
|
|
1142
|
+
/**
|
|
1143
|
+
* Compares two commit ordering keys: lower sourceEpoch first, then lower
|
|
1144
|
+
* commitDigest. Negative when `a` orders before `b`. This is for branch choice
|
|
1145
|
+
* only; the stored message id used to mark a losing commit stays separate.
|
|
1146
|
+
*/
|
|
1147
|
+
export function compareCommitOrderingKeys(a, b) {
|
|
1148
|
+
return (cmpNum(a.sourceEpoch, b.sourceEpoch) ||
|
|
1149
|
+
compareBytes(a.commitDigest, b.commitDigest));
|
|
1150
|
+
}
|