@johnhenry/browsermesh-apps 0.0.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.
@@ -0,0 +1,784 @@
1
+ /**
2
+ * clawser-mesh-consensus.js -- Voting and consensus protocols for BrowserMesh.
3
+ *
4
+ * Supports simple majority, super majority (>66.7%), unanimous, and weighted
5
+ * voting. Each Proposal tracks options, quorum, deadline, and status.
6
+ * Ballots record individual votes. Tally aggregates votes and determines
7
+ * winners based on the proposal's VoteType.
8
+ *
9
+ * ConsensusManager orchestrates the full lifecycle: propose -> vote -> close.
10
+ *
11
+ * No browser-only imports at module level.
12
+ *
13
+ * Run tests:
14
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-consensus.test.mjs
15
+ */
16
+
17
+ import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
18
+ import { silentCatch } from './silent-catch.mjs'
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Wire constants (re-exported from canonical registry)
22
+ // ---------------------------------------------------------------------------
23
+
24
+ export const CONSENSUS_PROPOSE = MESH_TYPE.CONSENSUS_PROPOSE; // 0xa8
25
+ export const CONSENSUS_VOTE = MESH_TYPE.CONSENSUS_VOTE; // 0xa9
26
+ export const CONSENSUS_CLOSE = MESH_TYPE.CONSENSUS_CLOSE; // 0xeb
27
+ export const CONSENSUS_RESULT = MESH_TYPE.CONSENSUS_RESULT; // 0xec
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // VoteType enum
31
+ // ---------------------------------------------------------------------------
32
+
33
+ /**
34
+ * Valid vote type identifiers.
35
+ *
36
+ * - `simple` : passes with > 50% of votes
37
+ * - `super` : passes with > 66.7% of votes
38
+ * - `unanimous` : passes only with 100% agreement
39
+ * - `weighted` : passes with > 50% of weighted votes
40
+ *
41
+ * @type {Readonly<{ SIMPLE: 'simple', SUPER: 'super', UNANIMOUS: 'unanimous', WEIGHTED: 'weighted' }>}
42
+ */
43
+ export const VoteType = Object.freeze({
44
+ SIMPLE: 'simple',
45
+ SUPER: 'super',
46
+ UNANIMOUS: 'unanimous',
47
+ WEIGHTED: 'weighted',
48
+ });
49
+
50
+ /** @type {ReadonlySet<string>} */
51
+ const VALID_VOTE_TYPES = new Set(Object.values(VoteType));
52
+
53
+ // ---------------------------------------------------------------------------
54
+ // ID generation
55
+ // ---------------------------------------------------------------------------
56
+
57
+ let _idCounter = 0;
58
+
59
+ /**
60
+ * Generate a unique proposal ID.
61
+ * @returns {string}
62
+ */
63
+ function generateProposalId() {
64
+ return `prop_${Date.now().toString(36)}_${(++_idCounter).toString(36)}`;
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Proposal
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /**
72
+ * A proposal that peers can vote on.
73
+ */
74
+ export class Proposal {
75
+ /**
76
+ * @param {object} opts
77
+ * @param {string} opts.proposalId - Unique identifier
78
+ * @param {string} opts.authorPodId - Pod ID of the author
79
+ * @param {string} opts.title - Short title
80
+ * @param {string} [opts.description] - Optional longer description
81
+ * @param {string[]} opts.options - Choices voters can pick
82
+ * @param {string} opts.voteType - One of VoteType values
83
+ * @param {Map<string,number>|object} [opts.weights] - Pod -> weight map (for weighted voting)
84
+ * @param {number} opts.quorum - Minimum votes required
85
+ * @param {number|null} [opts.deadline] - Unix timestamp (ms) after which the proposal expires
86
+ * @param {number} [opts.createdAt] - Unix timestamp (ms)
87
+ * @param {string} [opts.status] - 'open' | 'closed' | 'expired'
88
+ */
89
+ constructor({
90
+ proposalId,
91
+ authorPodId,
92
+ title,
93
+ description = null,
94
+ options,
95
+ voteType,
96
+ weights = null,
97
+ quorum,
98
+ deadline = null,
99
+ createdAt = Date.now(),
100
+ status = 'open',
101
+ }) {
102
+ if (!proposalId || typeof proposalId !== 'string') {
103
+ throw new Error('proposalId is required and must be a non-empty string');
104
+ }
105
+ if (!authorPodId || typeof authorPodId !== 'string') {
106
+ throw new Error('authorPodId is required and must be a non-empty string');
107
+ }
108
+ if (!title || typeof title !== 'string') {
109
+ throw new Error('title is required and must be a non-empty string');
110
+ }
111
+ if (!Array.isArray(options) || options.length < 2) {
112
+ throw new Error('options must be an array with at least 2 choices');
113
+ }
114
+ if (!VALID_VOTE_TYPES.has(voteType)) {
115
+ throw new Error(`voteType must be one of: ${[...VALID_VOTE_TYPES].join(', ')}`);
116
+ }
117
+ if (typeof quorum !== 'number' || quorum < 1) {
118
+ throw new Error('quorum must be a positive number');
119
+ }
120
+
121
+ this.proposalId = proposalId;
122
+ this.authorPodId = authorPodId;
123
+ this.title = title;
124
+ this.description = description;
125
+ this.options = [...options];
126
+ this.voteType = voteType;
127
+ this.weights = weights instanceof Map
128
+ ? new Map(weights)
129
+ : (weights ? new Map(Object.entries(weights)) : null);
130
+ this.quorum = quorum;
131
+ this.deadline = deadline;
132
+ this.createdAt = createdAt;
133
+ this.status = status;
134
+ }
135
+
136
+ /**
137
+ * Check if this proposal has expired relative to `now`.
138
+ *
139
+ * @param {number} [now=Date.now()]
140
+ * @returns {boolean}
141
+ */
142
+ isExpired(now = Date.now()) {
143
+ if (this.deadline === null) return false;
144
+ return now >= this.deadline;
145
+ }
146
+
147
+ /**
148
+ * Serialize to a JSON-safe object.
149
+ * @returns {object}
150
+ */
151
+ toJSON() {
152
+ return {
153
+ proposalId: this.proposalId,
154
+ authorPodId: this.authorPodId,
155
+ title: this.title,
156
+ description: this.description,
157
+ options: [...this.options],
158
+ voteType: this.voteType,
159
+ weights: this.weights ? Object.fromEntries(this.weights) : null,
160
+ quorum: this.quorum,
161
+ deadline: this.deadline,
162
+ createdAt: this.createdAt,
163
+ status: this.status,
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Re-hydrate from a plain object.
169
+ * @param {object} data
170
+ * @returns {Proposal}
171
+ */
172
+ static fromJSON(data) {
173
+ return new Proposal({
174
+ ...data,
175
+ weights: data.weights ? new Map(Object.entries(data.weights)) : null,
176
+ });
177
+ }
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // Ballot
182
+ // ---------------------------------------------------------------------------
183
+
184
+ /**
185
+ * An individual vote cast by a peer.
186
+ */
187
+ export class Ballot {
188
+ /**
189
+ * @param {object} opts
190
+ * @param {string} opts.proposalId - Which proposal this ballot is for
191
+ * @param {string} opts.voterPodId - Pod ID of the voter
192
+ * @param {string} opts.choice - The chosen option (must be in proposal.options)
193
+ * @param {number} [opts.weight] - Vote weight (defaults to 1)
194
+ * @param {number} [opts.timestamp]
195
+ * @param {string|null} [opts.signature] - Optional cryptographic signature
196
+ */
197
+ constructor({
198
+ proposalId,
199
+ voterPodId,
200
+ choice,
201
+ weight = 1,
202
+ timestamp = Date.now(),
203
+ signature = null,
204
+ }) {
205
+ if (!proposalId || typeof proposalId !== 'string') {
206
+ throw new Error('proposalId is required');
207
+ }
208
+ if (!voterPodId || typeof voterPodId !== 'string') {
209
+ throw new Error('voterPodId is required');
210
+ }
211
+ if (!choice || typeof choice !== 'string') {
212
+ throw new Error('choice is required');
213
+ }
214
+ if (typeof weight !== 'number' || weight < 0) {
215
+ throw new Error('weight must be a non-negative number');
216
+ }
217
+
218
+ this.proposalId = proposalId;
219
+ this.voterPodId = voterPodId;
220
+ this.choice = choice;
221
+ this.weight = weight;
222
+ this.timestamp = timestamp;
223
+ this.signature = signature;
224
+ }
225
+
226
+ /**
227
+ * Serialize to a JSON-safe object.
228
+ * @returns {object}
229
+ */
230
+ toJSON() {
231
+ return {
232
+ proposalId: this.proposalId,
233
+ voterPodId: this.voterPodId,
234
+ choice: this.choice,
235
+ weight: this.weight,
236
+ timestamp: this.timestamp,
237
+ signature: this.signature,
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Re-hydrate from a plain object.
243
+ * @param {object} data
244
+ * @returns {Ballot}
245
+ */
246
+ static fromJSON(data) {
247
+ return new Ballot(data);
248
+ }
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // Tally
253
+ // ---------------------------------------------------------------------------
254
+
255
+ /**
256
+ * Aggregates votes for a single Proposal and determines the outcome.
257
+ */
258
+ export class Tally {
259
+ /** @type {Proposal} */
260
+ #proposal;
261
+
262
+ /** @type {Map<string, Ballot>} voterPodId -> Ballot */
263
+ #ballots = new Map();
264
+
265
+ /**
266
+ * @param {Proposal} proposal
267
+ */
268
+ constructor(proposal) {
269
+ if (!(proposal instanceof Proposal)) {
270
+ throw new Error('proposal must be a Proposal instance');
271
+ }
272
+ this.#proposal = proposal;
273
+ }
274
+
275
+ /**
276
+ * Cast a ballot. Throws on duplicate voter, invalid choice, or
277
+ * closed/expired proposal.
278
+ *
279
+ * @param {Ballot} ballot
280
+ */
281
+ cast(ballot) {
282
+ if (!(ballot instanceof Ballot)) {
283
+ throw new Error('ballot must be a Ballot instance');
284
+ }
285
+ if (ballot.proposalId !== this.#proposal.proposalId) {
286
+ throw new Error('ballot proposalId does not match proposal');
287
+ }
288
+ if (this.#proposal.status === 'closed') {
289
+ throw new Error('proposal is closed');
290
+ }
291
+ if (this.#proposal.status === 'expired' || this.#proposal.isExpired()) {
292
+ throw new Error('proposal is expired');
293
+ }
294
+ if (!this.#proposal.options.includes(ballot.choice)) {
295
+ throw new Error(`invalid choice "${ballot.choice}"; valid options: ${this.#proposal.options.join(', ')}`);
296
+ }
297
+ if (this.#ballots.has(ballot.voterPodId)) {
298
+ throw new Error(`duplicate vote from "${ballot.voterPodId}"`);
299
+ }
300
+
301
+ this.#ballots.set(ballot.voterPodId, ballot);
302
+ }
303
+
304
+ /**
305
+ * Get aggregated results per choice.
306
+ *
307
+ * @returns {Map<string, { votes: number, weight: number }>}
308
+ */
309
+ getResults() {
310
+ /** @type {Map<string, { votes: number, weight: number }>} */
311
+ const results = new Map();
312
+ for (const opt of this.#proposal.options) {
313
+ results.set(opt, { votes: 0, weight: 0 });
314
+ }
315
+ for (const ballot of this.#ballots.values()) {
316
+ const entry = results.get(ballot.choice);
317
+ if (entry) {
318
+ entry.votes += 1;
319
+ entry.weight += ballot.weight;
320
+ }
321
+ }
322
+ return results;
323
+ }
324
+
325
+ /**
326
+ * Determine the winning choice based on the proposal's VoteType.
327
+ *
328
+ * For `simple`: winner needs > 50% of total votes.
329
+ * For `super`: winner needs > 66.7% of total votes.
330
+ * For `unanimous`: winner needs 100% of total votes.
331
+ * For `weighted`: winner needs > 50% of total weight.
332
+ *
333
+ * @returns {{ choice: string, votes: number, weight: number, passed: boolean } | null}
334
+ * null if no votes have been cast.
335
+ */
336
+ getWinner() {
337
+ if (this.#ballots.size === 0) return null;
338
+
339
+ const results = this.getResults();
340
+ let best = null;
341
+
342
+ for (const [choice, data] of results) {
343
+ if (!best || data.votes > best.votes || (data.votes === best.votes && data.weight > best.weight)) {
344
+ best = { choice, votes: data.votes, weight: data.weight };
345
+ }
346
+ }
347
+
348
+ if (!best) return null;
349
+
350
+ const total = this.totalVotes;
351
+ const totalW = this.totalWeight;
352
+ let passed = false;
353
+
354
+ switch (this.#proposal.voteType) {
355
+ case VoteType.SIMPLE:
356
+ passed = best.votes > total / 2;
357
+ break;
358
+ case VoteType.SUPER:
359
+ passed = best.votes > total * (2 / 3);
360
+ break;
361
+ case VoteType.UNANIMOUS:
362
+ passed = best.votes === total;
363
+ break;
364
+ case VoteType.WEIGHTED:
365
+ passed = totalW > 0 && best.weight > totalW / 2;
366
+ break;
367
+ }
368
+
369
+ return { ...best, passed };
370
+ }
371
+
372
+ /**
373
+ * Total number of ballots cast.
374
+ * @returns {number}
375
+ */
376
+ get totalVotes() {
377
+ return this.#ballots.size;
378
+ }
379
+
380
+ /**
381
+ * Sum of all ballot weights.
382
+ * @returns {number}
383
+ */
384
+ get totalWeight() {
385
+ let sum = 0;
386
+ for (const b of this.#ballots.values()) sum += b.weight;
387
+ return sum;
388
+ }
389
+
390
+ /**
391
+ * Whether the quorum has been met.
392
+ * @returns {boolean}
393
+ */
394
+ get hasQuorum() {
395
+ return this.#ballots.size >= this.#proposal.quorum;
396
+ }
397
+
398
+ /**
399
+ * List of voter pod IDs.
400
+ * @returns {string[]}
401
+ */
402
+ get voterList() {
403
+ return [...this.#ballots.keys()];
404
+ }
405
+
406
+ /**
407
+ * The proposal this tally is tracking.
408
+ * @returns {Proposal}
409
+ */
410
+ get proposal() {
411
+ return this.#proposal;
412
+ }
413
+
414
+ /**
415
+ * Serialize to a JSON-safe object.
416
+ * @returns {object}
417
+ */
418
+ toJSON() {
419
+ return {
420
+ proposal: this.#proposal.toJSON(),
421
+ ballots: [...this.#ballots.values()].map(b => b.toJSON()),
422
+ };
423
+ }
424
+
425
+ /**
426
+ * Re-hydrate from a plain object.
427
+ * @param {object} data
428
+ * @returns {Tally}
429
+ */
430
+ static fromJSON(data) {
431
+ const proposal = Proposal.fromJSON(data.proposal);
432
+ const tally = new Tally(proposal);
433
+ // Temporarily mark open to allow casting stored ballots
434
+ const originalStatus = proposal.status;
435
+ proposal.status = 'open';
436
+ const originalDeadline = proposal.deadline;
437
+ proposal.deadline = null;
438
+ for (const bd of data.ballots) {
439
+ tally.cast(Ballot.fromJSON(bd));
440
+ }
441
+ proposal.status = originalStatus;
442
+ proposal.deadline = originalDeadline;
443
+ return tally;
444
+ }
445
+ }
446
+
447
+ // ---------------------------------------------------------------------------
448
+ // ConsensusManager
449
+ // ---------------------------------------------------------------------------
450
+
451
+ /**
452
+ * Orchestrates proposal lifecycle: create, vote, close, expire.
453
+ *
454
+ * Validator sets (`addValidator`/`removeValidator`/`listValidators`) gate
455
+ * WHO may propose/vote — a simple membership check, not a consensus
456
+ * protocol. This class implements majority/super-majority/unanimous/
457
+ * weighted VOTING (see VoteType), not PBFT: there's no pre-prepare/
458
+ * prepare/commit round, no view changes, and no Byzantine fault
459
+ * tolerance guarantee (3f+1 quorum). For that, see the opt-in
460
+ * `@johnhenry/raijin-consensus` package wired at clawser-pod.js's PBFT integration
461
+ * (~line 417-478) — a separate, heavier protocol for when Byzantine
462
+ * safety actually matters (e.g. payment finality). This class is the
463
+ * lightweight default: mesh-wide polls, config changes, elections.
464
+ */
465
+ export class ConsensusManager {
466
+ /** @type {Map<string, Tally>} proposalId -> Tally */
467
+ #tallies = new Map();
468
+
469
+ /** @type {number} */
470
+ #maxProposals;
471
+
472
+ /** @type {function|null} */
473
+ #broadcastFn = null;
474
+
475
+ /** @type {Set<string>} podIds allowed to propose/vote; empty = open membership (no gating) */
476
+ #validators = new Set();
477
+
478
+ /**
479
+ * @param {object} [opts]
480
+ * @param {number} [opts.maxProposals=1000] - Maximum active proposals
481
+ * @param {string[]} [opts.validators] - Initial validator set (empty/omitted = open membership)
482
+ */
483
+ constructor(opts = {}) {
484
+ this.#maxProposals = opts.maxProposals ?? 1000;
485
+ for (const podId of opts.validators || []) this.#validators.add(podId);
486
+ }
487
+
488
+ /**
489
+ * Add a pod to the validator set. Once at least one validator is
490
+ * registered, `propose()`/`vote()` are gated to validator-only — an
491
+ * empty set means open membership (no gating), preserving the
492
+ * pre-validator-set behavior by default.
493
+ *
494
+ * @param {string} podId
495
+ */
496
+ addValidator(podId) {
497
+ if (!podId || typeof podId !== 'string') {
498
+ throw new Error('podId is required and must be a non-empty string');
499
+ }
500
+ this.#validators.add(podId);
501
+ }
502
+
503
+ /**
504
+ * Remove a pod from the validator set. Does not retroactively affect
505
+ * ballots already cast.
506
+ *
507
+ * @param {string} podId
508
+ * @returns {boolean} True if the pod was a validator
509
+ */
510
+ removeValidator(podId) {
511
+ return this.#validators.delete(podId);
512
+ }
513
+
514
+ /**
515
+ * List all registered validator pod IDs.
516
+ * @returns {string[]}
517
+ */
518
+ listValidators() {
519
+ return [...this.#validators];
520
+ }
521
+
522
+ /**
523
+ * Whether `podId` is a registered validator. Always true when the
524
+ * validator set is empty (open membership).
525
+ *
526
+ * @param {string} podId
527
+ * @returns {boolean}
528
+ */
529
+ isValidator(podId) {
530
+ if (this.#validators.size === 0) return true;
531
+ return this.#validators.has(podId);
532
+ }
533
+
534
+ /**
535
+ * Create a new proposal and register its tally.
536
+ *
537
+ * @param {string} authorPodId - Pod ID of the author
538
+ * @param {string} title - Proposal title
539
+ * @param {string[]} options - Choices
540
+ * @param {string} voteType - One of VoteType values
541
+ * @param {object} [opts]
542
+ * @param {string} [opts.description]
543
+ * @param {Map<string,number>|object} [opts.weights]
544
+ * @param {number} [opts.quorum=1]
545
+ * @param {number|null} [opts.deadline]
546
+ * @returns {Proposal}
547
+ */
548
+ propose(authorPodId, title, options, voteType, opts = {}) {
549
+ if (this.#tallies.size >= this.#maxProposals) {
550
+ throw new Error(`maximum proposals (${this.#maxProposals}) reached`);
551
+ }
552
+ if (!this.isValidator(authorPodId)) {
553
+ throw new Error(`"${authorPodId}" is not a registered validator`);
554
+ }
555
+
556
+ const proposal = new Proposal({
557
+ proposalId: generateProposalId(),
558
+ authorPodId,
559
+ title,
560
+ description: opts.description ?? null,
561
+ options,
562
+ voteType,
563
+ weights: opts.weights ?? null,
564
+ quorum: opts.quorum ?? 1,
565
+ deadline: opts.deadline ?? null,
566
+ });
567
+
568
+ this.#tallies.set(proposal.proposalId, new Tally(proposal));
569
+ return proposal;
570
+ }
571
+
572
+ /**
573
+ * Get a proposal by ID.
574
+ *
575
+ * @param {string} proposalId
576
+ * @returns {Proposal|null}
577
+ */
578
+ getProposal(proposalId) {
579
+ const tally = this.#tallies.get(proposalId);
580
+ return tally ? tally.proposal : null;
581
+ }
582
+
583
+ /**
584
+ * Cast a vote on a proposal.
585
+ *
586
+ * @param {string} proposalId
587
+ * @param {string} voterPodId
588
+ * @param {string} choice
589
+ * @param {number} [weight=1]
590
+ * @returns {Ballot}
591
+ */
592
+ vote(proposalId, voterPodId, choice, weight = 1) {
593
+ const tally = this.#tallies.get(proposalId);
594
+ if (!tally) {
595
+ throw new Error(`proposal "${proposalId}" not found`);
596
+ }
597
+ if (!this.isValidator(voterPodId)) {
598
+ throw new Error(`"${voterPodId}" is not a registered validator`);
599
+ }
600
+
601
+ const ballot = new Ballot({
602
+ proposalId,
603
+ voterPodId,
604
+ choice,
605
+ weight,
606
+ });
607
+
608
+ tally.cast(ballot);
609
+ return ballot;
610
+ }
611
+
612
+ /**
613
+ * Close a proposal and return the results.
614
+ *
615
+ * @param {string} proposalId
616
+ * @returns {{ winner: object|null, results: Map<string, { votes: number, weight: number }> }}
617
+ */
618
+ closeProposal(proposalId) {
619
+ const tally = this.#tallies.get(proposalId);
620
+ if (!tally) {
621
+ throw new Error(`proposal "${proposalId}" not found`);
622
+ }
623
+ if (tally.proposal.status === 'closed') {
624
+ throw new Error('proposal is already closed');
625
+ }
626
+
627
+ tally.proposal.status = 'closed';
628
+
629
+ return {
630
+ winner: tally.getWinner(),
631
+ results: tally.getResults(),
632
+ };
633
+ }
634
+
635
+ /**
636
+ * Get the tally for a proposal.
637
+ *
638
+ * @param {string} proposalId
639
+ * @returns {Tally|null}
640
+ */
641
+ getTally(proposalId) {
642
+ return this.#tallies.get(proposalId) || null;
643
+ }
644
+
645
+ /**
646
+ * List proposals, optionally filtered by status.
647
+ *
648
+ * @param {object} [opts]
649
+ * @param {string} [opts.status] - Filter by 'open', 'closed', or 'expired'
650
+ * @returns {Proposal[]}
651
+ */
652
+ listProposals(opts = {}) {
653
+ const proposals = [...this.#tallies.values()].map(t => t.proposal);
654
+ if (opts.status) {
655
+ return proposals.filter(p => p.status === opts.status);
656
+ }
657
+ return proposals;
658
+ }
659
+
660
+ /**
661
+ * Expire all proposals whose deadline has passed.
662
+ *
663
+ * @param {number} [now=Date.now()]
664
+ * @returns {number} Number of proposals expired
665
+ */
666
+ expireAll(now = Date.now()) {
667
+ let count = 0;
668
+ for (const tally of this.#tallies.values()) {
669
+ const p = tally.proposal;
670
+ if (p.status === 'open' && p.isExpired(now)) {
671
+ p.status = 'expired';
672
+ count++;
673
+ }
674
+ }
675
+ return count;
676
+ }
677
+
678
+ /**
679
+ * Total number of tracked proposals.
680
+ * @returns {number}
681
+ */
682
+ get size() {
683
+ return this.#tallies.size;
684
+ }
685
+
686
+ /**
687
+ * Wire the ConsensusManager to a mesh transport layer.
688
+ *
689
+ * Outbound: proposals, votes, close, and result messages are sent via
690
+ * `broadcastFn(type, payload)`.
691
+ *
692
+ * Inbound: messages are received via `subscribeFn(type, handler)` where
693
+ * handler receives `(payload, fromPodId)`.
694
+ *
695
+ * @param {function} broadcastFn - `(wireType: number, payload: object) => void`
696
+ * @param {function} subscribeFn - `(wireType: number, handler: (payload, fromPodId) => void) => void`
697
+ */
698
+ wireTransport(broadcastFn, subscribeFn) {
699
+ if (typeof broadcastFn !== 'function' || typeof subscribeFn !== 'function') {
700
+ throw new Error('broadcastFn and subscribeFn must be functions');
701
+ }
702
+
703
+ this.#broadcastFn = broadcastFn;
704
+
705
+ // Inbound: receive proposals
706
+ subscribeFn(CONSENSUS_PROPOSE, (payload, fromPodId) => {
707
+ try {
708
+ if (!this.isValidator(payload.authorPodId)) {
709
+ throw new Error(`"${payload.authorPodId}" is not a registered validator`);
710
+ }
711
+ const proposal = Proposal.fromJSON(payload);
712
+ const tally = new Tally(proposal);
713
+ this.#tallies.set(proposal.proposalId, tally);
714
+ } catch (e) { silentCatch('clawser-mesh-consensus', 'ignore-malformed-proposals', e) }
715
+ });
716
+
717
+ // Inbound: receive votes
718
+ subscribeFn(CONSENSUS_VOTE, (payload, fromPodId) => {
719
+ try {
720
+ const { proposalId, choice, weight } = payload;
721
+ this.vote(proposalId, fromPodId, choice, weight ?? 1);
722
+ } catch (e) { silentCatch('clawser-mesh-consensus', 'ignore-invalid-votes', e) }
723
+ });
724
+
725
+ // Inbound: receive close requests
726
+ subscribeFn(CONSENSUS_CLOSE, (payload, fromPodId) => {
727
+ try { this.closeProposal(payload.proposalId); } catch (e) { silentCatch('clawser-mesh-consensus', 'this.closeProposal', e) }
728
+ });
729
+
730
+ // Inbound: receive results (informational, for sync)
731
+ subscribeFn(CONSENSUS_RESULT, (payload, fromPodId) => {
732
+ // Results are informational — remote peers can use them to update UI
733
+ // No action needed on the ConsensusManager side
734
+ });
735
+ }
736
+
737
+ /**
738
+ * Broadcast a proposal over the transport.
739
+ *
740
+ * @param {Proposal} proposal
741
+ */
742
+ broadcastProposal(proposal) {
743
+ if (this.#broadcastFn) {
744
+ this.#broadcastFn(CONSENSUS_PROPOSE, proposal.toJSON());
745
+ }
746
+ }
747
+
748
+ /**
749
+ * Broadcast a vote over the transport.
750
+ *
751
+ * @param {string} proposalId
752
+ * @param {string} voterPodId
753
+ * @param {string} choice
754
+ * @param {number} [weight=1]
755
+ */
756
+ broadcastVote(proposalId, voterPodId, choice, weight = 1) {
757
+ if (this.#broadcastFn) {
758
+ this.#broadcastFn(CONSENSUS_VOTE, { proposalId, voterPodId, choice, weight });
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Broadcast a close request over the transport.
764
+ *
765
+ * @param {string} proposalId
766
+ */
767
+ broadcastClose(proposalId) {
768
+ if (this.#broadcastFn) {
769
+ this.#broadcastFn(CONSENSUS_CLOSE, { proposalId });
770
+ }
771
+ }
772
+
773
+ /**
774
+ * Broadcast a result over the transport.
775
+ *
776
+ * @param {string} proposalId
777
+ * @param {object} result
778
+ */
779
+ broadcastResult(proposalId, result) {
780
+ if (this.#broadcastFn) {
781
+ this.#broadcastFn(CONSENSUS_RESULT, { proposalId, ...result });
782
+ }
783
+ }
784
+ }