-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskServiceRefactored.ts
More file actions
1456 lines (1286 loc) · 51.7 KB
/
TaskServiceRefactored.ts
File metadata and controls
1456 lines (1286 loc) · 51.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
/**
* Task Service Refactored
*
* Database-agnostic version of TaskService using repository pattern
* This is a simplified version focusing on core task operations
* Full migration of all 2,461 lines will be done incrementally
*/
import { ILogger } from './utils/ILogger';
import { ITaskRepository } from './interfaces/ITaskRepository';
import { EvaluationService, TaskOutput, ValidatorEvaluation, EvaluationResult } from './EvaluationService';
import { SybilResistanceService } from './SybilResistanceService';
import { OnChainValidatorService } from './OnChainValidatorService';
import { TaskStateIPFSService } from './TaskStateIPFSService';
import { SignatureVerificationService } from './SignatureVerificationService';
import { JSONSchemaValidator } from './JSONSchemaValidator';
import { NetworkManifest } from './types';
import type {
TaskStatus,
TaskState,
TaskSubmission,
} from './TaskService';
export interface TaskServiceDependencies {
taskRepository: ITaskRepository;
evaluationService: EvaluationService;
sybilResistanceService: SybilResistanceService;
onChainValidatorService: OnChainValidatorService;
taskStateIPFSService: TaskStateIPFSService;
signatureVerificationService: SignatureVerificationService;
jsonSchemaValidator: JSONSchemaValidator;
collusionTrackingService: any; // CollusionTrackingService
bootstrapModeService: any; // BootstrapModeService
p2pService?: any; // Optional P2P service
}
/**
* Refactored TaskService with dependency injection
* Uses repository interfaces instead of direct Prisma calls
*/
export class TaskServiceRefactored {
private logger: ILogger;
private taskRepo: ITaskRepository;
private evaluationService: EvaluationService;
private sybilResistanceService: SybilResistanceService;
private onChainValidatorService: OnChainValidatorService;
private taskStateIPFSService: TaskStateIPFSService;
private signatureVerificationService: SignatureVerificationService;
private jsonSchemaValidator: JSONSchemaValidator;
private collusionTrackingService: any;
private bootstrapModeService: any;
private p2pService?: any;
constructor(logger: ILogger, dependencies: TaskServiceDependencies) {
this.logger = logger;
this.taskRepo = dependencies.taskRepository;
this.evaluationService = dependencies.evaluationService;
this.sybilResistanceService = dependencies.sybilResistanceService;
this.onChainValidatorService = dependencies.onChainValidatorService;
this.taskStateIPFSService = dependencies.taskStateIPFSService;
this.signatureVerificationService = dependencies.signatureVerificationService;
this.jsonSchemaValidator = dependencies.jsonSchemaValidator;
this.collusionTrackingService = dependencies.collusionTrackingService;
this.bootstrapModeService = dependencies.bootstrapModeService;
this.p2pService = dependencies.p2pService;
}
/**
* Submit a new task
* Uses repository instead of direct Prisma calls
*/
async submitTask(
taskId: string,
networkId: string,
input: any,
depositorAddress: string,
depositAmount: string,
manifest: NetworkManifest
): Promise<TaskState> {
// Validate input against schema
this.validateInput(input, manifest.taskFormat.inputSchema);
// Create task state object
const submission: TaskSubmission = {
taskId,
networkId,
input,
depositorAddress,
depositAmount,
timestamp: Date.now(),
};
const taskState: TaskState = {
taskId,
networkId,
status: 'submitted',
submission,
outputs: [],
evaluations: [],
consensusReached: false,
paymentReleased: false,
createdAt: Date.now(),
updatedAt: Date.now(),
};
// Upload to IPFS (primary storage)
let ipfsCid: string | null = null;
try {
ipfsCid = await this.taskStateIPFSService.uploadTaskState(taskState);
this.logger.info('Task state uploaded to IPFS', { taskId, ipfsCid });
} catch (error) {
this.logger.warn('Failed to upload to IPFS, will use database', { taskId, error });
}
// Persist to database using repository
await this.taskRepo.create({
taskId,
networkId,
status: 'submitted',
input,
depositorAddress,
depositAmount,
ipfsCid: ipfsCid || undefined,
consensusReached: false,
paymentReleased: false,
createdAt: new Date(),
updatedAt: new Date(),
});
// Announce task via P2P if available
if (this.p2pService) {
try {
await this.p2pService.announceTask({
taskId,
networkId,
taskType: (manifest.taskFormat.inputSchema as any)?.type || 'unknown',
requiredValidators: manifest.validatorConfig.minValidators,
deadline: Date.now() + (manifest.taskFormat.timeout || 3600000),
reward: depositAmount,
manifestCid: manifest.registry.ipfsCid || '',
});
} catch (error) {
this.logger.warn('Failed to announce task via P2P', { taskId, error });
}
}
this.logger.info('Task submitted successfully', { taskId, networkId });
return taskState;
}
/**
* Add miner output
* Uses repository instead of direct Prisma calls
*/
async addMinerOutput(
taskId: string,
output: any,
minerAddress: string,
manifest: NetworkManifest
): Promise<TaskOutput> {
// Validate output against schema
this.validateOutput(output, manifest.taskFormat.outputSchema);
// Generate output ID
const outputId = this.hashOutput(output);
// Create task output
const taskOutput: TaskOutput = {
outputId,
output,
minerAddress,
timestamp: Date.now(),
};
// Persist using repository
await this.taskRepo.addOutput({
id: outputId,
taskId,
outputId,
output,
minerAddress,
timestamp: new Date(),
});
// Update task status
await this.taskRepo.updateStatus(taskId, 'mining');
this.logger.info('Miner output added', { taskId, outputId, minerAddress });
return taskOutput;
}
/**
* Add validator evaluation
* Uses repository instead of direct Prisma calls
*/
async addValidatorEvaluation(
taskId: string,
validatorAddress: string,
outputId: string,
score: number,
confidence: number,
signature: string,
manifest: NetworkManifest
): Promise<ValidatorEvaluation> {
// Verify signature (simplified - actual service may have different signature)
// TODO: Update when SignatureVerificationService is refactored
const signatureValid = true; // Placeholder - actual verification would be done by service
if (!signatureValid) {
throw new Error('Invalid validator signature');
}
// Check validator qualification (Sybil resistance)
const qualificationResult = await this.sybilResistanceService.checkValidatorQualification(
validatorAddress,
manifest.networkId
);
if (!qualificationResult.qualified) {
throw new Error(`Validator not qualified: ${qualificationResult.reasons.join(', ')}`);
}
// Create evaluation
const evaluation: ValidatorEvaluation = {
validatorAddress,
outputId,
score,
confidence,
timestamp: Date.now(),
signature,
};
// Persist using repository
await this.taskRepo.addEvaluation({
id: `eval_${Date.now()}`,
taskId,
outputId,
validatorAddress,
score,
confidence,
signature,
timestamp: new Date(),
});
// Update task status
await this.taskRepo.updateStatus(taskId, 'evaluating');
this.logger.info('Validator evaluation added', { taskId, validatorAddress, outputId, score });
return evaluation;
}
/**
* Get task state
* Uses repository instead of direct Prisma calls
*/
async getTaskState(taskId: string): Promise<TaskState | null> {
// Try to load from repository
const taskData = await this.taskRepo.findById(taskId);
if (!taskData) {
return null;
}
// Load outputs and evaluations
const outputs = await this.taskRepo.getOutputs(taskId);
const evaluations = await this.taskRepo.getEvaluations(taskId);
// Convert to TaskState
const taskState: TaskState = {
taskId: taskData.taskId,
networkId: taskData.networkId,
status: taskData.status as TaskStatus,
submission: {
taskId: taskData.taskId,
networkId: taskData.networkId,
input: taskData.input,
depositorAddress: taskData.depositorAddress,
depositAmount: taskData.depositAmount,
depositTxHash: taskData.depositTxHash,
timestamp: taskData.createdAt.getTime(),
},
outputs: outputs.map(o => ({
outputId: o.outputId,
output: o.output,
minerAddress: o.minerAddress,
timestamp: o.timestamp.getTime(),
})),
evaluations: evaluations.map(e => ({
validatorAddress: e.validatorAddress,
outputId: e.outputId,
score: e.score,
confidence: e.confidence,
timestamp: e.timestamp.getTime(),
signature: e.signature,
})),
consensusReached: taskData.consensusReached,
winningOutputId: taskData.winningOutputId,
paymentReleased: taskData.paymentReleased,
paymentTxHash: taskData.paymentTxHash,
createdAt: taskData.createdAt.getTime(),
updatedAt: taskData.updatedAt.getTime(),
};
return taskState;
}
/**
* Mark task as paid
* Uses repository instead of direct Prisma calls
*/
async markTaskPaid(taskId: string, paymentTxHash: string): Promise<void> {
await this.taskRepo.update(taskId, {
paymentReleased: true,
paymentTxHash,
status: 'paid',
updatedAt: new Date(),
});
this.logger.info('Task marked as paid', { taskId, paymentTxHash });
}
/**
* Get tasks by network
* Uses repository instead of direct Prisma calls
*/
async getTasksByNetwork(networkId: string): Promise<TaskState[]> {
const tasks = await this.taskRepo.findByNetwork(networkId);
// Convert each task to TaskState
const taskStates = await Promise.all(
tasks.map(task => this.getTaskState(task.taskId))
);
return taskStates.filter(t => t !== null) as TaskState[];
}
/**
* Get tasks by status
* Uses repository instead of direct Prisma calls
*/
async getTasksByStatus(status: TaskStatus, limit?: number): Promise<TaskState[]> {
const tasks = await this.taskRepo.findByStatus(status as any, limit);
// Convert each task to TaskState
const taskStates = await Promise.all(
tasks.map(task => this.getTaskState(task.taskId))
);
return taskStates.filter(t => t !== null) as TaskState[];
}
/**
* Get tasks waiting for user selection (human-in-the-loop)
* Uses repository instead of direct Prisma calls
*/
async getTasksWaitingForSelection(networkId?: string): Promise<TaskState[]> {
const tasks = await this.taskRepo.findWaitingForSelection(networkId);
// Convert each task to TaskState
const taskStates = await Promise.all(
tasks.map(task => this.getTaskState(task.taskId))
);
return taskStates.filter(t => t !== null) as TaskState[];
}
/**
* Process evaluations and build consensus
* Uses repository instead of direct Prisma calls
*/
async processEvaluations(
taskId: string,
manifest: NetworkManifest,
validatorReputations: Map<string, number> = new Map()
): Promise<EvaluationResult> {
// Load task state using repository
const taskState = await this.getTaskState(taskId);
if (!taskState) {
throw new Error('Task not found');
}
// Check minimum validators
if (taskState.evaluations.length < manifest.validatorConfig.minValidators) {
throw new Error(`Insufficient validators: need ${manifest.validatorConfig.minValidators}, got ${taskState.evaluations.length}`);
}
// Verify all validator signatures
this.logger.info('Verifying all validator signatures', {
taskId,
evaluationCount: taskState.evaluations.length,
});
const signatureVerification = this.signatureVerificationService.verifyTaskEvaluationSignatures(
taskState.networkId,
taskId,
taskState.evaluations.map((eval_) => ({
validatorAddress: eval_.validatorAddress,
outputId: eval_.outputId,
score: eval_.score,
confidence: eval_.confidence,
signature: eval_.signature,
timestamp: eval_.timestamp,
}))
);
if (!signatureVerification.allValid) {
const invalidCount = signatureVerification.invalidEvaluations.length;
this.logger.warn('Some signatures invalid, filtering them out', {
taskId,
invalidCount,
totalCount: taskState.evaluations.length,
});
// Filter out invalid evaluations
const validEvaluations = taskState.evaluations.filter(
(eval_) => !signatureVerification.invalidEvaluations.some(
(invalid) => invalid.validatorAddress.toLowerCase() === eval_.validatorAddress.toLowerCase()
)
);
if (validEvaluations.length < manifest.validatorConfig.minValidators) {
throw new Error(
`After filtering invalid signatures, only ${validEvaluations.length} valid evaluations remain, but ${manifest.validatorConfig.minValidators} are required.`
);
}
taskState.evaluations = validEvaluations;
}
// Process based on evaluation mode
let evaluationResult: EvaluationResult;
if (manifest.evaluationMode === 'deterministic') {
evaluationResult = await this.evaluationService.evaluateDeterministic(
taskId,
taskState.submission.input,
taskState.outputs,
taskState.evaluations,
manifest.scoringLogic.hash,
manifest.deterministicReplay
);
} else if (manifest.evaluationMode === 'statistical') {
const distributionBased = manifest.statisticalEvaluation?.distributionBased !== false;
const taskType = manifest.category || 'general';
evaluationResult = await this.evaluationService.evaluateStatistical(
taskId,
taskState.outputs,
taskState.evaluations,
validatorReputations,
distributionBased,
taskType,
manifest,
taskState.submission.input
);
// Pre-filter for human-in-the-loop if enabled
if (manifest.humanInTheLoop?.enabled) {
const topN = manifest.humanInTheLoop.topN || 3;
const preFilteredOutputIds = await this.evaluationService.preFilterForHumanSelection(
evaluationResult,
topN,
manifest.humanInTheLoop.userPreference
);
await this.taskRepo.updatePreFilteredOutputs(taskId, preFilteredOutputIds);
this.logger.info('Top-N outputs pre-filtered for human selection', {
taskId,
topN,
outputs: preFilteredOutputIds,
});
}
} else {
// Default to deterministic
evaluationResult = await this.evaluationService.evaluateDeterministic(
taskId,
taskState.submission.input,
taskState.outputs,
taskState.evaluations,
manifest.scoringLogic.hash,
manifest.deterministicReplay
);
}
// Check consensus
const consensus = this.checkConsensus(taskState, manifest);
// Update repository with evaluation result
await this.taskRepo.updateEvaluationResult(taskId, evaluationResult);
if (consensus.reached) {
if (manifest.humanInTheLoop?.enabled && !taskState.humanSelection) {
await this.taskRepo.updateStatus(taskId, 'user-selecting');
this.logger.info('Waiting for user selection', { taskId });
} else {
await this.taskRepo.updateConsensus(taskId, evaluationResult.winningOutputId!);
this.logger.info('Consensus reached', { taskId, winningOutputId: evaluationResult.winningOutputId });
}
}
return evaluationResult;
}
/**
* Check if consensus is reached
*/
checkConsensus(taskState: TaskState, manifest: NetworkManifest): { reached: boolean; acceptCount: number; required: number } {
const scoreThreshold = 50;
const acceptCount = taskState.evaluations.filter(e => e.score >= scoreThreshold).length;
const totalEvaluations = taskState.evaluations.length;
const consensusThreshold = manifest.validatorConfig.consensusThreshold;
const required = Math.ceil(totalEvaluations * consensusThreshold);
const reached = acceptCount >= required && totalEvaluations >= manifest.validatorConfig.minValidators;
return {
reached,
acceptCount,
required,
};
}
/**
* Prepare validator signatures for contract release
*/
prepareValidatorSignatures(
taskState: TaskState,
winningOutputId: string
): Array<{
validator: string;
accepted: boolean;
score: number;
v: number;
r: string;
s: string;
}> {
const winningEvaluations = taskState.evaluations.filter(e => e.outputId === winningOutputId);
if (winningEvaluations.length === 0) {
throw new Error('No evaluations found for winning output');
}
// Verify signatures
const signatureVerification = this.signatureVerificationService.verifyTaskEvaluationSignatures(
taskState.networkId,
taskState.taskId,
winningEvaluations.map((eval_) => ({
validatorAddress: eval_.validatorAddress,
outputId: eval_.outputId,
score: eval_.score,
confidence: eval_.confidence,
signature: eval_.signature,
timestamp: eval_.timestamp,
}))
);
if (!signatureVerification.allValid) {
const invalidValidators = signatureVerification.invalidEvaluations.map(e => e.validatorAddress);
throw new Error(
`Cannot prepare signatures: ${signatureVerification.invalidEvaluations.length} of ${winningEvaluations.length} signatures are invalid. Invalid validators: ${invalidValidators.join(', ')}`
);
}
// Parse signatures
const parsedSignatures = winningEvaluations.map(eval_ => {
const parsed = this.signatureVerificationService.parseSignature(eval_.signature);
if (!parsed) {
throw new Error(`Failed to parse signature for validator ${eval_.validatorAddress}`);
}
return {
validator: eval_.validatorAddress,
accepted: eval_.score >= 50,
score: eval_.score,
v: parsed.v,
r: parsed.r,
s: parsed.s,
};
});
return parsedSignatures;
}
/**
* Get pre-filtered outputs for human selection
* Uses repository instead of direct Prisma calls
*/
async getPreFilteredOutputs(taskId: string): Promise<{
outputs: Array<{
outputId: string;
output: any;
minerAddress: string;
weightedScore: number;
agreementScore: number;
validatorCount: number;
}>;
topN: number;
} | null> {
const taskState = await this.getTaskState(taskId);
if (!taskState || !taskState.preFilteredOutputs) {
return null;
}
// Get evaluation result to calculate scores
const evaluationResult = taskState.evaluationResult;
if (!evaluationResult?.statisticalResult) {
return null;
}
const preFilteredOutputs = evaluationResult.statisticalResult.topOutputs
.filter(o => taskState.preFilteredOutputs!.includes(o.outputId))
.map(o => ({
outputId: o.outputId,
output: taskState.outputs.find(out => out.outputId === o.outputId)?.output,
minerAddress: taskState.outputs.find(out => out.outputId === o.outputId)?.minerAddress || '',
weightedScore: o.weightedScore,
agreementScore: o.agreementScore,
validatorCount: o.validatorCount,
}));
return {
outputs: preFilteredOutputs,
topN: taskState.preFilteredOutputs.length,
};
}
/**
* Add human selection
* Uses repository instead of direct Prisma calls
*/
async addHumanSelection(
taskId: string,
selectedOutputId: string,
userAddress: string,
manifest: NetworkManifest
): Promise<EvaluationResult> {
const taskState = await this.getTaskState(taskId);
if (!taskState) {
throw new Error('Task not found');
}
if (!taskState.preFilteredOutputs || !taskState.preFilteredOutputs.includes(selectedOutputId)) {
throw new Error('Selected output not in pre-filtered list');
}
// Update repository with human selection
await this.taskRepo.updateHumanSelection(taskId, selectedOutputId, userAddress);
// Create evaluation result with human selection
const evaluationResult: EvaluationResult = {
taskId,
mode: 'human-in-the-loop',
winningOutputId: selectedOutputId,
finalScore: 100,
validators: taskState.evaluations.map(e => e.validatorAddress),
humanSelection: {
taskId,
selectedOutputId,
userAddress,
timestamp: Date.now(),
preFilteredOutputs: taskState.preFilteredOutputs || [],
},
};
await this.taskRepo.updateEvaluationResult(taskId, evaluationResult);
this.logger.info('Human selection recorded', { taskId, selectedOutputId, userAddress });
return evaluationResult;
}
/**
* Upload task state to IPFS and anchor on-chain
* Uses repository instead of direct Prisma calls
*/
async uploadAndAnchorTaskState(
taskId: string,
manifest: NetworkManifest
): Promise<{ ipfsCid: string; anchorData: string }> {
try {
// Get current task state using repository
const taskState = await this.getTaskState(taskId);
if (!taskState) {
throw new Error('Task not found');
}
// Upload to IPFS
const ipfsCid = await this.taskStateIPFSService.uploadTaskState(taskState);
// Prepare on-chain anchor
const anchorData = await this.taskStateIPFSService.anchorTaskStateOnChain(
taskId,
ipfsCid,
manifest
);
// Update repository with IPFS CID
await this.taskRepo.update(taskId, {
ipfsCid,
updatedAt: new Date(),
});
this.logger.info('Task state uploaded to IPFS and anchor prepared', {
taskId,
ipfsCid,
contractAddress: manifest.settlement.contractAddress
});
return { ipfsCid, anchorData };
} catch (error) {
this.logger.error('Failed to upload and anchor task state', { taskId, error });
throw error;
}
}
/**
* Verify task state CID against on-chain anchor
* Uses ethers.js to query blockchain
*/
async verifyTaskStateCIDAgainstAnchor(
taskId: string,
ipfsCid: string,
manifest: NetworkManifest
): Promise<boolean> {
try {
const contractAddress = manifest.settlement.contractAddress;
if (!contractAddress) {
this.logger.warn('No contract address for verification', { taskId });
return false;
}
const provider = this.getProvider(manifest.settlement.chain);
if (!provider) {
return false;
}
const { ethers } = await import('ethers');
const contractABI = [
'function getTaskStateAnchor(bytes32 taskId) external view returns (bytes32 stateHash, uint256 timestamp)',
];
const contract = new ethers.Contract(contractAddress, contractABI, provider);
const taskIdBytes32 = ethers.encodeBytes32String(taskId);
const [stateHash] = await contract.getTaskStateAnchor(taskIdBytes32);
if (!stateHash || stateHash === ethers.ZeroHash) {
this.logger.debug('No anchor found on-chain for verification', { taskId });
return false;
}
// Hash the IPFS CID the same way it was hashed when anchored
const cidHash = ethers.keccak256(ethers.toUtf8Bytes(ipfsCid));
// Verify hash matches
const matches = stateHash.toLowerCase() === cidHash.toLowerCase();
if (matches) {
this.logger.info('Task state CID verified against on-chain anchor', {
taskId,
ipfsCid,
stateHash,
});
} else {
this.logger.warn('Task state CID does not match on-chain anchor', {
taskId,
ipfsCid,
expectedHash: stateHash,
computedHash: cidHash,
});
}
return matches;
} catch (error) {
this.logger.error('Failed to verify task state CID against anchor', {
taskId,
error: error instanceof Error ? error.message : String(error),
});
return false;
}
}
/**
* Get on-chain selected validators
* Delegates to OnChainValidatorService
*/
async getOnChainSelectedValidators(
taskId: string,
manifest: NetworkManifest
): Promise<string[]> {
try {
return await this.onChainValidatorService.getSelectedValidators(taskId, manifest);
} catch (error) {
this.logger.error('Failed to get on-chain selected validators', { taskId, error });
// Return empty array if on-chain query fails (fallback to off-chain selection)
return [];
}
}
/**
* Get blockchain provider for a specific chain
* Helper method for on-chain operations
*/
private getProvider(chain: string): any {
const { ethers } = require('ethers');
// Map chain to RPC URL from environment
const rpcUrls: Record<string, string | undefined> = {
ethereum: process.env.ETHEREUM_RPC_URL,
polygon: process.env.POLYGON_RPC_URL,
bsc: process.env.BSC_RPC_URL,
arbitrum: process.env.ARBITRUM_RPC_URL,
base: process.env.BASE_RPC_URL,
avalanche: process.env.AVALANCHE_RPC_URL,
optimism: process.env.OPTIMISM_RPC_URL,
};
const rpcUrl = rpcUrls[chain.toLowerCase()];
if (!rpcUrl) {
this.logger.warn('No RPC URL configured for chain', { chain });
return null;
}
return new ethers.JsonRpcProvider(rpcUrl);
}
/**
* User reject and redo mechanism
* Allows users to reject results and request redo with new validators
*/
async userRejectAndRedo(
taskId: string,
userAddress: string,
manifest: NetworkManifest
): Promise<{
newTaskId: string;
validatorsReplaced: string[];
patternHash: string;
onChainTxData: string | null;
reputationUpdated: boolean;
reputationReason?: string;
shouldPenalize: boolean;
penaltyType?: 'none' | 'soft' | 'partial' | 'challenge';
totalValidators: number;
}> {
try {
// Check if redo is enabled
if (!manifest.userRedo?.enabled) {
throw new Error('User redo not enabled for this network');
}
// Get current task state using repository
const taskState = await this.getTaskState(taskId);
if (!taskState) {
throw new Error('Task not found');
}
// Check redo limit
const redoCount = (taskState.redoCount || 0) + 1;
const maxRedos = manifest.userRedo.maxRedos || 3;
if (redoCount > maxRedos) {
throw new Error(`Maximum redo limit reached (${maxRedos})`);
}
// Get validators who approved the rejected result
const approvedValidators = taskState.evaluations
.filter(e => e.score >= 50)
.map(e => e.validatorAddress);
// Get total validator count in network
const totalValidators = await this.onChainValidatorService.getTotalValidatorCount(manifest);
// Track rejection pattern (encrypted) with statistical process control
const { patternHash, validatorsReplaced, reputationUpdated, reputationReason, shouldPenalize, penaltyType } =
await this.collusionTrackingService.trackUserRejection(
taskId,
manifest.networkId,
approvedValidators,
totalValidators,
redoCount
);
// Record rejection on-chain (returns tx data for frontend)
let onChainTxData: string | null = null;
if (manifest.settlement.contractAddress) {
try {
onChainTxData = await this.recordUserRejectionOnChain(
taskId,
userAddress,
approvedValidators,
patternHash,
manifest
);
} catch (error) {
this.logger.error('Failed to record user rejection on-chain', { taskId, error });
}
}
// Update task state
taskState.userRejected = true;
taskState.redoCount = redoCount;
taskState.collusionPattern = patternHash;
taskState.status = 'user-rejected';
taskState.updatedAt = Date.now();
// Upload updated state to IPFS
let ipfsCid: string | null = null;
try {
ipfsCid = await this.taskStateIPFSService.uploadTaskState(taskState);
} catch (error) {
this.logger.warn('Failed to upload user rejection to IPFS', { taskId, error });
}
// Cache to database
this.cacheTaskStateToDb(taskState, ipfsCid).catch(err => {
this.logger.debug('Failed to cache user rejection to database', { taskId, err });
});
// Create new task ID for redo
const newTaskId = `${taskId}-redo-${redoCount}`;
this.logger.info('User redo requested', {
originalTaskId: taskId,
newTaskId,
redoCount,
totalValidators,
rejectedValidators: approvedValidators.length,
reputationUpdated,
shouldPenalize,
penaltyType,
});
return {
newTaskId,
validatorsReplaced: approvedValidators,
patternHash,
onChainTxData,
reputationUpdated,
reputationReason,
shouldPenalize,
penaltyType,
totalValidators,
};
} catch (error) {
this.logger.error('Failed to process user redo', { taskId, error });
throw error;
}
}
/**
* Check if task is in bootstrap mode
* Uses repository instead of direct Prisma calls
*/
async checkBootstrapModeForTask(
taskId: string,
manifest: NetworkManifest
): Promise<any | null> {
try {
const task = await this.taskRepo.findById(taskId);
if (!task) {
return null;
}
// Get outputs to extract miner addresses
const outputs = await this.taskRepo.getOutputs(taskId);
const minerAddresses = [...new Set(outputs.map(o => o.minerAddress))];
// Check bootstrap mode
const bootstrapConfig = await this.bootstrapModeService.checkBootstrapMode(
manifest.networkId,
manifest,
minerAddresses,
task.depositAmount
);
if (bootstrapConfig.isActive) {
this.logger.info('Bootstrap mode active for task', {
taskId,
mode: bootstrapConfig.mode,
convertedValidators: bootstrapConfig.convertedValidators?.length || 0,
convertedMiners: bootstrapConfig.convertedMiners?.length || 0
});
}
return bootstrapConfig.isActive ? bootstrapConfig : null;
} catch (error) {
this.logger.error('Failed to check bootstrap mode for task', { taskId, error });
return null;
}
}
/**
* Get bootstrap outputs for user selection
* Returns top 2 outputs with bootstrap mode warnings
*/
async getBootstrapOutputsForUserSelection(
taskId: string,
manifest: NetworkManifest
): Promise<any | null> {