@optimystic/db-core 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/src/cohort-topic/membership/verifier.d.ts +8 -0
  2. package/dist/src/cohort-topic/membership/verifier.d.ts.map +1 -1
  3. package/dist/src/cohort-topic/membership/verifier.js +17 -0
  4. package/dist/src/cohort-topic/membership/verifier.js.map +1 -1
  5. package/dist/src/cohort-topic/promotion.d.ts +25 -0
  6. package/dist/src/cohort-topic/promotion.d.ts.map +1 -1
  7. package/dist/src/cohort-topic/promotion.js +58 -11
  8. package/dist/src/cohort-topic/promotion.js.map +1 -1
  9. package/dist/src/cohort-topic/wire/primitives.d.ts +6 -0
  10. package/dist/src/cohort-topic/wire/primitives.d.ts.map +1 -1
  11. package/dist/src/cohort-topic/wire/primitives.js +6 -0
  12. package/dist/src/cohort-topic/wire/primitives.js.map +1 -1
  13. package/dist/src/cohort-topic/wire/types.d.ts +5 -0
  14. package/dist/src/cohort-topic/wire/types.d.ts.map +1 -1
  15. package/dist/src/cohort-topic/wire/validate.d.ts.map +1 -1
  16. package/dist/src/cohort-topic/wire/validate.js +10 -19
  17. package/dist/src/cohort-topic/wire/validate.js.map +1 -1
  18. package/dist/src/collection/collection.d.ts +8 -1
  19. package/dist/src/collection/collection.d.ts.map +1 -1
  20. package/dist/src/collection/collection.js +19 -3
  21. package/dist/src/collection/collection.js.map +1 -1
  22. package/dist/src/matchmaking/wire.d.ts +2 -2
  23. package/dist/src/matchmaking/wire.d.ts.map +1 -1
  24. package/dist/src/matchmaking/wire.js +3 -3
  25. package/dist/src/matchmaking/wire.js.map +1 -1
  26. package/dist/src/network/struct.d.ts +5 -5
  27. package/dist/src/network/struct.d.ts.map +1 -1
  28. package/dist/src/testing/index.d.ts +1 -0
  29. package/dist/src/testing/index.d.ts.map +1 -1
  30. package/dist/src/testing/index.js +1 -0
  31. package/dist/src/testing/index.js.map +1 -1
  32. package/dist/src/testing/refresh-probe.d.ts +31 -0
  33. package/dist/src/testing/refresh-probe.d.ts.map +1 -0
  34. package/dist/src/testing/refresh-probe.js +39 -0
  35. package/dist/src/testing/refresh-probe.js.map +1 -0
  36. package/dist/src/testing/test-transactor.d.ts +58 -5
  37. package/dist/src/testing/test-transactor.d.ts.map +1 -1
  38. package/dist/src/testing/test-transactor.js +87 -4
  39. package/dist/src/testing/test-transactor.js.map +1 -1
  40. package/dist/src/transaction/coordinator.d.ts +90 -6
  41. package/dist/src/transaction/coordinator.d.ts.map +1 -1
  42. package/dist/src/transaction/coordinator.js +311 -90
  43. package/dist/src/transaction/coordinator.js.map +1 -1
  44. package/dist/src/transaction/errors.d.ts +42 -0
  45. package/dist/src/transaction/errors.d.ts.map +1 -1
  46. package/dist/src/transaction/errors.js +50 -0
  47. package/dist/src/transaction/errors.js.map +1 -1
  48. package/dist/src/transaction/index.d.ts +1 -1
  49. package/dist/src/transaction/index.d.ts.map +1 -1
  50. package/dist/src/transaction/index.js +1 -1
  51. package/dist/src/transaction/index.js.map +1 -1
  52. package/dist/src/transaction/session.d.ts +7 -3
  53. package/dist/src/transaction/session.d.ts.map +1 -1
  54. package/dist/src/transaction/session.js +7 -3
  55. package/dist/src/transaction/session.js.map +1 -1
  56. package/dist/src/transaction/transaction.d.ts +12 -2
  57. package/dist/src/transaction/transaction.d.ts.map +1 -1
  58. package/dist/src/transaction/transaction.js.map +1 -1
  59. package/dist/src/transactor/network-transactor.d.ts +1 -1
  60. package/dist/src/transactor/network-transactor.d.ts.map +1 -1
  61. package/dist/src/transactor/network-transactor.js +6 -26
  62. package/dist/src/transactor/network-transactor.js.map +1 -1
  63. package/dist/src/transactor/transactor-source.d.ts +4 -6
  64. package/dist/src/transactor/transactor-source.d.ts.map +1 -1
  65. package/dist/src/transactor/transactor-source.js +4 -6
  66. package/dist/src/transactor/transactor-source.js.map +1 -1
  67. package/dist/src/transform/atomic.d.ts.map +1 -1
  68. package/dist/src/transform/atomic.js +7 -0
  69. package/dist/src/transform/atomic.js.map +1 -1
  70. package/dist/src/transform/base-pins.d.ts +48 -0
  71. package/dist/src/transform/base-pins.d.ts.map +1 -0
  72. package/dist/src/transform/base-pins.js +65 -0
  73. package/dist/src/transform/base-pins.js.map +1 -0
  74. package/dist/src/transform/digest.d.ts +4 -2
  75. package/dist/src/transform/digest.d.ts.map +1 -1
  76. package/dist/src/transform/digest.js +14 -19
  77. package/dist/src/transform/digest.js.map +1 -1
  78. package/dist/src/transform/tracker.d.ts +31 -3
  79. package/dist/src/transform/tracker.d.ts.map +1 -1
  80. package/dist/src/transform/tracker.js +105 -13
  81. package/dist/src/transform/tracker.js.map +1 -1
  82. package/package.json +1 -1
  83. package/src/cohort-topic/membership/verifier.ts +487 -461
  84. package/src/cohort-topic/promotion.ts +86 -14
  85. package/src/cohort-topic/wire/primitives.ts +195 -188
  86. package/src/cohort-topic/wire/types.ts +480 -475
  87. package/src/cohort-topic/wire/validate.ts +504 -512
  88. package/src/collection/collection.ts +19 -3
  89. package/src/matchmaking/wire.ts +605 -603
  90. package/src/network/struct.ts +5 -5
  91. package/src/testing/index.ts +1 -0
  92. package/src/testing/refresh-probe.ts +52 -0
  93. package/src/testing/test-transactor.ts +100 -4
  94. package/src/transaction/coordinator.ts +312 -99
  95. package/src/transaction/errors.ts +141 -91
  96. package/src/transaction/index.ts +1 -1
  97. package/src/transaction/session.ts +7 -3
  98. package/src/transaction/transaction.ts +12 -2
  99. package/src/transactor/network-transactor.ts +1025 -1045
  100. package/src/transactor/transactor-source.ts +170 -172
  101. package/src/transform/atomic.ts +6 -0
  102. package/src/transform/base-pins.ts +83 -0
  103. package/src/transform/digest.ts +14 -19
  104. package/src/transform/tracker.ts +108 -15
