@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,522 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-verification.js — Verification quorum protocol.
4
+ *
5
+ * Run the same job on N peers, collect results, vote on correctness.
6
+ * Enables trustless compute verification without TEEs.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-verification.test.mjs
10
+ */
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Constants
14
+ // ---------------------------------------------------------------------------
15
+
16
+ /**
17
+ * Available verification strategies for quorum voting.
18
+ */
19
+ export const VERIFICATION_STRATEGIES = Object.freeze({
20
+ UNANIMOUS: 'unanimous', // all must match
21
+ MAJORITY: 'majority', // >50% match
22
+ THRESHOLD: 'threshold', // configurable % match
23
+ BYZANTINE: 'byzantine', // tolerates f < n/3 faulty
24
+ })
25
+
26
+ /**
27
+ * Default policy values for verification quorum.
28
+ */
29
+ export const VERIFICATION_DEFAULTS = Object.freeze({
30
+ minPeers: 2,
31
+ maxPeers: 10,
32
+ strategy: 'majority',
33
+ timeoutMs: 30000,
34
+ thresholdPct: 0.67,
35
+ })
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Hash helper
39
+ // ---------------------------------------------------------------------------
40
+
41
+ /**
42
+ * Compute a deterministic hash of a result value.
43
+ * Uses JSON.stringify + a simple 32-bit integer hash (djb2-like).
44
+ *
45
+ * @param {*} result - The result to hash
46
+ * @returns {string} Hex-encoded hash string
47
+ */
48
+ export function computeResultHash(result) {
49
+ const str = typeof result === 'string' ? result : JSON.stringify(result)
50
+ let hash = 0
51
+ for (let i = 0; i < str.length; i++) {
52
+ hash = ((hash << 5) - hash + str.charCodeAt(i)) | 0
53
+ }
54
+ return hash.toString(16)
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Attestation
59
+ // ---------------------------------------------------------------------------
60
+
61
+ /**
62
+ * An attestation certifying that a peer produced a specific result
63
+ * for a given job.
64
+ */
65
+ export class Attestation {
66
+ /** @type {string} */
67
+ podId
68
+
69
+ /** @type {string} */
70
+ jobId
71
+
72
+ /** @type {string} */
73
+ resultHash
74
+
75
+ /** @type {string} */
76
+ signature
77
+
78
+ /** @type {number} */
79
+ timestamp
80
+
81
+ /**
82
+ * @param {object} fields
83
+ * @param {string} fields.podId
84
+ * @param {string} fields.jobId
85
+ * @param {string} fields.resultHash
86
+ * @param {string} fields.signature
87
+ * @param {number} fields.timestamp
88
+ */
89
+ constructor({ podId, jobId, resultHash, signature, timestamp }) {
90
+ this.podId = podId
91
+ this.jobId = jobId
92
+ this.resultHash = resultHash
93
+ this.signature = signature
94
+ this.timestamp = timestamp
95
+ }
96
+
97
+ /**
98
+ * Verify this attestation using the provided verification function.
99
+ *
100
+ * @param {Function} verifyFn - (podId, resultHash, signature) => boolean
101
+ * @returns {boolean}
102
+ */
103
+ verify(verifyFn) {
104
+ return verifyFn(this.podId, this.resultHash, this.signature)
105
+ }
106
+
107
+ /**
108
+ * Serialize to a JSON-safe object.
109
+ * @returns {object}
110
+ */
111
+ toJSON() {
112
+ return {
113
+ podId: this.podId,
114
+ jobId: this.jobId,
115
+ resultHash: this.resultHash,
116
+ signature: this.signature,
117
+ timestamp: this.timestamp,
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Restore an Attestation from serialized data.
123
+ * @param {object} json
124
+ * @returns {Attestation}
125
+ */
126
+ static fromJSON(json) {
127
+ return new Attestation({
128
+ podId: json.podId,
129
+ jobId: json.jobId,
130
+ resultHash: json.resultHash,
131
+ signature: json.signature,
132
+ timestamp: json.timestamp,
133
+ })
134
+ }
135
+ }
136
+
137
+ // ---------------------------------------------------------------------------
138
+ // ID generation
139
+ // ---------------------------------------------------------------------------
140
+
141
+ let _jobSeq = 0
142
+
143
+ function generateJobId() {
144
+ return `job_${Date.now().toString(36)}_${(++_jobSeq).toString(36)}`
145
+ }
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // VerificationQuorum
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /**
152
+ * Verification quorum protocol for trustless compute verification.
153
+ *
154
+ * Dispatches the same job to N peers, collects results, groups them
155
+ * by hash, and applies a voting strategy to determine the correct result.
156
+ */
157
+ export class VerificationQuorum {
158
+ /** @type {object} scheduler with dispatch(peerId, job) */
159
+ #scheduler
160
+
161
+ /** @type {object} trust with getReputation(podId), listTrustedPeers() */
162
+ #trust
163
+
164
+ /** @type {Function} */
165
+ #onLog
166
+
167
+ /** @type {object} current policy (mutable copy of defaults) */
168
+ #policy
169
+
170
+ /** @type {Map<string, Function[]>} */
171
+ #listeners = new Map()
172
+
173
+ /**
174
+ * @param {object} deps
175
+ * @param {object} deps.scheduler - { dispatch(peerId, job) => result }
176
+ * @param {object} deps.trust - { getReputation(podId) => number, listTrustedPeers(threshold?) => podId[] }
177
+ * @param {Function} [deps.onLog] - Logging callback
178
+ */
179
+ constructor({ scheduler, trust, onLog } = {}) {
180
+ if (!scheduler) throw new Error('scheduler is required')
181
+ if (!trust) throw new Error('trust is required')
182
+
183
+ this.#scheduler = scheduler
184
+ this.#trust = trust
185
+ this.#onLog = onLog ?? (() => {})
186
+ this.#policy = { ...VERIFICATION_DEFAULTS }
187
+ }
188
+
189
+ // ── Policy ─────────────────────────────────────────────────────────
190
+
191
+ /**
192
+ * Override default policy values.
193
+ *
194
+ * @param {object} policy
195
+ * @param {number} [policy.minPeers]
196
+ * @param {number} [policy.maxPeers]
197
+ * @param {string} [policy.strategy]
198
+ * @param {number} [policy.timeoutMs]
199
+ * @param {number} [policy.thresholdPct]
200
+ */
201
+ setPolicy(policy) {
202
+ if (policy.minPeers != null) this.#policy.minPeers = policy.minPeers
203
+ if (policy.maxPeers != null) this.#policy.maxPeers = policy.maxPeers
204
+ if (policy.strategy != null) this.#policy.strategy = policy.strategy
205
+ if (policy.timeoutMs != null) this.#policy.timeoutMs = policy.timeoutMs
206
+ if (policy.thresholdPct != null) this.#policy.thresholdPct = policy.thresholdPct
207
+ }
208
+
209
+ // ── Core ───────────────────────────────────────────────────────────
210
+
211
+ /**
212
+ * Submit a job for verified execution across a quorum of peers.
213
+ *
214
+ * @param {object} job - The job to execute
215
+ * @param {object} [opts]
216
+ * @param {string[]} [opts.verifiers] - Explicit list of verifier pod IDs
217
+ * @param {string} [opts.verifyLevel] - Override verification level
218
+ * @returns {Promise<{ result: *, confidence: number, attestations: Attestation[], divergent?: object }>}
219
+ */
220
+ async submitVerified(job, opts = {}) {
221
+ const jobId = generateJobId()
222
+ const count = Math.min(this.#policy.maxPeers, Math.max(this.#policy.minPeers, this.#policy.maxPeers))
223
+
224
+ // Step 1: Select verifiers
225
+ const verifiers = opts.verifiers ?? this.#selectVerifiers(job, count)
226
+
227
+ if (verifiers.length === 0) {
228
+ throw new Error('No verifiers available: not enough trusted peers')
229
+ }
230
+
231
+ this.#onLog('info', `Dispatching job ${jobId} to ${verifiers.length} verifiers`)
232
+
233
+ // Step 2: Dispatch to all verifiers in parallel with timeout
234
+ const timeoutMs = this.#policy.timeoutMs
235
+ const settled = await Promise.allSettled(
236
+ verifiers.map((peerId) =>
237
+ this.#dispatchWithTimeout(peerId, job, timeoutMs)
238
+ ),
239
+ )
240
+
241
+ // Collect successful results, track timeouts
242
+ const results = [] // { peerId, result, hash }
243
+ for (let i = 0; i < settled.length; i++) {
244
+ const outcome = settled[i]
245
+ const peerId = verifiers[i]
246
+ if (outcome.status === 'fulfilled') {
247
+ const result = outcome.value
248
+ const hash = computeResultHash(result)
249
+ results.push({ peerId, result, hash })
250
+ } else {
251
+ // Timed out or failed
252
+ this.#onLog('warn', `Verifier ${peerId} failed: ${outcome.reason?.message ?? outcome.reason}`)
253
+ this.#emit('timeout', { peerId, jobId, error: outcome.reason?.message ?? String(outcome.reason) })
254
+ }
255
+ }
256
+
257
+ if (results.length === 0) {
258
+ throw new Error('All verifiers failed or timed out')
259
+ }
260
+
261
+ // Check we have minimum peers
262
+ if (results.length < this.#policy.minPeers) {
263
+ // If we have *some* results but below minimum, we still proceed but with reduced confidence
264
+ this.#onLog('warn', `Only ${results.length}/${this.#policy.minPeers} verifiers responded`)
265
+ }
266
+
267
+ // Step 3-4: Group results by hash
268
+ const { groups, largest } = this.#compareResults(results)
269
+
270
+ // Step 5: Apply strategy
271
+ const stratResult = this.#applyStrategy(groups, results.length)
272
+
273
+ if (!stratResult) {
274
+ // No winner — divergent
275
+ const divergent = {
276
+ groups: Object.fromEntries(
277
+ [...groups.entries()].map(([h, entries]) => [h, entries.map((e) => e.peerId)])
278
+ ),
279
+ totalResponded: results.length,
280
+ }
281
+ this.#emit('divergent', { jobId, groups: divergent })
282
+ const err = new Error(`No winner: results diverge across ${groups.size} groups`)
283
+ err.divergent = divergent
284
+ throw err
285
+ }
286
+
287
+ // Step 6: Build attestations for agreeing peers
288
+ const winnerHash = stratResult.winnerHash
289
+ const winnerEntries = groups.get(winnerHash)
290
+ const attestations = winnerEntries.map((entry) =>
291
+ this.#buildAttestation(entry.peerId, jobId, winnerHash)
292
+ )
293
+
294
+ const outcome = {
295
+ result: winnerEntries[0].result,
296
+ confidence: stratResult.confidence,
297
+ attestations,
298
+ }
299
+
300
+ // Step 7: Emit and return
301
+ this.#emit('verified', outcome)
302
+ this.#onLog('info', `Job ${jobId} verified: confidence=${stratResult.confidence}`)
303
+
304
+ return outcome
305
+ }
306
+
307
+ // ── Private: verifier selection ────────────────────────────────────
308
+
309
+ /**
310
+ * Select verifiers from trusted peers, sorted by reputation (highest first).
311
+ *
312
+ * @param {object} job
313
+ * @param {number} count - Number of verifiers to select
314
+ * @returns {string[]} Array of pod IDs
315
+ */
316
+ #selectVerifiers(job, count) {
317
+ const trusted = this.#trust.listTrustedPeers()
318
+
319
+ if (trusted.length === 0) {
320
+ return []
321
+ }
322
+
323
+ // Sort by reputation descending
324
+ const sorted = [...trusted].sort((a, b) => {
325
+ const ra = this.#trust.getReputation(a)
326
+ const rb = this.#trust.getReputation(b)
327
+ return rb - ra
328
+ })
329
+
330
+ // Take top `count` peers
331
+ return sorted.slice(0, count)
332
+ }
333
+
334
+ // ── Private: dispatch with timeout ─────────────────────────────────
335
+
336
+ /**
337
+ * Dispatch a job to a peer with a timeout.
338
+ *
339
+ * @param {string} peerId
340
+ * @param {object} job
341
+ * @param {number} timeoutMs
342
+ * @returns {Promise<*>}
343
+ */
344
+ #dispatchWithTimeout(peerId, job, timeoutMs) {
345
+ return new Promise((resolve, reject) => {
346
+ let settled = false
347
+ const timer = setTimeout(() => {
348
+ if (!settled) {
349
+ settled = true
350
+ reject(new Error(`Timeout after ${timeoutMs}ms`))
351
+ }
352
+ }, timeoutMs)
353
+
354
+ this.#scheduler.dispatch(peerId, job).then(
355
+ (result) => {
356
+ if (!settled) {
357
+ settled = true
358
+ clearTimeout(timer)
359
+ resolve(result)
360
+ }
361
+ },
362
+ (err) => {
363
+ if (!settled) {
364
+ settled = true
365
+ clearTimeout(timer)
366
+ reject(err)
367
+ }
368
+ },
369
+ ).catch(() => {})
370
+ })
371
+ }
372
+
373
+ // ── Private: compare results ───────────────────────────────────────
374
+
375
+ /**
376
+ * Group results by their hash.
377
+ *
378
+ * @param {Array<{ peerId: string, result: *, hash: string }>} results
379
+ * @returns {{ groups: Map<string, Array>, largest: string }}
380
+ */
381
+ #compareResults(results) {
382
+ const groups = new Map()
383
+
384
+ for (const entry of results) {
385
+ if (!groups.has(entry.hash)) {
386
+ groups.set(entry.hash, [])
387
+ }
388
+ groups.get(entry.hash).push(entry)
389
+ }
390
+
391
+ // Find largest group
392
+ let largest = null
393
+ let largestSize = 0
394
+ for (const [hash, entries] of groups) {
395
+ if (entries.length > largestSize) {
396
+ largestSize = entries.length
397
+ largest = hash
398
+ }
399
+ }
400
+
401
+ return { groups, largest }
402
+ }
403
+
404
+ // ── Private: apply voting strategy ─────────────────────────────────
405
+
406
+ /**
407
+ * Apply the configured strategy to determine a winner.
408
+ *
409
+ * @param {Map<string, Array>} groups - Hash -> entries
410
+ * @param {number} total - Total number of results
411
+ * @returns {{ winnerHash: string, confidence: number }|null}
412
+ */
413
+ #applyStrategy(groups, total) {
414
+ // Find the largest group
415
+ let largestHash = null
416
+ let largestSize = 0
417
+ for (const [hash, entries] of groups) {
418
+ if (entries.length > largestSize) {
419
+ largestSize = entries.length
420
+ largestHash = hash
421
+ }
422
+ }
423
+
424
+ const confidence = largestSize / total
425
+ const strategy = this.#policy.strategy
426
+
427
+ switch (strategy) {
428
+ case VERIFICATION_STRATEGIES.UNANIMOUS:
429
+ // All must agree: single group containing all results
430
+ if (groups.size === 1 && largestSize === total) {
431
+ return { winnerHash: largestHash, confidence: 1.0 }
432
+ }
433
+ return null
434
+
435
+ case VERIFICATION_STRATEGIES.MAJORITY:
436
+ // >50% must agree
437
+ if (confidence > 0.5) {
438
+ return { winnerHash: largestHash, confidence }
439
+ }
440
+ return null
441
+
442
+ case VERIFICATION_STRATEGIES.THRESHOLD:
443
+ // >= configured threshold
444
+ if (confidence >= this.#policy.thresholdPct) {
445
+ return { winnerHash: largestHash, confidence }
446
+ }
447
+ return null
448
+
449
+ case VERIFICATION_STRATEGIES.BYZANTINE:
450
+ // Tolerates f < n/3: winner needs > 2/3 of total
451
+ if (confidence > 2 / 3) {
452
+ return { winnerHash: largestHash, confidence }
453
+ }
454
+ return null
455
+
456
+ default:
457
+ this.#onLog('error', `Unknown strategy: ${strategy}`)
458
+ return null
459
+ }
460
+ }
461
+
462
+ // ── Private: build attestation ─────────────────────────────────────
463
+
464
+ /**
465
+ * Build an attestation for a peer's result.
466
+ *
467
+ * @param {string} podId
468
+ * @param {string} jobId
469
+ * @param {string} resultHash
470
+ * @returns {Attestation}
471
+ */
472
+ #buildAttestation(podId, jobId, resultHash) {
473
+ return new Attestation({
474
+ podId,
475
+ jobId,
476
+ resultHash,
477
+ signature: `sig_${podId}_${jobId}_${resultHash}`,
478
+ timestamp: Date.now(),
479
+ })
480
+ }
481
+
482
+ // ── Events ─────────────────────────────────────────────────────────
483
+
484
+ /**
485
+ * Subscribe to an event.
486
+ * @param {string} event - 'verified' | 'divergent' | 'timeout'
487
+ * @param {Function} cb
488
+ */
489
+ on(event, cb) {
490
+ if (!this.#listeners.has(event)) {
491
+ this.#listeners.set(event, [])
492
+ }
493
+ this.#listeners.get(event).push(cb)
494
+ }
495
+
496
+ /**
497
+ * Unsubscribe from an event.
498
+ * @param {string} event
499
+ * @param {Function} cb
500
+ */
501
+ off(event, cb) {
502
+ const cbs = this.#listeners.get(event)
503
+ if (!cbs) return
504
+ const idx = cbs.indexOf(cb)
505
+ if (idx !== -1) cbs.splice(idx, 1)
506
+ }
507
+
508
+ // ── Private: emit ──────────────────────────────────────────────────
509
+
510
+ /**
511
+ * Emit an event to all listeners (snapshot iteration for safety).
512
+ * @param {string} event
513
+ * @param {...any} args
514
+ */
515
+ #emit(event, ...args) {
516
+ const cbs = this.#listeners.get(event)
517
+ if (!cbs) return
518
+ for (const cb of [...cbs]) {
519
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
520
+ }
521
+ }
522
+ }