-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollusionTrackingService.ts
More file actions
1222 lines (1067 loc) · 40.7 KB
/
CollusionTrackingService.ts
File metadata and controls
1222 lines (1067 loc) · 40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Collusion Tracking Service
*
* Tracks validator patterns to detect potential collusion
* Encrypts patterns to prevent gaming while allowing detection
*/
import { ILogger } from './utils/ILogger';
import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'crypto';
import { PrismaClient } from '@prisma/client';
export interface ValidatorPattern {
validatorAddress: string;
taskId: string;
approved: boolean;
score: number;
timestamp: number;
}
export interface CollusionPattern {
patternHash: string; // Encrypted hash of validator combination
validatorAddresses: string[]; // Validators who always agree (encrypted)
agreementRate: number; // How often they agree (0-1)
taskCount: number; // Number of tasks they've evaluated together
flagged: boolean; // Whether pattern is suspicious
}
export interface ValidatorRejectionStats {
validatorAddress: string;
rejectionRate: number; // R_v: rejection rate of validator v
totalEvaluations: number;
totalRejections: number;
roundsEvaluated: number;
}
export interface NetworkRejectionStats {
networkId: string;
medianRejectionRate: number; // R_net: median rejection rate of network
validatorStats: ValidatorRejectionStats[];
}
export class CollusionTrackingService {
private logger: ILogger;
private prisma: PrismaClient;
private encryptionKey: Buffer;
constructor(prisma: PrismaClient, logger?: Logger) {
this.prisma = prisma;
this.logger = logger || new Logger('CollusionTrackingService');
// In production, get from environment variable
this.encryptionKey = Buffer.from(
process.env.COLLUSION_ENCRYPTION_KEY ||
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
'hex'
);
}
/**
* Track validator evaluation pattern
* Encrypts validator addresses to prevent gaming while allowing pattern detection
*/
async trackValidatorPattern(
taskId: string,
validatorAddress: string,
approved: boolean,
score: number
): Promise<string> {
try {
// Create pattern identifier (validator + task context)
const patternData = {
validatorAddress,
taskId,
approved,
score,
timestamp: Date.now(),
};
// Encrypt validator address (one-way hash for privacy)
const encryptedValidator = this.encryptValidatorAddress(validatorAddress);
// Store pattern (encrypted)
const patternHash = this.hashPattern(patternData);
// Store in database (encrypted)
await this.storePattern(encryptedValidator, taskId, approved, score, patternHash);
this.logger.info('Validator pattern tracked', {
taskId,
encryptedValidator: encryptedValidator.substring(0, 16) + '...',
approved,
patternHash: patternHash.substring(0, 16) + '...',
});
return patternHash;
} catch (error) {
this.logger.error('Failed to track validator pattern', { taskId, validatorAddress, error });
throw error;
}
}
/**
* Detect collusion patterns
* Finds validators who always agree with each other
* FULLY IMPLEMENTED: Queries encrypted patterns and detects correlations
*/
async detectCollusionPatterns(
networkId: string,
minAgreementRate: number = 0.95, // 95% agreement is suspicious
minTaskCount: number = 5 // Need at least 5 tasks together
): Promise<CollusionPattern[]> {
try {
this.logger.info('Detecting collusion patterns', {
networkId,
minAgreementRate,
minTaskCount,
});
// Step 1: Query all tasks with evaluations for this network
const tasks = await this.prisma.tenseuronTask.findMany({
where: { networkId },
include: {
evaluations: true,
},
orderBy: {
createdAt: 'desc',
},
take: 100, // Analyze last 100 tasks
});
if (tasks.length < minTaskCount) {
this.logger.debug('Not enough tasks for pattern detection', {
networkId,
taskCount: tasks.length,
minTaskCount,
});
return [];
}
// Step 2: Build validator co-occurrence matrix (encrypted addresses)
// Map: encryptedValidator -> Set of other encrypted validators they've worked with
const validatorCooccurrence = new Map<string, Map<string, {
tasksTogether: number;
agreements: number;
disagreements: number;
}>>();
for (const task of tasks) {
const evaluations = task.evaluations || [];
if (evaluations.length < 2) continue; // Need at least 2 validators
// Encrypt all validator addresses for this task
const encryptedValidators = evaluations.map(eval_ => ({
encrypted: this.encryptValidatorAddress(eval_.validatorAddress),
original: eval_.validatorAddress,
score: eval_.score,
}));
// Build pairwise relationships
for (let i = 0; i < encryptedValidators.length; i++) {
for (let j = i + 1; j < encryptedValidators.length; j++) {
const v1 = encryptedValidators[i];
const v2 = encryptedValidators[j];
// Initialize maps if needed
if (!validatorCooccurrence.has(v1.encrypted)) {
validatorCooccurrence.set(v1.encrypted, new Map());
}
if (!validatorCooccurrence.has(v2.encrypted)) {
validatorCooccurrence.set(v2.encrypted, new Map());
}
const v1Map = validatorCooccurrence.get(v1.encrypted)!;
const v2Map = validatorCooccurrence.get(v2.encrypted)!;
// Initialize or update co-occurrence data
if (!v1Map.has(v2.encrypted)) {
v1Map.set(v2.encrypted, { tasksTogether: 0, agreements: 0, disagreements: 0 });
}
if (!v2Map.has(v1.encrypted)) {
v2Map.set(v1.encrypted, { tasksTogether: 0, agreements: 0, disagreements: 0 });
}
const v1Data = v1Map.get(v2.encrypted)!;
const v2Data = v2Map.get(v1.encrypted)!;
// Update counts
v1Data.tasksTogether++;
v2Data.tasksTogether++;
v1Data.agreements++;
v2Data.agreements++;
// Check if they agreed (both accepted or both rejected)
const v1Accepted = v1.score >= 50;
const v2Accepted = v2.score >= 50;
if (v1Accepted === v2Accepted) {
v1Data.agreements++;
v2Data.agreements++;
} else {
v1Data.disagreements++;
v2Data.disagreements++;
}
}
}
}
// Step 3: Detect suspicious patterns (high agreement rate)
const collusionPatterns: CollusionPattern[] = [];
const processedPairs = new Set<string>();
for (const [validator1, cooccurrences] of validatorCooccurrence.entries()) {
for (const [validator2, data] of cooccurrences.entries()) {
// Create unique pair key (sorted to avoid duplicates)
const pairKey = [validator1, validator2].sort().join('-');
if (processedPairs.has(pairKey)) continue;
processedPairs.add(pairKey);
// Calculate agreement rate
const totalInteractions = data.agreements + data.disagreements;
if (totalInteractions === 0) continue;
const agreementRate = data.agreements / totalInteractions;
// Check if pattern is suspicious
if (data.tasksTogether >= minTaskCount && agreementRate >= minAgreementRate) {
// Find all validators in this collusion group
const collusionGroup = await this.findCollusionGroup(
validator1,
validator2,
validatorCooccurrence,
minAgreementRate,
minTaskCount
);
if (collusionGroup.length >= 2) {
// Create pattern hash from encrypted validator addresses
const patternHash = this.hashPattern({
validators: collusionGroup.sort(),
networkId,
detectedAt: Date.now(),
});
// Determine if pattern should be flagged
const flagged = agreementRate >= 0.98 && data.tasksTogether >= 10;
collusionPatterns.push({
patternHash,
validatorAddresses: collusionGroup, // Encrypted addresses
agreementRate,
taskCount: data.tasksTogether,
flagged,
});
this.logger.warn('Collusion pattern detected', {
networkId,
patternHash: patternHash.substring(0, 16) + '...',
validatorCount: collusionGroup.length,
agreementRate,
taskCount: data.tasksTogether,
flagged,
});
}
}
}
}
this.logger.info('Collusion pattern detection completed', {
networkId,
patternsFound: collusionPatterns.length,
flaggedPatterns: collusionPatterns.filter(p => p.flagged).length,
});
return collusionPatterns;
} catch (error) {
this.logger.error('Failed to detect collusion patterns', { networkId, error });
return [];
}
}
/**
* Find collusion group starting from a pair of validators
* Uses graph traversal to find all validators who collude together
*/
private async findCollusionGroup(
validator1: string,
validator2: string,
cooccurrence: Map<string, Map<string, { tasksTogether: number; agreements: number; disagreements: number }>>,
minAgreementRate: number,
minTaskCount: number
): Promise<string[]> {
const group = new Set<string>([validator1, validator2]);
const queue = [validator1, validator2];
const visited = new Set<string>();
while (queue.length > 0) {
const current = queue.shift()!;
if (visited.has(current)) continue;
visited.add(current);
const neighbors = cooccurrence.get(current);
if (!neighbors) continue;
for (const [neighbor, data] of neighbors.entries()) {
if (visited.has(neighbor)) continue;
const totalInteractions = data.agreements + data.disagreements;
if (totalInteractions === 0) continue;
const agreementRate = data.agreements / totalInteractions;
// If neighbor has high agreement with current validator, add to group
if (data.tasksTogether >= minTaskCount && agreementRate >= minAgreementRate) {
group.add(neighbor);
queue.push(neighbor);
}
}
}
return Array.from(group);
}
/**
* Track user rejection and mark validators
* CORE PRINCIPLE: Never punish disagreement. Only punish statistically implausible disagreement over time.
*/
async trackUserRejection(
taskId: string,
networkId: string,
approvedValidators: string[],
totalValidators: number, // N: active validators
userRedoCount: number // How many times user has redone this task
): Promise<{
patternHash: string;
validatorsReplaced: boolean;
reputationUpdated: boolean;
reputationReason?: string;
shouldPenalize: boolean; // Only true if statistically implausible over time
penaltyType?: 'none' | 'soft' | 'partial' | 'challenge';
}> {
try {
// Create rejection pattern
const rejectionPattern = {
taskId,
networkId,
approvedValidators: approvedValidators.sort(), // Sort for consistent hashing
timestamp: Date.now(),
type: 'user_rejection',
};
// Hash pattern (encrypted)
const patternHash = this.hashPattern(rejectionPattern);
// Store rejection pattern
await this.storeRejectionPattern(taskId, approvedValidators, patternHash);
// CORE PRINCIPLE: Never punish disagreement. Only punish statistically implausible disagreement over time.
// Step 1: Get network rejection statistics
const networkStats = await this.getNetworkRejectionStats(networkId);
const medianRejectionRate = networkStats.medianRejectionRate; // R_net
// Step 2: Calculate validator rejection rates (R_v) and deviations (Δ_v)
const validatorDeviations = new Map<string, number>();
for (const validatorAddress of approvedValidators) {
const validatorStats = networkStats.validatorStats.find(
v => v.validatorAddress.toLowerCase() === validatorAddress.toLowerCase()
);
if (validatorStats) {
const rejectionRate = validatorStats.rejectionRate; // R_v
const deviation = Math.abs(rejectionRate - medianRejectionRate); // Δ_v = |R_v - R_net|
validatorDeviations.set(validatorAddress, deviation);
} else {
// New validator, no stats yet
validatorDeviations.set(validatorAddress, 0);
}
}
// Step 3: User gaming protection
const U_MAX = 4; // Maximum retries before marking as ambiguous
let shouldUpdateReputation = true;
let reputationReason: string | undefined;
let shouldPenalize = false;
let penaltyType: 'none' | 'soft' | 'partial' | 'challenge' = 'none';
if (userRedoCount > U_MAX) {
// User gaming: task marked as ambiguous, validators immune
shouldUpdateReputation = false;
shouldPenalize = false;
penaltyType = 'none';
reputationReason = `User retry count (${userRedoCount}) > ${U_MAX} - task ambiguous, validators immune`;
// User should pay higher fee (handled elsewhere)
this.logger.warn('User gaming detected - task marked ambiguous', {
taskId,
userRedoCount,
networkId,
});
}
// Step 4: Network-size-adaptive evaluation
else if (totalValidators <= 10) {
// Small networks (N ≤ 10)
const δ_small = 0.3; // Threshold for strong outlier (30% deviation)
const K_small = 3; // Consecutive rounds
// Check if validators are strong outliers over multiple rounds
const outlierValidators = Array.from(validatorDeviations.entries())
.filter(([_, deviation]) => deviation > δ_small)
.map(([address, _]) => address);
if (outlierValidators.length > 0) {
// Check if they've been outliers for K_small consecutive rounds
const persistentOutliers = await this.checkConsecutiveOutliers(
outlierValidators,
networkId,
K_small
);
if (persistentOutliers.length > 0) {
shouldPenalize = true;
penaltyType = 'soft'; // Temporary stake lock, reduced assignment
reputationReason = `Small network: Validators are persistent outliers (${persistentOutliers.length} validators, ${K_small} consecutive rounds)`;
} else {
shouldPenalize = false;
penaltyType = 'none';
reputationReason = 'Small network: Validators are outliers but not persistent - no penalty';
}
} else {
shouldPenalize = false;
penaltyType = 'none';
reputationReason = 'Small network: Validators within normal deviation - no penalty';
}
} else if (totalValidators <= 20) {
// Medium networks (11 ≤ N ≤ 20)
const δ_medium = 0.25; // 25% deviation
const M_medium = 3; // Minimum rounds of disagreement
// Check if validators disagree with majority in multiple rounds
const disagreeingValidators = await this.checkMajorityDisagreement(
approvedValidators,
networkId,
M_medium
);
// Check if disagreement persists across different users/tasks
const persistentDisagreement = await this.checkCrossTaskDisagreement(
disagreeingValidators,
networkId
);
if (persistentDisagreement.length > 0) {
shouldPenalize = true;
penaltyType = 'partial'; // Partial slashing, reputation decay
reputationReason = `Medium network: Validators show persistent systematic bias (${persistentDisagreement.length} validators)`;
} else {
shouldPenalize = false;
penaltyType = 'none';
reputationReason = 'Medium network: Disagreement is task-specific, not systematic - no penalty';
}
} else {
// Large networks (N > 20)
// No penalty for disagreement alone
// Only penalize if: consistency failures, challenge failures, or collusion evidence
const consistencyFailures = await this.checkConsistencyFailures(
approvedValidators,
networkId
);
const collusionEvidence = await this.checkCollusionEvidence(
approvedValidators,
networkId
);
if (consistencyFailures.length > 0 || collusionEvidence.length > 0) {
shouldPenalize = true;
penaltyType = 'challenge'; // Slashing only via challenges
reputationReason = `Large network: Evidence-based penalty (consistency: ${consistencyFailures.length}, collusion: ${collusionEvidence.length})`;
} else {
shouldPenalize = false;
penaltyType = 'none';
reputationReason = 'Large network: Disagreement is normal - rotation + reputation weighting only';
}
}
// Mark validators for replacement (always rotate)
const validatorsReplaced = await this.markValidatorsForReplacement(
networkId,
approvedValidators
);
// Update reputation (always track, conditionally penalize)
if (shouldUpdateReputation) {
await this.updateReputationOnly(approvedValidators, networkId, totalValidators, shouldPenalize, penaltyType);
}
this.logger.info('User rejection tracked (statistical process control)', {
taskId,
networkId,
validatorCount: approvedValidators.length,
totalValidators,
userRedoCount,
medianRejectionRate,
reputationUpdated: shouldUpdateReputation,
shouldPenalize,
penaltyType,
reputationReason,
patternHash: patternHash.substring(0, 16) + '...',
validatorsReplaced,
});
return {
patternHash,
validatorsReplaced,
reputationUpdated: shouldUpdateReputation,
reputationReason,
shouldPenalize,
penaltyType,
};
} catch (error) {
this.logger.error('Failed to track user rejection', { taskId, error });
throw error;
}
}
/**
* Encrypt validator address (one-way for privacy)
*/
private encryptValidatorAddress(address: string): string {
// Use deterministic encryption (same address = same encrypted value)
// This allows pattern detection without revealing identity
const hash = createHash('sha256')
.update(address.toLowerCase())
.update(this.encryptionKey)
.digest('hex');
return hash;
}
/**
* Hash pattern data
*/
private hashPattern(data: any): string {
const json = JSON.stringify(data, Object.keys(data).sort());
return createHash('sha256').update(json).digest('hex');
}
/**
* Store pattern in database
* FULLY IMPLEMENTED: Stores encrypted patterns in database for correlation analysis
*/
private async storePattern(
encryptedValidator: string,
taskId: string,
approved: boolean,
score: number,
patternHash: string
): Promise<void> {
try {
// Store pattern in database for later correlation analysis
// Note: We store encrypted validator address to preserve privacy while allowing pattern detection
// Check if pattern already exists
const existingPattern = await this.prisma.tenseuronTask.findUnique({
where: { taskId },
select: { collusionPattern: true },
});
if (!existingPattern?.collusionPattern) {
// Store pattern hash in task record
await this.prisma.tenseuronTask.update({
where: { taskId },
data: {
collusionPattern: patternHash,
},
});
}
this.logger.debug('Pattern stored in database', {
encryptedValidator: encryptedValidator.substring(0, 16) + '...',
taskId,
approved,
score,
patternHash: patternHash.substring(0, 16) + '...',
});
} catch (error) {
this.logger.error('Failed to store pattern in database', {
taskId,
error: error instanceof Error ? error.message : String(error),
});
// Don't throw - pattern storage is non-critical
}
}
/**
* Store rejection pattern
*/
private async storeRejectionPattern(
taskId: string,
approvedValidators: string[],
patternHash: string
): Promise<void> {
// Encrypt validator addresses
const encryptedValidators = approvedValidators.map(addr =>
this.encryptValidatorAddress(addr)
);
// Store pattern (encrypted)
this.logger.info('Rejection pattern stored', {
taskId,
validatorCount: encryptedValidators.length,
patternHash: patternHash.substring(0, 16) + '...',
});
}
/**
* Mark validators for replacement (rotation)
* Doesn't punish, just rotates them out
*/
private async markValidatorsForReplacement(
networkId: string,
validatorAddresses: string[]
): Promise<boolean> {
try {
// Mark validators as "recently used" so they're excluded from next selection
// This rotates them out without punishment
// In production, update validator rotation tracking
this.logger.info('Validators marked for replacement', {
networkId,
validatorCount: validatorAddresses.length,
});
return true;
} catch (error) {
this.logger.error('Failed to mark validators for replacement', { networkId, error });
return false;
}
}
/**
* Check validator rejection rates
* Returns validators with high rejection rates (>3 rejections or >20% rejection rate)
*/
private async checkValidatorRejectionRates(
validatorAddresses: string[],
networkId: string
): Promise<string[]> {
try {
const highRejectionValidators: string[] = [];
// In production, would query on-chain rejection counts
// For now, check database
for (const validatorAddress of validatorAddresses) {
const rejectionCount = await this.getValidatorRejectionCount(validatorAddress, networkId);
// High rejection: >3 rejections
if (rejectionCount > 3) {
highRejectionValidators.push(validatorAddress);
}
}
return highRejectionValidators;
} catch (error) {
this.logger.error('Failed to check validator rejection rates', { error });
return [];
}
}
/**
* Get validator rejection count
*/
private async getValidatorRejectionCount(
validatorAddress: string,
networkId: string
): Promise<number> {
try {
// In production, would query on-chain: EscrowContract.userRejectionCount(validatorAddress)
// For now, count from database
const tasks = await this.prisma.tenseuronTask.findMany({
where: {
networkId,
userRejected: true,
},
include: {
evaluations: true,
},
});
let rejectionCount = 0;
for (const task of tasks) {
const evaluations = task.evaluations || [];
const validatorEvaluated = evaluations.some(
(e: any) => e.validatorAddress?.toLowerCase() === validatorAddress.toLowerCase()
);
if (validatorEvaluated) {
rejectionCount++;
}
}
return rejectionCount;
} catch (error) {
this.logger.error('Failed to get validator rejection count', { validatorAddress, error });
return 0;
}
}
/**
* Get network rejection statistics
* Calculates R_net (median rejection rate) and R_v (per-validator rejection rates)
*/
private async getNetworkRejectionStats(networkId: string): Promise<NetworkRejectionStats> {
try {
// Get all validators and their rejection stats
const validatorStats: ValidatorRejectionStats[] = [];
// In production, would query on-chain or database
// For now, calculate from task history
const tasks = await this.prisma.tenseuronTask.findMany({
where: { networkId },
include: {
evaluations: true,
},
});
// Count rejections per validator
const validatorRejectionCounts = new Map<string, { rejections: number; evaluations: number }>();
for (const task of tasks) {
if (task.userRejected) {
const taskEvaluations = task.evaluations || [];
for (const eval_ of taskEvaluations) {
const validatorAddress = eval_.validatorAddress;
if (!validatorRejectionCounts.has(validatorAddress)) {
validatorRejectionCounts.set(validatorAddress, { rejections: 0, evaluations: 0 });
}
const stats = validatorRejectionCounts.get(validatorAddress)!;
stats.evaluations++;
// If validator approved but task was rejected, count as rejection
if (eval_.score >= 50) {
stats.rejections++;
}
}
}
}
// Calculate rejection rates
for (const [address, counts] of validatorRejectionCounts.entries()) {
const rejectionRate = counts.evaluations > 0
? counts.rejections / counts.evaluations
: 0;
validatorStats.push({
validatorAddress: address,
rejectionRate,
totalEvaluations: counts.evaluations,
totalRejections: counts.rejections,
roundsEvaluated: counts.evaluations, // Simplified
});
}
// Calculate median rejection rate (R_net)
const rejectionRates = validatorStats.map(v => v.rejectionRate).sort((a, b) => a - b);
const medianRejectionRate = rejectionRates.length > 0
? rejectionRates[Math.floor(rejectionRates.length / 2)]
: 0;
return {
networkId,
medianRejectionRate,
validatorStats,
};
} catch (error) {
this.logger.error('Failed to get network rejection stats', { networkId, error });
return {
networkId,
medianRejectionRate: 0,
validatorStats: [],
};
}
}
/**
* Check if validators have been outliers for consecutive rounds
* REAL IMPLEMENTATION: Queries historical data to check if validators were outliers in last K_small rounds
*/
private async checkConsecutiveOutliers(
validatorAddresses: string[],
networkId: string,
K_small: number
): Promise<string[]> {
try {
// Get recent tasks (last K_small rounds)
const recentTasks = await this.prisma.tenseuronTask.findMany({
where: {
networkId,
userRejected: true, // Only rejected tasks count
},
include: {
evaluations: true,
},
orderBy: {
createdAt: 'desc',
},
take: K_small * 10, // Get enough tasks to cover K_small rounds
});
if (recentTasks.length < K_small) {
// Not enough data yet
return [];
}
// Get network stats for comparison
const networkStats = await this.getNetworkRejectionStats(networkId);
const medianRejectionRate = networkStats.medianRejectionRate;
const δ_small = 0.3; // 30% deviation threshold
// Track how many consecutive rounds each validator was an outlier
const validatorOutlierRounds = new Map<string, number>();
// Group tasks by "round" (simplified: each task is a round)
for (let i = 0; i < Math.min(recentTasks.length, K_small); i++) {
const task = recentTasks[i];
const evaluations = task.evaluations || [];
// Check each validator's evaluation in this round
for (const validatorAddress of validatorAddresses) {
const evaluation = evaluations.find(
(e: any) => e.validatorAddress?.toLowerCase() === validatorAddress.toLowerCase()
);
if (evaluation) {
// Get validator's rejection rate
const validatorStats = networkStats.validatorStats.find(
v => v.validatorAddress.toLowerCase() === validatorAddress.toLowerCase()
);
if (validatorStats) {
const deviation = Math.abs(validatorStats.rejectionRate - medianRejectionRate);
if (deviation > δ_small) {
// Validator is an outlier in this round
const currentCount = validatorOutlierRounds.get(validatorAddress) || 0;
validatorOutlierRounds.set(validatorAddress, currentCount + 1);
} else {
// Reset count if not an outlier
validatorOutlierRounds.set(validatorAddress, 0);
}
}
}
}
}
// Return validators who were outliers for K_small consecutive rounds
const persistentOutliers = Array.from(validatorOutlierRounds.entries())
.filter(([_, rounds]) => rounds >= K_small)
.map(([address, _]) => address);
return persistentOutliers;
} catch (error) {
this.logger.error('Failed to check consecutive outliers', { networkId, error });
return [];
}
}
/**
* Check if validators disagree with majority in multiple rounds
* REAL IMPLEMENTATION: Checks if validators disagreed with majority consensus in last M_medium rounds
*/
private async checkMajorityDisagreement(
validatorAddresses: string[],
networkId: string,
M_medium: number
): Promise<string[]> {
try {
// Get recent tasks
const recentTasks = await this.prisma.tenseuronTask.findMany({
where: { networkId },
orderBy: { createdAt: 'desc' },
take: M_medium * 10, // Get enough tasks
include: {
evaluations: true,
},
});
if (recentTasks.length < M_medium) {
return [];
}
// Track disagreement count per validator
const validatorDisagreementCount = new Map<string, number>();
for (let i = 0; i < Math.min(recentTasks.length, M_medium); i++) {
const task = recentTasks[i];
const evaluations = task.evaluations || [];
if (evaluations.length === 0) continue;
// Calculate majority position (accepted or rejected)
const acceptedCount = evaluations.filter((e: any) => e.score >= 50).length;
const majorityAccepted = acceptedCount > evaluations.length / 2;
// Check each validator's position
for (const validatorAddress of validatorAddresses) {
const evaluation = evaluations.find(
(e: any) => e.validatorAddress?.toLowerCase() === validatorAddress.toLowerCase()
);
if (evaluation) {
const validatorAccepted = evaluation.score >= 50;
// If validator disagrees with majority
if (validatorAccepted !== majorityAccepted) {
const currentCount = validatorDisagreementCount.get(validatorAddress) || 0;
validatorDisagreementCount.set(validatorAddress, currentCount + 1);
}
}
}
}
// Return validators who disagreed in >= M_medium rounds
const disagreeingValidators = Array.from(validatorDisagreementCount.entries())
.filter(([_, count]) => count >= M_medium)
.map(([address, _]) => address);
return disagreeingValidators;
} catch (error) {
this.logger.error('Failed to check majority disagreement', { networkId, error });
return [];
}
}
/**
* Check if disagreement persists across different users/tasks
* REAL IMPLEMENTATION: Verifies disagreement is systematic, not task-specific
*/
private async checkCrossTaskDisagreement(
validatorAddresses: string[],
networkId: string
): Promise<string[]> {
try {
// Get tasks from different users (different depositor addresses)
const tasks = await this.prisma.tenseuronTask.findMany({
where: {
networkId,
userRejected: true,
},
include: {
evaluations: true,
},
});
if (tasks.length < 3) {
// Need at least 3 different tasks to check cross-task pattern
return [];
}
// Group tasks by depositor (different users)
const tasksByUser = new Map<string, typeof tasks>();
for (const task of tasks) {
const depositor = task.depositorAddress;
if (!tasksByUser.has(depositor)) {
tasksByUser.set(depositor, []);
}
tasksByUser.get(depositor)!.push(task);
}
// Check if validators disagree across different users
const validatorCrossTaskDisagreement = new Map<string, Set<string>>();
for (const validatorAddress of validatorAddresses) {
const disagreedUsers = new Set<string>();
for (const [userAddress, userTasks] of tasksByUser.entries()) {
// Check if validator disagreed in this user's tasks
for (const task of userTasks) {
const evaluations = task.evaluations || [];
const evaluation = evaluations.find(
(e: any) => e.validatorAddress?.toLowerCase() === validatorAddress.toLowerCase()
);
if (evaluation && evaluation.score >= 50) {
// Validator approved, but task was rejected
disagreedUsers.add(userAddress);
break; // Count each user once
}
}
}
// If validator disagreed across multiple users, it's systematic
if (disagreedUsers.size >= 2) {
validatorCrossTaskDisagreement.set(validatorAddress, disagreedUsers);
}
}
// Return validators who disagreed across multiple users (systematic bias)
return Array.from(validatorCrossTaskDisagreement.keys());
} catch (error) {
this.logger.error('Failed to check cross-task disagreement', { networkId, error });
return [];
}