@@ -1,512 +1,504 @@
1
- /**
2
- * Cohort-topic substrate — per-message structural validation.
3
- *
4
- * Each validator narrows an already-parsed `unknown` (the output of `JSON.parse` on a decoded
5
- * frame) to a concrete V1 interface, throwing {@link CohortWireError} on any structural defect:
6
- * missing required field, wrong `v`, out-of-enum discriminant, a byte field that does not decode
7
- * as base64url, or an out-of-range numeric. Validators never return partial data — they either
8
- * narrow cleanly or throw.
9
- */
10
-
11
- import { DEFAULT_D_MAX_CAP } from "../dmax.js";
12
- import {
13
- assignDefined,
14
- asObject,
15
- b64urlField,
16
- b64urlFixedLen,
17
- failWire as fail,
18
- optBool,
19
- optFiniteNumber,
20
- optString,
21
- optStringArray,
22
- reqBool,
23
- reqEnum,
24
- reqFiniteNumber,
25
- reqString,
26
- reqStringArray,
27
- requireV1,
28
- } from "./primitives.js";
29
- import type {
30
- ChildLinkRefV1,
31
- ChildLinkReplyV1,
32
- ChildLinkV1,
33
- CohortGossipV1,
34
- CohortTopicSummary,
35
- DemotionNoticeV1,
36
- GossipRecordRefV1,
37
- GossipRecordV1,
38
- MembershipCertV1,
39
- PromotionNoticeV1,
40
- RegisterReplyV1,
41
- RegisterResult,
42
- RegisterV1,
43
- RenewReplyV1,
44
- RenewV1,
45
- SignKind,
46
- SignRequestV1,
47
- SignReplyV1,
48
- TopicTrafficV1,
49
- } from "./types.js";
50
-
51
- // The generic structural-validation primitives (`fail`/`asObject`/`req*`/`opt*`/`b64url*`/`reqEnum`/…)
52
- // live in ./primitives.js and are imported above; only the cohort-topic domain validators and the
53
- // tier-semantics helpers below stay local. `CohortWireError` is re-exported here so existing importers
54
- // of this module (codec, wire/index, matchmaking, reactivity) are unaffected by the move.
55
- export { CohortWireError } from "./primitives.js";
56
-
57
- function tier(value: number, what: string): number {
58
- if (!Number.isInteger(value) || value < 0 || value > 3) {
59
- fail(`${what}: tier must be an integer in 0..3, got ${value}`);
60
- }
61
- return value;
62
- }
63
-
64
- /**
65
- * Validate a `treeTier` (the walk-toward-root start tier `d` a register/redirect targets): an integer in
66
- * `0..DEFAULT_D_MAX_CAP`. `d_max_cap` (60) is the substrate's own ceiling on useful walk depth, so a
67
- * `treeTier` above it cannot correspond to a real walk position. Rejecting here keeps an out-of-range value
68
- * from reaching `addressing.coord()` downstream whose `coordD` throws a raw `RangeError` for a
69
- * non-integer / negative / `> 255` tier, an unclassified crash rather than a clean malformed-frame rejection.
70
- */
71
- function treeTier(value: number, what: string): number {
72
- if (!Number.isInteger(value) || value < 0 || value > DEFAULT_D_MAX_CAP) {
73
- fail(`${what}: treeTier must be an integer in 0..${DEFAULT_D_MAX_CAP}, got ${value}`);
74
- }
75
- return value;
76
- }
77
-
78
- /** Ring-coord / topic-id / epoch byte width (SHA-256 truncated to the ring width). */
79
- const COORD_BYTES = 32;
80
- /** Correlation-id byte width (a 16-byte nonce minted per walk probe / renew). */
81
- const CORRELATION_BYTES = 16;
82
-
83
- const REGISTER_RESULTS: readonly RegisterResult[] = [
84
- "accepted",
85
- "no_state",
86
- "promoted",
87
- "unwilling_member",
88
- "unwilling_cohort",
89
- ];
90
-
91
- export function validateRegisterV1(value: unknown): RegisterV1 {
92
- const what = "RegisterV1";
93
- const obj = asObject(value, what);
94
- requireV1(obj, what);
95
- const out: RegisterV1 = {
96
- v: 1,
97
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
98
- tier: tier(reqFiniteNumber(obj, "tier", what), what),
99
- treeTier: treeTier(reqFiniteNumber(obj, "treeTier", what), what),
100
- participantCoord: b64urlField(reqString(obj, "participantCoord", what), "participantCoord", what),
101
- ttl: reqFiniteNumber(obj, "ttl", what),
102
- timestamp: reqFiniteNumber(obj, "timestamp", what),
103
- correlationId: b64urlFixedLen(reqString(obj, "correlationId", what), "correlationId", CORRELATION_BYTES, what),
104
- signature: b64urlField(reqString(obj, "signature", what), "signature", what),
105
- };
106
- const bootstrap = optBool(obj, "bootstrap", what);
107
- if (bootstrap !== undefined) {
108
- out.bootstrap = bootstrap;
109
- }
110
- const probe = optBool(obj, "probe", what);
111
- if (probe !== undefined) {
112
- out.probe = probe;
113
- }
114
- const followOn = optBool(obj, "followOn", what);
115
- if (followOn !== undefined) {
116
- out.followOn = followOn;
117
- }
118
- // `bootstrap`, `followOn`, and `probe` are pairwise mutually exclusive the walk sets at most one
119
- // (bootstrap only at the tier-0 root re-issue, followOn only at a `treeTier >= 1` redirect target,
120
- // probe never instantiates). A frame that sets more than one is malformed / adversarial.
121
- if ([bootstrap, followOn, probe].filter((flag) => flag === true).length > 1) {
122
- fail(`${what}: at most one of bootstrap, followOn, probe may be set`);
123
- }
124
- // A follow-on is by definition a deeper-than-root growth point, so `treeTier >= 1`. A `followOn: true`
125
- // at the root (treeTier 0) would be a bootstrap, not a follow-on — reject it as malformed.
126
- if (followOn === true && out.treeTier < 1) {
127
- fail(`${what}: followOn requires treeTier >= 1, got ${out.treeTier}`);
128
- }
129
- const appPayload = optString(obj, "appPayload", what);
130
- if (appPayload !== undefined) {
131
- out.appPayload = b64urlField(appPayload, "appPayload", what);
132
- }
133
- // Bootstrap-evidence envelope (base64url; present only on a `bootstrap: true` register). A non-string
134
- // is rejected as malformed; an empty string is treated as absent so it normalizes to the same signed
135
- // image placeholder as a missing field (see `registerSigningPayload`'s `normalizeEvidence`).
136
- const bootstrapEvidence = optString(obj, "bootstrapEvidence", what);
137
- if (bootstrapEvidence !== undefined && bootstrapEvidence !== "") {
138
- out.bootstrapEvidence = b64urlField(bootstrapEvidence, "bootstrapEvidence", what);
139
- }
140
- return out;
141
- }
142
-
143
- function validateTopicTrafficV1(value: unknown): TopicTrafficV1 {
144
- const what = "TopicTrafficV1";
145
- const obj = asObject(value, what);
146
- return {
147
- windowSeconds: reqFiniteNumber(obj, "windowSeconds", what),
148
- arrivalsPerMin: reqFiniteNumber(obj, "arrivalsPerMin", what),
149
- queriesPerMin: reqFiniteNumber(obj, "queriesPerMin", what),
150
- directParticipants: reqFiniteNumber(obj, "directParticipants", what),
151
- childCohortCount: reqFiniteNumber(obj, "childCohortCount", what),
152
- };
153
- }
154
-
155
- export function validateRegisterReplyV1(value: unknown): RegisterReplyV1 {
156
- const what = "RegisterReplyV1";
157
- const obj = asObject(value, what);
158
- requireV1(obj, what);
159
- const out: RegisterReplyV1 = {
160
- v: 1,
161
- result: reqEnum(obj, "result", REGISTER_RESULTS, what),
162
- };
163
- assignDefined(out, "primary", optString(obj, "primary", what));
164
- assignDefined(out, "backups", optStringArray(obj, "backups", what));
165
- const cohortEpoch = optString(obj, "cohortEpoch", what);
166
- if (cohortEpoch !== undefined) {
167
- // NOTE: cohortEpoch is NOT length-pinned though real epochs are a 32-byte SHA-256 — several
168
- // test fixtures (db-core reactivity + db-p2p) feed 1-byte synthetic epochs. Pinning is tracked
169
- // by debt-cohort-topic-pin-cohort-epoch. See b64urlField's note.
170
- out.cohortEpoch = b64urlField(cohortEpoch, "cohortEpoch", what);
171
- }
172
- assignDefined(out, "cohortMembers", optStringArray(obj, "cohortMembers", what));
173
- if (obj["topicTraffic"] !== undefined) {
174
- out.topicTraffic = validateTopicTrafficV1(obj["topicTraffic"]);
175
- }
176
- // NOTE: `targetTier` is range-checked in the walk loop (walk.ts, case "promoted"), not here — an
177
- // out-of-range redirect must surface as a `retry_later` outcome, not a decode-time throw.
178
- assignDefined(out, "targetTier", optFiniteNumber(obj, "targetTier", what));
179
- assignDefined(out, "candidateMembers", optStringArray(obj, "candidateMembers", what));
180
- assignDefined(out, "retryAfterMs", optFiniteNumber(obj, "retryAfterMs", what));
181
- assignDefined(out, "reason", optString(obj, "reason", what));
182
- return out;
183
- }
184
-
185
- export function validateRenewV1(value: unknown): RenewV1 {
186
- const what = "RenewV1";
187
- const obj = asObject(value, what);
188
- requireV1(obj, what);
189
- const out: RenewV1 = {
190
- v: 1,
191
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
192
- participantId: reqString(obj, "participantId", what),
193
- correlationId: b64urlFixedLen(reqString(obj, "correlationId", what), "correlationId", CORRELATION_BYTES, what),
194
- timestamp: reqFiniteNumber(obj, "timestamp", what),
195
- signature: b64urlField(reqString(obj, "signature", what), "signature", what),
196
- };
197
- assignDefined(out, "reattach", optBool(obj, "reattach", what));
198
- assignDefined(out, "withdraw", optBool(obj, "withdraw", what));
199
- return out;
200
- }
201
-
202
- export function validateRenewReplyV1(value: unknown): RenewReplyV1 {
203
- const what = "RenewReplyV1";
204
- const obj = asObject(value, what);
205
- requireV1(obj, what);
206
- const out: RenewReplyV1 = {
207
- v: 1,
208
- result: reqEnum(obj, "result", ["ok", "unknown_registration", "primary_moved", "withdrawn"] as const, what),
209
- };
210
- assignDefined(out, "newPrimary", optString(obj, "newPrimary", what));
211
- assignDefined(out, "newBackups", optStringArray(obj, "newBackups", what));
212
- const cohortEpoch = optString(obj, "cohortEpoch", what);
213
- if (cohortEpoch !== undefined) {
214
- // NOTE: cohortEpoch is NOT length-pinned — see validateRegisterReplyV1's note and
215
- // debt-cohort-topic-pin-cohort-epoch.
216
- out.cohortEpoch = b64urlField(cohortEpoch, "cohortEpoch", what);
217
- }
218
- return out;
219
- }
220
-
221
- export function validatePromotionNoticeV1(value: unknown): PromotionNoticeV1 {
222
- const what = "PromotionNoticeV1";
223
- const obj = asObject(value, what);
224
- requireV1(obj, what);
225
- const fromTier = treeTier(reqFiniteNumber(obj, "fromTier", what), what);
226
- const toTier = treeTier(reqFiniteNumber(obj, "toTier", what), what);
227
- if (toTier !== fromTier + 1) {
228
- fail(`${what}: toTier must equal fromTier + 1, got fromTier=${fromTier} toTier=${toTier}`);
229
- }
230
- return {
231
- v: 1,
232
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
233
- fromTier,
234
- toTier,
235
- cohortCoord: b64urlFixedLen(reqString(obj, "cohortCoord", what), "cohortCoord", COORD_BYTES, what),
236
- effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
237
- thresholdSig: b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what),
238
- signers: reqStringArray(obj, "signers", what),
239
- cohortEpoch: b64urlField(reqString(obj, "cohortEpoch", what), "cohortEpoch", what),
240
- };
241
- }
242
-
243
- export function validateDemotionNoticeV1(value: unknown): DemotionNoticeV1 {
244
- const what = "DemotionNoticeV1";
245
- const obj = asObject(value, what);
246
- requireV1(obj, what);
247
- return {
248
- v: 1,
249
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
250
- tier: treeTier(reqFiniteNumber(obj, "tier", what), what),
251
- parentCohortCoord: b64urlFixedLen(reqString(obj, "parentCohortCoord", what), "parentCohortCoord", COORD_BYTES, what),
252
- cohortCoord: b64urlFixedLen(reqString(obj, "cohortCoord", what), "cohortCoord", COORD_BYTES, what),
253
- effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
254
- thresholdSig: b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what),
255
- signers: reqStringArray(obj, "signers", what),
256
- cohortEpoch: b64urlField(reqString(obj, "cohortEpoch", what), "cohortEpoch", what),
257
- };
258
- }
259
-
260
- /**
261
- * Validate a {@link ChildLinkV1}. Enforces `childTier >= 1` (the root never links), `tier` in 0..3, and
262
- * well-formed base64url on every byte field. The hash-derived fields (`topicId` / `childCohortCoord` /
263
- * `cohortEpoch`) are additionally length-checked to exactly 32 bytes (each is a SHA-256 truncation); the
264
- * `childParticipantCoord` follows the lenient `RegisterV1` convention (base64url only — a participant
265
- * coord is not always 32 raw bytes, e.g. a multihash-encoded peer id in tests). When `minSigs`
266
- * is supplied AND the frame carries a threshold signature (`thresholdSig` non-empty), `signers.length` must
267
- * be `>= minSigs`; a key-less-interim frame carries neither, so that cross-field bound is skipped. `minSigs`
268
- * is optional so a bare structural decode (no quorum context) still narrows the frame.
269
- */
270
- export function validateChildLinkV1(value: unknown, minSigs?: number): ChildLinkV1 {
271
- const what = "ChildLinkV1";
272
- const obj = asObject(value, what);
273
- requireV1(obj, what);
274
- const childTier = reqFiniteNumber(obj, "childTier", what);
275
- if (!Number.isInteger(childTier) || childTier < 1) {
276
- fail(`${what}: childTier must be an integer >= 1, got ${childTier}`);
277
- }
278
- const thresholdSig = b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what);
279
- const signers = reqStringArray(obj, "signers", what).map((s) => b64urlField(s, "signers", what));
280
- if (minSigs !== undefined && thresholdSig.length > 0 && signers.length < minSigs) {
281
- fail(`${what}: a signed child-link needs signers.length >= ${minSigs}, got ${signers.length}`);
282
- }
283
- return {
284
- v: 1,
285
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
286
- childCohortCoord: b64urlFixedLen(reqString(obj, "childCohortCoord", what), "childCohortCoord", COORD_BYTES, what),
287
- childParticipantCoord: b64urlField(reqString(obj, "childParticipantCoord", what), "childParticipantCoord", what),
288
- childTier,
289
- tier: tier(reqFiniteNumber(obj, "tier", what), what),
290
- effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
291
- thresholdSig,
292
- signers,
293
- cohortEpoch: b64urlField(reqString(obj, "cohortEpoch", what), "cohortEpoch", what),
294
- };
295
- }
296
-
297
- /** Validate a {@link ChildLinkReplyV1}: `result` in `linked | rejected`, optional human-readable `reason`. */
298
- export function validateChildLinkReplyV1(value: unknown): ChildLinkReplyV1 {
299
- const what = "ChildLinkReplyV1";
300
- const obj = asObject(value, what);
301
- requireV1(obj, what);
302
- const out: ChildLinkReplyV1 = {
303
- v: 1,
304
- result: reqEnum(obj, "result", ["linked", "rejected"] as const, what),
305
- };
306
- assignDefined(out, "reason", optString(obj, "reason", what));
307
- return out;
308
- }
309
-
310
- function validateCohortTopicSummary(value: unknown): CohortTopicSummary {
311
- const what = "CohortTopicSummary";
312
- const obj = asObject(value, what);
313
- return {
314
- topicId: b64urlField(reqString(obj, "topicId", what), "topicId", what),
315
- tier: tier(reqFiniteNumber(obj, "tier", what), what),
316
- directParticipants: reqFiniteNumber(obj, "directParticipants", what),
317
- arrivalsPerMin: reqFiniteNumber(obj, "arrivalsPerMin", what),
318
- queriesPerMin: reqFiniteNumber(obj, "queriesPerMin", what),
319
- promoted: reqBool(obj, "promoted", what),
320
- childCohortCount: reqFiniteNumber(obj, "childCohortCount", what),
321
- };
322
- }
323
-
324
- function validateGossipRecordV1(value: unknown): GossipRecordV1 {
325
- const what = "GossipRecordV1";
326
- const obj = asObject(value, what);
327
- const out: GossipRecordV1 = {
328
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
329
- participantId: b64urlField(reqString(obj, "participantId", what), "participantId", what),
330
- tier: tier(reqFiniteNumber(obj, "tier", what), what),
331
- primary: b64urlField(reqString(obj, "primary", what), "primary", what),
332
- backups: reqStringArray(obj, "backups", what).map((b) => b64urlField(b, "backups", what)),
333
- attachedAt: reqFiniteNumber(obj, "attachedAt", what),
334
- lastPing: reqFiniteNumber(obj, "lastPing", what),
335
- ttl: reqFiniteNumber(obj, "ttl", what),
336
- };
337
- const appState = optString(obj, "appState", what);
338
- if (appState !== undefined) {
339
- out.appState = b64urlField(appState, "appState", what);
340
- }
341
- return out;
342
- }
343
-
344
- function validateGossipRecordRefV1(value: unknown): GossipRecordRefV1 {
345
- const what = "GossipRecordRefV1";
346
- const obj = asObject(value, what);
347
- return {
348
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
349
- participantId: b64urlField(reqString(obj, "participantId", what), "participantId", what),
350
- lastPing: reqFiniteNumber(obj, "lastPing", what),
351
- };
352
- }
353
-
354
- function validateChildLinkRefV1(value: unknown): ChildLinkRefV1 {
355
- const what = "ChildLinkRefV1";
356
- const obj = asObject(value, what);
357
- return {
358
- topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
359
- childCohortCoord: b64urlField(reqString(obj, "childCohortCoord", what), "childCohortCoord", what),
360
- effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
361
- };
362
- }
363
-
364
- /** `willingnessBits` carries exactly 4 bits (T0..T3) as a single hex nibble. */
365
- const WILLINGNESS_RE = /^[0-9a-fA-F]$/;
366
-
367
- export function validateCohortGossipV1(value: unknown): CohortGossipV1 {
368
- const what = "CohortGossipV1";
369
- const obj = asObject(value, what);
370
- requireV1(obj, what);
371
- const willingnessBits = reqString(obj, "willingnessBits", what);
372
- if (!WILLINGNESS_RE.test(willingnessBits)) {
373
- fail(`${what}: field "willingnessBits" must be a single hex nibble (4 bits)`);
374
- }
375
- const loadBuckets = obj["loadBuckets"];
376
- if (!Array.isArray(loadBuckets) || loadBuckets.length !== 4) {
377
- fail(`${what}: field "loadBuckets" must be an array of length 4`);
378
- }
379
- for (const bucket of loadBuckets) {
380
- if (typeof bucket !== "number" || !Number.isInteger(bucket) || bucket < 0 || bucket > 7) {
381
- fail(`${what}: each loadBuckets entry must be an integer in 0..7`);
382
- }
383
- }
384
- const summaries = obj["topicSummaries"];
385
- if (!Array.isArray(summaries)) {
386
- fail(`${what}: field "topicSummaries" must be an array`);
387
- }
388
- const treeTier = reqFiniteNumber(obj, "treeTier", what);
389
- if (!Number.isInteger(treeTier) || treeTier < 0) {
390
- fail(`${what}: field "treeTier" must be a non-negative integer, got ${treeTier}`);
391
- }
392
- const out: CohortGossipV1 = {
393
- v: 1,
394
- fromMember: reqString(obj, "fromMember", what),
395
- coord: b64urlFixedLen(reqString(obj, "coord", what), "coord", COORD_BYTES, what),
396
- cohortEpoch: b64urlField(reqString(obj, "cohortEpoch", what), "cohortEpoch", what),
397
- treeTier,
398
- willingnessBits,
399
- loadBuckets: loadBuckets as number[],
400
- windowSeconds: reqFiniteNumber(obj, "windowSeconds", what),
401
- topicSummaries: summaries.map(validateCohortTopicSummary),
402
- timestamp: reqFiniteNumber(obj, "timestamp", what),
403
- signature: b64urlField(reqString(obj, "signature", what), "signature", what),
404
- };
405
- const records = obj["records"];
406
- if (records !== undefined) {
407
- if (!Array.isArray(records)) {
408
- fail(`${what}: field "records" must be an array when present`);
409
- }
410
- out.records = records.map(validateGossipRecordV1);
411
- }
412
- const evicted = obj["evicted"];
413
- if (evicted !== undefined) {
414
- if (!Array.isArray(evicted)) {
415
- fail(`${what}: field "evicted" must be an array when present`);
416
- }
417
- out.evicted = evicted.map(validateGossipRecordRefV1);
418
- }
419
- const childLinks = obj["childLinks"];
420
- if (childLinks !== undefined) {
421
- if (!Array.isArray(childLinks)) {
422
- fail(`${what}: field "childLinks" must be an array when present`);
423
- }
424
- out.childLinks = childLinks.map(validateChildLinkRefV1);
425
- }
426
- const childUnlinks = obj["childUnlinks"];
427
- if (childUnlinks !== undefined) {
428
- if (!Array.isArray(childUnlinks)) {
429
- fail(`${what}: field "childUnlinks" must be an array when present`);
430
- }
431
- out.childUnlinks = childUnlinks.map(validateChildLinkRefV1);
432
- }
433
- return out;
434
- }
435
-
436
- const SIGN_KINDS: readonly SignKind[] = ["membership", "promotion", "demotion", "rotation", "childlink"];
437
-
438
- export function validateSignRequestV1(value: unknown): SignRequestV1 {
439
- const what = "SignRequestV1";
440
- const obj = asObject(value, what);
441
- requireV1(obj, what);
442
- return {
443
- v: 1,
444
- kind: reqEnum(obj, "kind", SIGN_KINDS, what),
445
- coord: b64urlFixedLen(reqString(obj, "coord", what), "coord", COORD_BYTES, what),
446
- cohortEpoch: b64urlField(reqString(obj, "cohortEpoch", what), "cohortEpoch", what),
447
- payload: b64urlField(reqString(obj, "payload", what), "payload", what),
448
- };
449
- }
450
-
451
- export function validateSignReplyV1(value: unknown): SignReplyV1 {
452
- const what = "SignReplyV1";
453
- const obj = asObject(value, what);
454
- requireV1(obj, what);
455
- // Discriminated by `refused`: a refusal carries a reason; an endorsement carries signer + signature.
456
- if (obj["refused"] !== undefined) {
457
- if (obj["refused"] !== true) {
458
- fail(`${what}: field "refused" must be true when present`);
459
- }
460
- return { v: 1, refused: true, reason: reqString(obj, "reason", what) };
461
- }
462
- return {
463
- v: 1,
464
- signer: b64urlField(reqString(obj, "signer", what), "signer", what),
465
- signature: b64urlField(reqString(obj, "signature", what), "signature", what),
466
- };
467
- }
468
-
469
- export function validateMembershipCertV1(value: unknown): MembershipCertV1 {
470
- const what = "MembershipCertV1";
471
- const obj = asObject(value, what);
472
- requireV1(obj, what);
473
- const out: MembershipCertV1 = {
474
- v: 1,
475
- cohortCoord: b64urlFixedLen(reqString(obj, "cohortCoord", what), "cohortCoord", COORD_BYTES, what),
476
- cohortEpoch: b64urlField(reqString(obj, "cohortEpoch", what), "cohortEpoch", what),
477
- members: reqStringArray(obj, "members", what),
478
- stabilizedAt: reqFiniteNumber(obj, "stabilizedAt", what),
479
- thresholdSig: b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what),
480
- signers: reqStringArray(obj, "signers", what),
481
- };
482
- const attestation = optString(obj, "fretAttestation", what);
483
- if (attestation !== undefined) {
484
- out.fretAttestation = b64urlField(attestation, "fretAttestation", what);
485
- }
486
- validateRotationAttestation(obj, out, what);
487
- return out;
488
- }
489
-
490
- /**
491
- * Validate the optional rotation attestation as an all-or-nothing group: either all three of
492
- * `prevEpoch`/`rotationSig`/`rotationSigners` are present (and well-formed) or all are absent. A
493
- * partial set is a {@link CohortWireError}. `rotationSigners` is validated only as a string array (its
494
- * elements are decoded per-element later, mirroring `signers`).
495
- */
496
- function validateRotationAttestation(obj: Record<string, unknown>, out: MembershipCertV1, what: string): void {
497
- const prevEpoch = optString(obj, "prevEpoch", what);
498
- const rotationSig = optString(obj, "rotationSig", what);
499
- const rotationSigners = optStringArray(obj, "rotationSigners", what);
500
- const presentCount = [prevEpoch, rotationSig, rotationSigners].filter((v) => v !== undefined).length;
501
- if (presentCount === 0) {
502
- return;
503
- }
504
- if (presentCount !== 3) {
505
- fail(`${what}: rotation attestation requires all of prevEpoch, rotationSig, rotationSigners — or none`);
506
- }
507
- // prevEpoch is a prior cohortEpoch, so it inherits cohortEpoch's leniency (see the b64urlField note
508
- // and debt-cohort-topic-pin-cohort-epoch).
509
- out.prevEpoch = b64urlField(prevEpoch!, "prevEpoch", what);
510
- out.rotationSig = b64urlField(rotationSig!, "rotationSig", what);
511
- out.rotationSigners = rotationSigners!;
512
- }
1
+ /**
2
+ * Cohort-topic substrate — per-message structural validation.
3
+ *
4
+ * Each validator narrows an already-parsed `unknown` (the output of `JSON.parse` on a decoded
5
+ * frame) to a concrete V1 interface, throwing {@link CohortWireError} on any structural defect:
6
+ * missing required field, wrong `v`, out-of-enum discriminant, a byte field that does not decode
7
+ * as base64url, or an out-of-range numeric. Validators never return partial data — they either
8
+ * narrow cleanly or throw.
9
+ */
10
+
11
+ import { DEFAULT_D_MAX_CAP } from "../dmax.js";
12
+ import {
13
+ assignDefined,
14
+ asObject,
15
+ b64urlField,
16
+ b64urlFixedLen,
17
+ COORD_BYTES,
18
+ failWire as fail,
19
+ optBool,
20
+ optFiniteNumber,
21
+ optString,
22
+ optStringArray,
23
+ reqBool,
24
+ reqEnum,
25
+ reqFiniteNumber,
26
+ reqString,
27
+ reqStringArray,
28
+ requireV1,
29
+ } from "./primitives.js";
30
+ import type {
31
+ ChildLinkRefV1,
32
+ ChildLinkReplyV1,
33
+ ChildLinkV1,
34
+ CohortGossipV1,
35
+ CohortTopicSummary,
36
+ DemotionNoticeV1,
37
+ GossipRecordRefV1,
38
+ GossipRecordV1,
39
+ MembershipCertV1,
40
+ PromotionNoticeV1,
41
+ RegisterReplyV1,
42
+ RegisterResult,
43
+ RegisterV1,
44
+ RenewReplyV1,
45
+ RenewV1,
46
+ SignKind,
47
+ SignRequestV1,
48
+ SignReplyV1,
49
+ TopicTrafficV1,
50
+ } from "./types.js";
51
+
52
+ // The generic structural-validation primitives (`fail`/`asObject`/`req*`/`opt*`/`b64url*`/`reqEnum`/…)
53
+ // live in ./primitives.js and are imported above; only the cohort-topic domain validators and the
54
+ // tier-semantics helpers below stay local. `CohortWireError` is re-exported here so existing importers
55
+ // of this module (codec, wire/index, matchmaking, reactivity) are unaffected by the move.
56
+ export { CohortWireError } from "./primitives.js";
57
+
58
+ function tier(value: number, what: string): number {
59
+ if (!Number.isInteger(value) || value < 0 || value > 3) {
60
+ fail(`${what}: tier must be an integer in 0..3, got ${value}`);
61
+ }
62
+ return value;
63
+ }
64
+
65
+ /**
66
+ * Validate a `treeTier` (the walk-toward-root start tier `d` a register/redirect targets): an integer in
67
+ * `0..DEFAULT_D_MAX_CAP`. `d_max_cap` (60) is the substrate's own ceiling on useful walk depth, so a
68
+ * `treeTier` above it cannot correspond to a real walk position. Rejecting here keeps an out-of-range value
69
+ * from reaching `addressing.coord()` downstream whose `coordD` throws a raw `RangeError` for a
70
+ * non-integer / negative / `> 255` tier, an unclassified crash rather than a clean malformed-frame rejection.
71
+ */
72
+ function treeTier(value: number, what: string): number {
73
+ if (!Number.isInteger(value) || value < 0 || value > DEFAULT_D_MAX_CAP) {
74
+ fail(`${what}: treeTier must be an integer in 0..${DEFAULT_D_MAX_CAP}, got ${value}`);
75
+ }
76
+ return value;
77
+ }
78
+
79
+ /** Correlation-id byte width (a 16-byte nonce minted per walk probe / renew). */
80
+ const CORRELATION_BYTES = 16;
81
+
82
+ const REGISTER_RESULTS: readonly RegisterResult[] = [
83
+ "accepted",
84
+ "no_state",
85
+ "promoted",
86
+ "unwilling_member",
87
+ "unwilling_cohort",
88
+ ];
89
+
90
+ export function validateRegisterV1(value: unknown): RegisterV1 {
91
+ const what = "RegisterV1";
92
+ const obj = asObject(value, what);
93
+ requireV1(obj, what);
94
+ const out: RegisterV1 = {
95
+ v: 1,
96
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
97
+ tier: tier(reqFiniteNumber(obj, "tier", what), what),
98
+ treeTier: treeTier(reqFiniteNumber(obj, "treeTier", what), what),
99
+ participantCoord: b64urlField(reqString(obj, "participantCoord", what), "participantCoord", what),
100
+ ttl: reqFiniteNumber(obj, "ttl", what),
101
+ timestamp: reqFiniteNumber(obj, "timestamp", what),
102
+ correlationId: b64urlFixedLen(reqString(obj, "correlationId", what), "correlationId", CORRELATION_BYTES, what),
103
+ signature: b64urlField(reqString(obj, "signature", what), "signature", what),
104
+ };
105
+ const bootstrap = optBool(obj, "bootstrap", what);
106
+ if (bootstrap !== undefined) {
107
+ out.bootstrap = bootstrap;
108
+ }
109
+ const probe = optBool(obj, "probe", what);
110
+ if (probe !== undefined) {
111
+ out.probe = probe;
112
+ }
113
+ const followOn = optBool(obj, "followOn", what);
114
+ if (followOn !== undefined) {
115
+ out.followOn = followOn;
116
+ }
117
+ // `bootstrap`, `followOn`, and `probe` are pairwise mutually exclusive — the walk sets at most one
118
+ // (bootstrap only at the tier-0 root re-issue, followOn only at a `treeTier >= 1` redirect target,
119
+ // probe never instantiates). A frame that sets more than one is malformed / adversarial.
120
+ if ([bootstrap, followOn, probe].filter((flag) => flag === true).length > 1) {
121
+ fail(`${what}: at most one of bootstrap, followOn, probe may be set`);
122
+ }
123
+ // A follow-on is by definition a deeper-than-root growth point, so `treeTier >= 1`. A `followOn: true`
124
+ // at the root (treeTier 0) would be a bootstrap, not a follow-on reject it as malformed.
125
+ if (followOn === true && out.treeTier < 1) {
126
+ fail(`${what}: followOn requires treeTier >= 1, got ${out.treeTier}`);
127
+ }
128
+ const appPayload = optString(obj, "appPayload", what);
129
+ if (appPayload !== undefined) {
130
+ out.appPayload = b64urlField(appPayload, "appPayload", what);
131
+ }
132
+ // Bootstrap-evidence envelope (base64url; present only on a `bootstrap: true` register). A non-string
133
+ // is rejected as malformed; an empty string is treated as absent so it normalizes to the same signed
134
+ // image placeholder as a missing field (see `registerSigningPayload`'s `normalizeEvidence`).
135
+ const bootstrapEvidence = optString(obj, "bootstrapEvidence", what);
136
+ if (bootstrapEvidence !== undefined && bootstrapEvidence !== "") {
137
+ out.bootstrapEvidence = b64urlField(bootstrapEvidence, "bootstrapEvidence", what);
138
+ }
139
+ return out;
140
+ }
141
+
142
+ function validateTopicTrafficV1(value: unknown): TopicTrafficV1 {
143
+ const what = "TopicTrafficV1";
144
+ const obj = asObject(value, what);
145
+ return {
146
+ windowSeconds: reqFiniteNumber(obj, "windowSeconds", what),
147
+ arrivalsPerMin: reqFiniteNumber(obj, "arrivalsPerMin", what),
148
+ queriesPerMin: reqFiniteNumber(obj, "queriesPerMin", what),
149
+ directParticipants: reqFiniteNumber(obj, "directParticipants", what),
150
+ childCohortCount: reqFiniteNumber(obj, "childCohortCount", what),
151
+ };
152
+ }
153
+
154
+ export function validateRegisterReplyV1(value: unknown): RegisterReplyV1 {
155
+ const what = "RegisterReplyV1";
156
+ const obj = asObject(value, what);
157
+ requireV1(obj, what);
158
+ const out: RegisterReplyV1 = {
159
+ v: 1,
160
+ result: reqEnum(obj, "result", REGISTER_RESULTS, what),
161
+ };
162
+ assignDefined(out, "primary", optString(obj, "primary", what));
163
+ assignDefined(out, "backups", optStringArray(obj, "backups", what));
164
+ const cohortEpoch = optString(obj, "cohortEpoch", what);
165
+ if (cohortEpoch !== undefined) {
166
+ out.cohortEpoch = b64urlFixedLen(cohortEpoch, "cohortEpoch", COORD_BYTES, what);
167
+ }
168
+ assignDefined(out, "cohortMembers", optStringArray(obj, "cohortMembers", what));
169
+ if (obj["topicTraffic"] !== undefined) {
170
+ out.topicTraffic = validateTopicTrafficV1(obj["topicTraffic"]);
171
+ }
172
+ // NOTE: `targetTier` is range-checked in the walk loop (walk.ts, case "promoted"), not here — an
173
+ // out-of-range redirect must surface as a `retry_later` outcome, not a decode-time throw.
174
+ assignDefined(out, "targetTier", optFiniteNumber(obj, "targetTier", what));
175
+ assignDefined(out, "candidateMembers", optStringArray(obj, "candidateMembers", what));
176
+ assignDefined(out, "retryAfterMs", optFiniteNumber(obj, "retryAfterMs", what));
177
+ assignDefined(out, "reason", optString(obj, "reason", what));
178
+ return out;
179
+ }
180
+
181
+ export function validateRenewV1(value: unknown): RenewV1 {
182
+ const what = "RenewV1";
183
+ const obj = asObject(value, what);
184
+ requireV1(obj, what);
185
+ const out: RenewV1 = {
186
+ v: 1,
187
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
188
+ participantId: reqString(obj, "participantId", what),
189
+ correlationId: b64urlFixedLen(reqString(obj, "correlationId", what), "correlationId", CORRELATION_BYTES, what),
190
+ timestamp: reqFiniteNumber(obj, "timestamp", what),
191
+ signature: b64urlField(reqString(obj, "signature", what), "signature", what),
192
+ };
193
+ assignDefined(out, "reattach", optBool(obj, "reattach", what));
194
+ assignDefined(out, "withdraw", optBool(obj, "withdraw", what));
195
+ return out;
196
+ }
197
+
198
+ export function validateRenewReplyV1(value: unknown): RenewReplyV1 {
199
+ const what = "RenewReplyV1";
200
+ const obj = asObject(value, what);
201
+ requireV1(obj, what);
202
+ const out: RenewReplyV1 = {
203
+ v: 1,
204
+ result: reqEnum(obj, "result", ["ok", "unknown_registration", "primary_moved", "withdrawn"] as const, what),
205
+ };
206
+ assignDefined(out, "newPrimary", optString(obj, "newPrimary", what));
207
+ assignDefined(out, "newBackups", optStringArray(obj, "newBackups", what));
208
+ const cohortEpoch = optString(obj, "cohortEpoch", what);
209
+ if (cohortEpoch !== undefined) {
210
+ out.cohortEpoch = b64urlFixedLen(cohortEpoch, "cohortEpoch", COORD_BYTES, what);
211
+ }
212
+ return out;
213
+ }
214
+
215
+ export function validatePromotionNoticeV1(value: unknown): PromotionNoticeV1 {
216
+ const what = "PromotionNoticeV1";
217
+ const obj = asObject(value, what);
218
+ requireV1(obj, what);
219
+ const fromTier = treeTier(reqFiniteNumber(obj, "fromTier", what), what);
220
+ const toTier = treeTier(reqFiniteNumber(obj, "toTier", what), what);
221
+ if (toTier !== fromTier + 1) {
222
+ fail(`${what}: toTier must equal fromTier + 1, got fromTier=${fromTier} toTier=${toTier}`);
223
+ }
224
+ return {
225
+ v: 1,
226
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
227
+ fromTier,
228
+ toTier,
229
+ cohortCoord: b64urlFixedLen(reqString(obj, "cohortCoord", what), "cohortCoord", COORD_BYTES, what),
230
+ effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
231
+ thresholdSig: b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what),
232
+ signers: reqStringArray(obj, "signers", what),
233
+ cohortEpoch: b64urlFixedLen(reqString(obj, "cohortEpoch", what), "cohortEpoch", COORD_BYTES, what),
234
+ };
235
+ }
236
+
237
+ export function validateDemotionNoticeV1(value: unknown): DemotionNoticeV1 {
238
+ const what = "DemotionNoticeV1";
239
+ const obj = asObject(value, what);
240
+ requireV1(obj, what);
241
+ return {
242
+ v: 1,
243
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
244
+ tier: treeTier(reqFiniteNumber(obj, "tier", what), what),
245
+ parentCohortCoord: b64urlFixedLen(reqString(obj, "parentCohortCoord", what), "parentCohortCoord", COORD_BYTES, what),
246
+ cohortCoord: b64urlFixedLen(reqString(obj, "cohortCoord", what), "cohortCoord", COORD_BYTES, what),
247
+ effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
248
+ thresholdSig: b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what),
249
+ signers: reqStringArray(obj, "signers", what),
250
+ cohortEpoch: b64urlFixedLen(reqString(obj, "cohortEpoch", what), "cohortEpoch", COORD_BYTES, what),
251
+ };
252
+ }
253
+
254
+ /**
255
+ * Validate a {@link ChildLinkV1}. Enforces `childTier >= 1` (the root never links), `tier` in 0..3, and
256
+ * well-formed base64url on every byte field. The hash-derived fields (`topicId` / `childCohortCoord` /
257
+ * `cohortEpoch`) are additionally length-checked to exactly 32 bytes (each is a SHA-256 truncation); the
258
+ * `childParticipantCoord` follows the lenient `RegisterV1` convention (base64url only — a participant
259
+ * coord is not always 32 raw bytes, e.g. a multihash-encoded peer id in tests). When `minSigs`
260
+ * is supplied AND the frame carries a threshold signature (`thresholdSig` non-empty), `signers.length` must
261
+ * be `>= minSigs`; a key-less-interim frame carries neither, so that cross-field bound is skipped. `minSigs`
262
+ * is optional so a bare structural decode (no quorum context) still narrows the frame.
263
+ */
264
+ export function validateChildLinkV1(value: unknown, minSigs?: number): ChildLinkV1 {
265
+ const what = "ChildLinkV1";
266
+ const obj = asObject(value, what);
267
+ requireV1(obj, what);
268
+ const childTier = reqFiniteNumber(obj, "childTier", what);
269
+ if (!Number.isInteger(childTier) || childTier < 1) {
270
+ fail(`${what}: childTier must be an integer >= 1, got ${childTier}`);
271
+ }
272
+ const thresholdSig = b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what);
273
+ const signers = reqStringArray(obj, "signers", what).map((s) => b64urlField(s, "signers", what));
274
+ if (minSigs !== undefined && thresholdSig.length > 0 && signers.length < minSigs) {
275
+ fail(`${what}: a signed child-link needs signers.length >= ${minSigs}, got ${signers.length}`);
276
+ }
277
+ return {
278
+ v: 1,
279
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
280
+ childCohortCoord: b64urlFixedLen(reqString(obj, "childCohortCoord", what), "childCohortCoord", COORD_BYTES, what),
281
+ childParticipantCoord: b64urlField(reqString(obj, "childParticipantCoord", what), "childParticipantCoord", what),
282
+ childTier,
283
+ tier: tier(reqFiniteNumber(obj, "tier", what), what),
284
+ effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
285
+ thresholdSig,
286
+ signers,
287
+ cohortEpoch: b64urlFixedLen(reqString(obj, "cohortEpoch", what), "cohortEpoch", COORD_BYTES, what),
288
+ };
289
+ }
290
+
291
+ /** Validate a {@link ChildLinkReplyV1}: `result` in `linked | rejected`, optional human-readable `reason`. */
292
+ export function validateChildLinkReplyV1(value: unknown): ChildLinkReplyV1 {
293
+ const what = "ChildLinkReplyV1";
294
+ const obj = asObject(value, what);
295
+ requireV1(obj, what);
296
+ const out: ChildLinkReplyV1 = {
297
+ v: 1,
298
+ result: reqEnum(obj, "result", ["linked", "rejected"] as const, what),
299
+ };
300
+ assignDefined(out, "reason", optString(obj, "reason", what));
301
+ return out;
302
+ }
303
+
304
+ function validateCohortTopicSummary(value: unknown): CohortTopicSummary {
305
+ const what = "CohortTopicSummary";
306
+ const obj = asObject(value, what);
307
+ return {
308
+ topicId: b64urlField(reqString(obj, "topicId", what), "topicId", what),
309
+ tier: tier(reqFiniteNumber(obj, "tier", what), what),
310
+ directParticipants: reqFiniteNumber(obj, "directParticipants", what),
311
+ arrivalsPerMin: reqFiniteNumber(obj, "arrivalsPerMin", what),
312
+ queriesPerMin: reqFiniteNumber(obj, "queriesPerMin", what),
313
+ promoted: reqBool(obj, "promoted", what),
314
+ childCohortCount: reqFiniteNumber(obj, "childCohortCount", what),
315
+ };
316
+ }
317
+
318
+ function validateGossipRecordV1(value: unknown): GossipRecordV1 {
319
+ const what = "GossipRecordV1";
320
+ const obj = asObject(value, what);
321
+ const out: GossipRecordV1 = {
322
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
323
+ participantId: b64urlField(reqString(obj, "participantId", what), "participantId", what),
324
+ tier: tier(reqFiniteNumber(obj, "tier", what), what),
325
+ primary: b64urlField(reqString(obj, "primary", what), "primary", what),
326
+ backups: reqStringArray(obj, "backups", what).map((b) => b64urlField(b, "backups", what)),
327
+ attachedAt: reqFiniteNumber(obj, "attachedAt", what),
328
+ lastPing: reqFiniteNumber(obj, "lastPing", what),
329
+ ttl: reqFiniteNumber(obj, "ttl", what),
330
+ };
331
+ const appState = optString(obj, "appState", what);
332
+ if (appState !== undefined) {
333
+ out.appState = b64urlField(appState, "appState", what);
334
+ }
335
+ return out;
336
+ }
337
+
338
+ function validateGossipRecordRefV1(value: unknown): GossipRecordRefV1 {
339
+ const what = "GossipRecordRefV1";
340
+ const obj = asObject(value, what);
341
+ return {
342
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
343
+ participantId: b64urlField(reqString(obj, "participantId", what), "participantId", what),
344
+ lastPing: reqFiniteNumber(obj, "lastPing", what),
345
+ };
346
+ }
347
+
348
+ function validateChildLinkRefV1(value: unknown): ChildLinkRefV1 {
349
+ const what = "ChildLinkRefV1";
350
+ const obj = asObject(value, what);
351
+ return {
352
+ topicId: b64urlFixedLen(reqString(obj, "topicId", what), "topicId", COORD_BYTES, what),
353
+ childCohortCoord: b64urlField(reqString(obj, "childCohortCoord", what), "childCohortCoord", what),
354
+ effectiveAt: reqFiniteNumber(obj, "effectiveAt", what),
355
+ };
356
+ }
357
+
358
+ /** `willingnessBits` carries exactly 4 bits (T0..T3) as a single hex nibble. */
359
+ const WILLINGNESS_RE = /^[0-9a-fA-F]$/;
360
+
361
+ export function validateCohortGossipV1(value: unknown): CohortGossipV1 {
362
+ const what = "CohortGossipV1";
363
+ const obj = asObject(value, what);
364
+ requireV1(obj, what);
365
+ const willingnessBits = reqString(obj, "willingnessBits", what);
366
+ if (!WILLINGNESS_RE.test(willingnessBits)) {
367
+ fail(`${what}: field "willingnessBits" must be a single hex nibble (4 bits)`);
368
+ }
369
+ const loadBuckets = obj["loadBuckets"];
370
+ if (!Array.isArray(loadBuckets) || loadBuckets.length !== 4) {
371
+ fail(`${what}: field "loadBuckets" must be an array of length 4`);
372
+ }
373
+ for (const bucket of loadBuckets) {
374
+ if (typeof bucket !== "number" || !Number.isInteger(bucket) || bucket < 0 || bucket > 7) {
375
+ fail(`${what}: each loadBuckets entry must be an integer in 0..7`);
376
+ }
377
+ }
378
+ const summaries = obj["topicSummaries"];
379
+ if (!Array.isArray(summaries)) {
380
+ fail(`${what}: field "topicSummaries" must be an array`);
381
+ }
382
+ const treeTier = reqFiniteNumber(obj, "treeTier", what);
383
+ if (!Number.isInteger(treeTier) || treeTier < 0) {
384
+ fail(`${what}: field "treeTier" must be a non-negative integer, got ${treeTier}`);
385
+ }
386
+ const out: CohortGossipV1 = {
387
+ v: 1,
388
+ fromMember: reqString(obj, "fromMember", what),
389
+ coord: b64urlFixedLen(reqString(obj, "coord", what), "coord", COORD_BYTES, what),
390
+ cohortEpoch: b64urlFixedLen(reqString(obj, "cohortEpoch", what), "cohortEpoch", COORD_BYTES, what),
391
+ treeTier,
392
+ willingnessBits,
393
+ loadBuckets: loadBuckets as number[],
394
+ windowSeconds: reqFiniteNumber(obj, "windowSeconds", what),
395
+ topicSummaries: summaries.map(validateCohortTopicSummary),
396
+ timestamp: reqFiniteNumber(obj, "timestamp", what),
397
+ signature: b64urlField(reqString(obj, "signature", what), "signature", what),
398
+ };
399
+ const records = obj["records"];
400
+ if (records !== undefined) {
401
+ if (!Array.isArray(records)) {
402
+ fail(`${what}: field "records" must be an array when present`);
403
+ }
404
+ out.records = records.map(validateGossipRecordV1);
405
+ }
406
+ const evicted = obj["evicted"];
407
+ if (evicted !== undefined) {
408
+ if (!Array.isArray(evicted)) {
409
+ fail(`${what}: field "evicted" must be an array when present`);
410
+ }
411
+ out.evicted = evicted.map(validateGossipRecordRefV1);
412
+ }
413
+ const childLinks = obj["childLinks"];
414
+ if (childLinks !== undefined) {
415
+ if (!Array.isArray(childLinks)) {
416
+ fail(`${what}: field "childLinks" must be an array when present`);
417
+ }
418
+ out.childLinks = childLinks.map(validateChildLinkRefV1);
419
+ }
420
+ const childUnlinks = obj["childUnlinks"];
421
+ if (childUnlinks !== undefined) {
422
+ if (!Array.isArray(childUnlinks)) {
423
+ fail(`${what}: field "childUnlinks" must be an array when present`);
424
+ }
425
+ out.childUnlinks = childUnlinks.map(validateChildLinkRefV1);
426
+ }
427
+ return out;
428
+ }
429
+
430
+ const SIGN_KINDS: readonly SignKind[] = ["membership", "promotion", "demotion", "rotation", "childlink"];
431
+
432
+ export function validateSignRequestV1(value: unknown): SignRequestV1 {
433
+ const what = "SignRequestV1";
434
+ const obj = asObject(value, what);
435
+ requireV1(obj, what);
436
+ return {
437
+ v: 1,
438
+ kind: reqEnum(obj, "kind", SIGN_KINDS, what),
439
+ coord: b64urlFixedLen(reqString(obj, "coord", what), "coord", COORD_BYTES, what),
440
+ cohortEpoch: b64urlFixedLen(reqString(obj, "cohortEpoch", what), "cohortEpoch", COORD_BYTES, what),
441
+ payload: b64urlField(reqString(obj, "payload", what), "payload", what),
442
+ };
443
+ }
444
+
445
+ export function validateSignReplyV1(value: unknown): SignReplyV1 {
446
+ const what = "SignReplyV1";
447
+ const obj = asObject(value, what);
448
+ requireV1(obj, what);
449
+ // Discriminated by `refused`: a refusal carries a reason; an endorsement carries signer + signature.
450
+ if (obj["refused"] !== undefined) {
451
+ if (obj["refused"] !== true) {
452
+ fail(`${what}: field "refused" must be true when present`);
453
+ }
454
+ return { v: 1, refused: true, reason: reqString(obj, "reason", what) };
455
+ }
456
+ return {
457
+ v: 1,
458
+ signer: b64urlField(reqString(obj, "signer", what), "signer", what),
459
+ signature: b64urlField(reqString(obj, "signature", what), "signature", what),
460
+ };
461
+ }
462
+
463
+ export function validateMembershipCertV1(value: unknown): MembershipCertV1 {
464
+ const what = "MembershipCertV1";
465
+ const obj = asObject(value, what);
466
+ requireV1(obj, what);
467
+ const out: MembershipCertV1 = {
468
+ v: 1,
469
+ cohortCoord: b64urlFixedLen(reqString(obj, "cohortCoord", what), "cohortCoord", COORD_BYTES, what),
470
+ cohortEpoch: b64urlFixedLen(reqString(obj, "cohortEpoch", what), "cohortEpoch", COORD_BYTES, what),
471
+ members: reqStringArray(obj, "members", what),
472
+ stabilizedAt: reqFiniteNumber(obj, "stabilizedAt", what),
473
+ thresholdSig: b64urlField(reqString(obj, "thresholdSig", what), "thresholdSig", what),
474
+ signers: reqStringArray(obj, "signers", what),
475
+ };
476
+ const attestation = optString(obj, "fretAttestation", what);
477
+ if (attestation !== undefined) {
478
+ out.fretAttestation = b64urlField(attestation, "fretAttestation", what);
479
+ }
480
+ validateRotationAttestation(obj, out, what);
481
+ return out;
482
+ }
483
+
484
+ /**
485
+ * Validate the optional rotation attestation as an all-or-nothing group: either all three of
486
+ * `prevEpoch`/`rotationSig`/`rotationSigners` are present (and well-formed) or all are absent. A
487
+ * partial set is a {@link CohortWireError}. `rotationSigners` is validated only as a string array (its
488
+ * elements are decoded per-element later, mirroring `signers`).
489
+ */
490
+ function validateRotationAttestation(obj: Record<string, unknown>, out: MembershipCertV1, what: string): void {
491
+ const prevEpoch = optString(obj, "prevEpoch", what);
492
+ const rotationSig = optString(obj, "rotationSig", what);
493
+ const rotationSigners = optStringArray(obj, "rotationSigners", what);
494
+ const presentCount = [prevEpoch, rotationSig, rotationSigners].filter((v) => v !== undefined).length;
495
+ if (presentCount === 0) {
496
+ return;
497
+ }
498
+ if (presentCount !== 3) {
499
+ fail(`${what}: rotation attestation requires all of prevEpoch, rotationSig, rotationSigners — or none`);
500
+ }
501
+ out.prevEpoch = b64urlFixedLen(prevEpoch!, "prevEpoch", COORD_BYTES, what);
502
+ out.rotationSig = b64urlField(rotationSig!, "rotationSig", what);
503
+ out.rotationSigners = rotationSigners!;
504
+ }