-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcommands.go
More file actions
2937 lines (2476 loc) · 105 KB
/
commands.go
File metadata and controls
2937 lines (2476 loc) · 105 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
package main
import (
"bufio"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"gobius/account"
"gobius/bindings/arbiusrouterv1"
"gobius/bindings/basetoken" // Added for BaseToken ABI
"gobius/bindings/engine"
"gobius/client"
task "gobius/common"
"gobius/ipfs"
"gobius/metrics"
"gobius/models"
"gobius/storage"
"io"
"log"
"math"
"math/big"
"math/rand"
"os"
"sort"
"strings"
"time"
"bytes" // Added for bytes.Equal
"gobius/bindings/bulktasks"
gpu "gobius/common"
"github.com/briandowns/spinner"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types" // Added for deriving addresses
"github.com/google/uuid"
"github.com/ipfs/go-cid" // Added for CID handling
"github.com/mr-tron/base58" // Added for Base58 encoding
"github.com/olekukonko/tablewriter" // Added for table output
"github.com/rs/zerolog"
)
func importUnsolvedTasks(appQuit context.Context, filename string, removeMode bool, logger *zerolog.Logger, ctx context.Context) error {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
if removeMode {
logger.Info().Str("file", filename).Msg("removing tasks listed in file from task queue")
} else {
logger.Info().Str("file", filename).Msg("importing tasks into task queue")
}
file, err := os.Open(filename)
if err != nil {
logger.Fatal().Err(err).Msg("could not open file")
}
// send file to json decoder
decoder := json.NewDecoder(file)
taskIdsToTxes := make(map[string]string) // Still need TxHash if importing, might be unused if removing
err = decoder.Decode(&taskIdsToTxes)
if err != nil {
logger.Fatal().Err(err).Msg("could not decode file")
}
file.Close()
totalItemstoProcess := len(taskIdsToTxes)
if removeMode {
logger.Info().Int("tasks", totalItemstoProcess).Msg("processing tasks from file for removal")
} else {
logger.Info().Int("tasks", totalItemstoProcess).Msg("processing tasks from file for import")
}
s := spinner.New(spinner.CharSets[11], 500*time.Millisecond, spinner.WithWriter(os.Stderr)) // Ensure spinner writes to stderr if needed
if removeMode {
s.Suffix = " removing tasks..."
} else {
s.Suffix = " processing tasks..."
}
s.FinalMSG = "completed!\n"
s.Start()
defer s.Stop() // Ensure spinner stops
mapOfPendingSolTasks := make(map[task.TaskId]struct{})
pendingSols, err := services.TaskStorage.GetAllSolutions()
if err != nil {
logger.Fatal().Err(err).Msg("could not get all pending solutions")
}
for _, v := range pendingSols {
mapOfPendingSolTasks[v.TaskId] = struct{}{}
}
if removeMode {
removedCount := 0
skippedPendingCount := 0
index := 0
for taskIdStr := range taskIdsToTxes {
index++
select {
case <-appQuit.Done():
logger.Info().Msg("app quit signal received, stopping removal")
return nil
default:
}
id, err := task.ConvertTaskIdString2Bytes(taskIdStr)
if err != nil {
logger.Error().Err(err).Str("task", taskIdStr).Msg("could not convert task ID string")
continue // Skip this task
}
// *** Check if a solution is pending for this task ***
if _, isPending := mapOfPendingSolTasks[id]; isPending {
logger.Warn().Str("task", taskIdStr).Msg("skipping removal: task has a pending solution")
skippedPendingCount++
continue // Skip deletion attempt
}
// Attempt to delete the task
err = services.TaskStorage.DeleteTask(id)
if err != nil {
logger.Error().Err(err).Str("task", taskIdStr).Msg("failed to delete task")
} else {
logger.Debug().Str("task", taskIdStr).Msg("task removed successfully")
removedCount++
}
s.Suffix = fmt.Sprintf(" removing tasks [%d/%d] (removed: %d, skipped_pending: %d)\n", index, totalItemstoProcess, removedCount, skippedPendingCount)
}
logger.Info().Int("removed", removedCount).Int("skipped_pending", skippedPendingCount).Int("total_processed", totalItemstoProcess).Msg("finished removing tasks from queue")
return nil // End function here for removal mode
}
mapOfHashsByTasks := make(map[string][]task.TaskId)
allTasks, err := services.TaskStorage.GetQueuedTasks()
if err != nil {
logger.Fatal().Err(err).Msg("could not get all tasks")
}
mapOfTaskOnwers := make(map[common.Address]int)
uniqueTasksMap := make(map[task.TaskId]struct{})
for _, v := range allTasks {
uniqueTasksMap[v.TaskId] = struct{}{} // Corrected syntax
}
whitelistedCount := 0
solvedCount := 0
pendingCount := 0
alreadyExists := 0
index := 0
for taskId, txHash := range taskIdsToTxes {
index++
select {
case <-appQuit.Done():
logger.Info().Msg("app quit signal received, stopping import")
return nil
default:
// continue
}
id, err := task.ConvertTaskIdString2Bytes(taskId)
if err != nil {
logger.Error().Err(err).Str("task", taskId).Msg("could convert task")
return err
}
if _, ok := mapOfPendingSolTasks[id]; ok {
pendingCount++
continue
}
if _, ok := uniqueTasksMap[id]; ok {
logger.Debug().Str("task", taskId).Msg("task already exists in the storage tasks list")
alreadyExists++
continue
}
taskInfo, err := services.Engine.Engine.Tasks(nil, id)
if err != nil {
logger.Error().Err(err).Str("task", taskId).Msg("error getting task information")
return err
}
mapOfTaskOnwers[taskInfo.Owner] = mapOfTaskOnwers[taskInfo.Owner] + 1
res, err := services.Engine.GetSolution(id)
if err != nil {
logger.Err(err).Msg("error getting solution information")
return err
}
logger.Debug().Uint64("blocktime", res.Blocktime).Bool("claimed", res.Claimed).Str("validator", res.Validator.String()).Str("Cid", common.Bytes2Hex(res.Cid[:])).Msg("old tasks being added to queue")
if res.Blocktime == 0 {
mapOfHashsByTasks[txHash] = append(mapOfHashsByTasks[txHash], id)
} else {
solvedCount++
}
s.Suffix = fmt.Sprintf(" processing tasks [%d/%d] (already imported: %d)\n", index, totalItemstoProcess, alreadyExists)
}
addedTasksCount := 0
for key, value := range mapOfHashsByTasks {
key := common.HexToHash(key)
services.TaskStorage.AddTasks(value, key, 0)
addedTasksCount += len(value)
}
for owner, v := range mapOfTaskOnwers {
logger.Debug().Int("tasks", v).Str("owner", owner.String()).Msg("tasks per owner")
}
logger.Info().Int("pending_sol", pendingCount).Int("added_tasks", addedTasksCount).Int("solved", solvedCount).Int("whitelisted", whitelistedCount).Msg("finished adding unsolved tasks to queue")
return nil
}
func taskCheck(logger *zerolog.Logger, ctx context.Context) error {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
allTasks, err := services.TaskStorage.GetQueuedTasks()
if err != nil {
logger.Fatal().Err(err).Msg("could not get all tasks")
}
mapOfTaskOnwers := make(map[common.Address]int)
mapOfSolutionVals := make(map[common.Address]int)
totalItemstoProcess := len(allTasks)
logger.Info().Int("tasks", totalItemstoProcess).Msg("checking tasks")
s := spinner.New(spinner.CharSets[11], 500*time.Millisecond)
s.Suffix = " processing tasks..."
s.FinalMSG = "completed!\n"
s.Start()
for index, key := range allTasks {
taskInfo, err := services.Engine.Engine.Tasks(nil, key.TaskId)
if err != nil {
logger.Error().Err(err).Str("task", key.TaskId.String()).Msg("error getting task information")
return err
}
mapOfTaskOnwers[taskInfo.Owner] = mapOfTaskOnwers[taskInfo.Owner] + 1
res, err := services.Engine.GetSolution(key.TaskId)
if err != nil {
logger.Err(err).Msg("error getting solution information")
return err
}
logger.Debug().Uint64("blocktime", res.Blocktime).Bool("claimed", res.Claimed).Str("validator", res.Validator.String()).Str("Cid", common.Bytes2Hex(res.Cid[:])).Msg("old tasks being added to queue")
if res.Blocktime != 0 {
mapOfSolutionVals[res.Validator] = mapOfSolutionVals[res.Validator] + 1
}
s.Suffix = fmt.Sprintf(" processing tasks [%d/%d]\n", index, totalItemstoProcess)
}
for owner, v := range mapOfTaskOnwers {
logger.Info().Int("tasks", v).Str("owner", owner.String()).Msg("tasks per owner")
}
for owner, v := range mapOfSolutionVals {
logger.Info().Int("tasks", v).Str("val", owner.String()).Msg("solved tasks per validator")
}
return nil
}
func importUnclaimedTasks(filename string, logger *zerolog.Logger, ctx context.Context) error {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
logger.Info().Str("file", filename).Msg("importing unclaimed tasks into claims queue")
file, err := os.Open(filename)
if err != nil {
logger.Fatal().Err(err).Msg("could not open file")
}
defer file.Close()
// send file to json decoder
decoder := json.NewDecoder(file)
taskIds := []string{}
err = decoder.Decode(&taskIds)
if err != nil {
logger.Fatal().Err(err).Msg("could not decode file")
}
logger.Info().Int("tasks", len(taskIds)).Msg("adding claims to storage")
tasks := make([]task.TaskId, len(taskIds))
for _, v := range taskIds {
taskId, err := task.ConvertTaskIdString2Bytes(v)
if err != nil {
logger.Error().Err(err).Str("task", v).Msg("could convert task")
break
}
tasks = append(tasks, taskId)
}
services.TaskStorage.AddTasksToClaim(tasks, 0)
//logger.Info().Msg("claims added, now running deduplicate and verify stage")
// TODO: readd
// dedupeVerifyClaims(logger, ctx)
return nil
}
func verifyClaims(logger *zerolog.Logger, ctx context.Context) {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
logger.Info().Msg("verifying claims in storage")
_, claims, err := services.TaskStorage.TotalSolutionsAndClaims()
if err != nil {
logger.Fatal().Err(err).Msg("could not get claim totals from storage")
}
allClaims, _, err := services.TaskStorage.GetClaims(int(claims))
if err != nil {
logger.Fatal().Err(err).Msg("could not get claims in storage")
}
logger.Info().Int("claims", len(allClaims)).Msg("verifying claims")
minClaimSolutionTimeBig, err := services.Engine.Engine.MinClaimSolutionTime(nil)
if err != nil {
logger.Fatal().Err(err).Msg("error calling MinClaimSolutionTime")
}
minContestationVotePeriodTimeBig, err := services.Engine.Engine.MinContestationVotePeriodTime(nil)
if err != nil {
logger.Fatal().Err(err).Msg("error calling MinContestationVotePeriodTime")
}
cacheValidatorCooldown := map[common.Address]uint64{}
var claimsToDelete []task.TaskId
s := spinner.New(spinner.CharSets[11], 500*time.Millisecond)
s.Suffix = " processing tasks..."
s.FinalMSG = "completed!\n"
s.Start()
totalItemstoProcess := len(allClaims)
for index, value := range allClaims {
s.Suffix = fmt.Sprintf(" processing tasks [%d/%d]", index, totalItemstoProcess)
taskStr := value.ID.String()
contestationDetails, err := services.Engine.GetContestation(value.ID)
if err != nil {
logger.Fatal().Err(err).Str("task", taskStr).Msg("could not get contestation details")
}
if contestationDetails.Validator.String() != "0x0000000000000000000000000000000000000000" {
contestor := contestationDetails.Validator.String()
logger.Warn().Str("task", taskStr).Str("contestor", contestor).Str("validator", contestationDetails.Validator.String()).Str("slashedamount", contestationDetails.SlashAmount.String()).Msg("⚠️ task was contested, deleting ⚠️")
claimsToDelete = append(claimsToDelete, value.ID)
continue
}
solution, err := services.Engine.GetSolution(value.ID)
if err != nil {
logger.Fatal().Err(err).Str("task", taskStr).Msg("cloud not get solution details")
}
cooldownTime := uint64(0)
//cacheValidatorCooldown[solution.Validator]
if cooldownTime, ok = cacheValidatorCooldown[solution.Validator]; !ok {
lastContestationLossTimeBig, err := services.Engine.Engine.LastContestationLossTime(nil, solution.Validator)
if err != nil {
logger.Fatal().Err(err).Msg("error calling LastContestationLossTime")
}
lastContestationLossTime := lastContestationLossTimeBig.Uint64()
if lastContestationLossTime > 0 {
minClaimSolutionTime := minClaimSolutionTimeBig.Uint64()
minContestationVotePeriodTime := minContestationVotePeriodTimeBig.Uint64()
cooldownTime = lastContestationLossTime + minClaimSolutionTime + minContestationVotePeriodTime
cacheValidatorCooldown[solution.Validator] = cooldownTime
logger.Debug().Uint64("lastcontestationlosttime", lastContestationLossTime).Uint64("cooldowntime", cooldownTime).Msg("last contestation time")
} else {
cacheValidatorCooldown[solution.Validator] = 0
}
}
if solution.Blocktime <= cooldownTime {
logger.Warn().Str("taskid", taskStr).Str("validator", solution.Validator.String()).Msg("⚠️ lost due to contestation cooldown ⚠️")
claimsToDelete = append(claimsToDelete, value.ID)
continue
}
if solution.Claimed {
logger.Info().Str("task", taskStr).Msgf("task already claimed by %s", solution.Validator.String())
claimsToDelete = append(claimsToDelete, value.ID)
continue
}
}
s.Stop()
if len(claimsToDelete) > 0 {
logger.Info().Int("claims", len(claimsToDelete)).Msgf("deleting claimed or unclaimable tasks")
err := services.TaskStorage.DeleteClaims(claimsToDelete)
if err != nil {
logger.Fatal().Err(err).Msg("could not delete claims")
}
}
logger.Info().Msgf("verified claims and %d deleted", len(claimsToDelete))
}
func getBatchPricingInfo(ctx context.Context) error {
var err error
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
basePrice, ethPrice, err := services.Paraswap.GetPrices()
if err != nil {
services.Logger.Error().Err(err).Msg("could not get prices from oracle api!")
}
basefee, err := services.OwnerAccount.Client.GetBaseFee()
if err != nil {
services.Logger.Error().Err(err).Msg("could not get basefee!")
}
// convert basefee to gwei
basefeeinEth := Eth.ToFloat(basefee)
//rewardInAIUS := tm.cumulativeGasUsed.rewardEMA.Average()
reward, err := services.Engine.Engine.GetReward(nil)
if err != nil {
services.Logger.Error().Err(err).Msg("could not get reward!")
}
rewardInAIUS := services.Config.BaseConfig.BaseToken.ToFloat(reward) * 0.9
claimMaxBatchSize := services.Config.Claim.MaxClaims
//claims, err := services.TaskStorage.GetClaims(claimMaxBatchSize)
claims, averageGas, err := services.TaskStorage.GetClaims(claimMaxBatchSize)
if err != nil {
services.Logger.Error().Err(err).Msg("could not get keys from storage")
return err
}
claimMaxBatchSize = len(claims)
totalCost := 0.0
for _, task := range claims {
totalCost += task.TotalCost
}
claimTasks := (47_300.0 * basefeeinEth * float64(claimMaxBatchSize))
services.Logger.Warn().Msgf("** debug. total cost : %f **", totalCost)
services.Logger.Warn().Msgf("** average gas/task : %f **", averageGas)
totalCost += claimTasks
totalCostInUSD := totalCost * ethPrice //fmt.Sprintf("%0.4f$", totalCost*ethPrice)
claimValue := rewardInAIUS * float64(claimMaxBatchSize) * basePrice
services.Logger.Warn().Msgf("** total cost of mining batch : %0.4g$ (gas spent: %f)**", totalCostInUSD, totalCost)
services.Logger.Warn().Msgf("** batch value : %0.4g$ **", claimValue)
services.Logger.Warn().Msgf("** profit : %0.4g$ **", claimValue-totalCostInUSD)
return nil
}
func verifyAllTasks(ctx context.Context, dryMode bool) error {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
allTasks, err := services.TaskStorage.GetAllTasks()
if err != nil {
services.Logger.Fatal().Err(err).Msg("could not get claims in storage")
}
// get all solutions from storage
solutions, err := services.TaskStorage.GetAllSolutions()
if err != nil {
services.Logger.Fatal().Err(err).Msg("could not get solutions from storage")
}
// make a map of solutions by taskid
solutionsMap := make(map[task.TaskId]storage.TaskData)
for _, solution := range solutions {
solutionsMap[solution.TaskId] = solution
}
// get all commitments from storage
commitments, err := services.TaskStorage.GetAllCommitments()
if err != nil {
services.Logger.Fatal().Err(err).Msg("could not get commitments from storage")
}
// make a map of commitments by taskid
commitmentsMap := make(map[task.TaskId]storage.TaskData)
for _, commitment := range commitments {
commitmentsMap[commitment.TaskId] = commitment
}
services.Logger.Info().Int("total", len(allTasks)).Bool("dry_mode", dryMode).Msg("verifying all tasks")
var commitmentsToDelete []task.TaskId
var solutionsToDelete []task.TaskId
s := spinner.New(spinner.CharSets[11], 500*time.Millisecond, spinner.WithWriter(os.Stderr))
s.Suffix = " processing tasks..."
s.FinalMSG = "completed!\n"
s.Start()
totalItemstoProcess := len(allTasks)
deleted := 0
claimable := 0
tasksUpdated := 0
for index, v := range allTasks {
res, err := services.Engine.Engine.Solutions(nil, v.Taskid)
if err != nil {
services.Logger.Fatal().Err(err).Msg("error getting solution information")
}
if res.Blocktime > 0 {
// if the task is claimed, delete the task from storage and flag any commitments and solutions to delete
if res.Claimed {
// delete the task from storage
if !dryMode {
err := services.TaskStorage.DeleteTask(v.Taskid)
if err != nil {
services.Logger.Fatal().Err(err).Msg("could delete task data key")
}
}
deleted++
} else {
// if the task is not claimed, make sure the task is updated for claims
if !dryMode {
claimTime := time.Unix(int64(res.Blocktime), 0)
_, err = services.TaskStorage.UpsertTaskToClaimable(v.Taskid, common.Hash{}, claimTime)
if err != nil {
services.Logger.Error().Err(err).Msg("error updating task in storage")
} else {
tasksUpdated++
services.Logger.Info().Str("taskid", v.Taskid.String()).Int64("old_status", v.Status).Int64("new_status", 3).Msg("Task status updated to claimable.") // Status 3 is claimable
}
} else {
tasksUpdated++
services.Logger.Info().Str("taskid", v.Taskid.String()).Int64("old_status", v.Status).Int64("new_status", 3).Msg("Task status updated to claimable (dry run).") // Status 3 is claimable
}
}
// flag any commitments and solutions to delete
commitmentsToDelete = append(commitmentsToDelete, v.Taskid)
solutionsToDelete = append(solutionsToDelete, v.Taskid)
} else {
// No solution on-chain: Determine state based on local commitment and on-chain commitment
// We know we have a local solution because we are iterating through GetAllSolutions()
log.Printf("DEBUG: Task %s has no solution on-chain. Checking local/on-chain commitment...", v.Taskid.String())
// Initialize taskStatusToSet with the current status to only update if needed
taskStatusToSet := v.Status
shouldDeleteCommitment := false
shouldDeleteSolution := false
commitmentData, hasLocalCommitment := commitmentsMap[v.Taskid]
_, hasLocalSolution := solutionsMap[v.Taskid]
if !hasLocalCommitment {
// Case 1: No local commitment. Task needs to start over.
taskStatusToSet = 0
if hasLocalSolution {
// If there's an orphaned local solution without a commitment, delete it.
shouldDeleteSolution = true
services.Logger.Debug().Str("taskid", v.Taskid.String()).Msg("No local commitment, deleting orphaned local solution.")
} else {
services.Logger.Debug().Str("taskid", v.Taskid.String()).Msg("No local commitment, setting status to 0.")
}
} else {
// Case 2: Local commitment exists. Check its on-chain status and local solution presence.
isOnChainCommitment := false
if commitmentData.Commitment != [32]byte{} {
block, err := services.Engine.Engine.Commitments(nil, commitmentData.Commitment)
if err != nil {
services.Logger.Error().Err(err).Str("taskid", v.Taskid.String()).Msg("Error checking on-chain commitment status, skipping task update.")
continue // Skip update for this task if chain check fails
}
isOnChainCommitment = block.Uint64() > 0
} else {
// Commitment record exists locally but hash is zero - invalid state.
services.Logger.Warn().Str("taskid", v.Taskid.String()).Msg("Local commitment record found with zero hash, treating as invalid.")
// Treat as needing to start over.
taskStatusToSet = 0
shouldDeleteCommitment = true // Delete the invalid record
shouldDeleteSolution = true // Delete potentially related solution
}
if !hasLocalSolution {
// Case 2a: Local commitment, but no local solution. Need to regenerate both.
taskStatusToSet = 0
shouldDeleteCommitment = true // Delete stale commitment
services.Logger.Debug().Str("taskid", v.Taskid.String()).Bool("has_onchain_commitment", isOnChainCommitment).Msg("Local commitment found, but no local solution. Setting status to 0, deleting commitment.")
} else {
// Case 2b: Local commitment AND local solution exist.
if isOnChainCommitment {
// Subcase: Commitment is confirmed on-chain. Ready for solution submission.
taskStatusToSet = 2
shouldDeleteCommitment = true // Commitment is on-chain, remove local record
services.Logger.Debug().Str("taskid", v.Taskid.String()).Msg("Local commitment confirmed on-chain, local solution exists. Setting status to 2, deleting commitment record.")
} else {
// Subcase: Commitment is NOT yet on-chain. Local solution exists.
// This is a valid state (e.g., status 1, ready for commitment submission).
// DO NOT change status or delete local records.
services.Logger.Debug().Str("taskid", v.Taskid.String()).Msg("Local commitment NOT confirmed on-chain, local solution exists. State is valid, no changes needed.")
// Ensure flags are false and taskStatusToSet remains v.Status
shouldDeleteCommitment = false
shouldDeleteSolution = false
}
}
}
if !dryMode {
// Add to delete lists if flagged
if shouldDeleteCommitment {
commitmentsToDelete = append(commitmentsToDelete, v.Taskid)
}
if shouldDeleteSolution {
solutionsToDelete = append(solutionsToDelete, v.Taskid)
}
} else {
// log the changes that would be made e.g. we are deleting a commitment or solution
services.Logger.Debug().Str("taskid", v.Taskid.String()).Bool("delete_commitment", shouldDeleteCommitment).Bool("delete_solution", shouldDeleteSolution).Msg("Would delete commitment and/or solution")
}
// Update task status in storage only if it has changed
if taskStatusToSet != v.Status {
if !dryMode {
err = services.TaskStorage.AddOrUpdateTaskWithStatus(v.Taskid, v.Txhash, taskStatusToSet)
if err != nil {
services.Logger.Error().Err(err).Str("taskid", v.Taskid.String()).Int64("targetStatus", taskStatusToSet).Msg("Error updating task status in storage")
} else {
tasksUpdated++
services.Logger.Info().Str("taskid", v.Taskid.String()).Int64("old_status", v.Status).Int64("new_status", taskStatusToSet).Msg("Task status updated.")
}
} else {
tasksUpdated++
services.Logger.Info().Str("taskid", v.Taskid.String()).Int64("old_status", v.Status).Int64("new_status", taskStatusToSet).Msg("Task status updated (dry run).")
}
} else {
services.Logger.Debug().Str("taskid", v.Taskid.String()).Int64("status", v.Status).Msg("Task is already in the correct state.")
}
}
s.Suffix = fmt.Sprintf(" processing tasks [%d/%d] [deleted: %d] [claimable: %d] [updated: %d]\n", index+1, totalItemstoProcess, deleted, claimable, tasksUpdated) // Updated suffix
}
if len(commitmentsToDelete) > 0 {
services.Logger.Info().Int("commitments", len(commitmentsToDelete)).Msg("deleting commitments")
err := services.TaskStorage.DeleteProcessedCommitments(commitmentsToDelete)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting commitments from storage")
}
}
if len(solutionsToDelete) > 0 {
services.Logger.Info().Int("solutions", len(solutionsToDelete)).Msg("deleting solutions")
err := services.TaskStorage.DeleteProcessedSolutions(solutionsToDelete)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting solutions from storage")
}
}
s.Stop()
services.Logger.Info().Msg("completed verifying qall tasks ")
services.Logger.Info().Int("deleted", deleted).Msg("deleted tasks")
services.Logger.Info().Int("claimable", claimable).Msg("new claimable tasks")
services.Logger.Info().Int("updated", tasksUpdated).Msg("updated tasks (status)")
return nil
}
func verifySolutions(ctx context.Context) error {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
deleteCommitments := func(_commitmentsToDelete []task.TaskId) error {
const batchSize = 1000
if len(_commitmentsToDelete) > 0 {
/*err := services.TaskStorage.DeleteProcessedCommitments(_commitmentsToDelete)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting commitment(s) from storage")
return err
}
services.Logger.Warn().Msgf("deleted %d commitments from storage", len(_commitmentsToDelete))
*/
for i := 0; i < len(_commitmentsToDelete); i += batchSize {
end := i + batchSize
if end > len(_commitmentsToDelete) {
end = len(_commitmentsToDelete)
}
batch := _commitmentsToDelete[i:end]
err := services.TaskStorage.DeleteProcessedCommitments(batch)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting commitment(s) from storage")
return err
}
services.Logger.Warn().Msgf("deleted %d commitments from storage", len(batch))
}
}
return nil
}
deleteSolutions := func(_solutionsToDelete []task.TaskId) error {
const batchSize = 1000
if len(_solutionsToDelete) > 0 {
/*err := services.TaskStorage.DeleteProcessedSolutions(_solutionsToDelete)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting solution(s) from storage")
return err
}
services.Logger.Warn().Msgf("deleted %d solutions from storage", len(_solutionsToDelete))
*/
for i := 0; i < len(_solutionsToDelete); i += batchSize {
end := i + batchSize
if end > len(_solutionsToDelete) {
end = len(_solutionsToDelete)
}
batch := _solutionsToDelete[i:end]
err := services.TaskStorage.DeleteProcessedSolutions(batch)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting solution(s) from storage")
return err
}
services.Logger.Warn().Msgf("deleted %d solutions from storage", len(batch))
}
}
return nil
}
tasks, err := services.TaskStorage.GetAllSolutions()
if err != nil {
services.Logger.Err(err).Msg("failed to get tasks from storage")
}
commitments, err := services.TaskStorage.GetAllCommitments()
if err != nil {
services.Logger.Err(err).Msg("failed to get tasks from storage")
}
commitmentsMap := make(map[task.TaskId]storage.TaskData)
for _, commitment := range commitments {
commitmentsMap[commitment.TaskId] = commitment
}
services.Logger.Info().Int("solutions", len(tasks)).Msg("verifying solutions")
var commitmentsToDelete []task.TaskId
var solutionsToDelete []task.TaskId
solvedByMap := map[common.Address]int{}
s := spinner.New(spinner.CharSets[11], 500*time.Millisecond)
s.Suffix = " processing tasks..."
s.FinalMSG = "completed!\n"
s.Start()
totalItemstoProcess := len(tasks)
claimedAlready := 0
toClaim := 0
tasksUpdated := 0
for index, t := range tasks {
s.Suffix = fmt.Sprintf(" processing tasks [%d/%d]", index, totalItemstoProcess)
if t.Commitment != [32]byte{} {
// commitStr := task.TaskId(t.Commitment).String()
// // commitStr := task.
// tm.services.Logger.Info().Msgf("bulk submitting commitment: %s ", commitStr)
block, err := services.Engine.Engine.Commitments(nil, t.Commitment)
if err != nil {
services.Logger.Error().Err(err).Msg("error getting commitment")
continue
}
blockNo := block.Uint64()
if blockNo > 0 {
commitmentsToDelete = append(commitmentsToDelete, t.TaskId)
}
}
res, err := services.Engine.Engine.Solutions(nil, t.TaskId)
if err != nil {
services.Logger.Err(err).Msg("error getting solution information")
return nil
}
if res.Blocktime > 0 {
if res.Claimed {
claimedAlready++
services.Logger.Warn().Msgf("task %s was claimed by %s", t.TaskId.String(), res.Validator.String())
// delete the task from storage
err := services.TaskStorage.DeleteTask(t.TaskId)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting task from storage")
}
} else {
toClaim++
// update the task in storage with claim information
// set empty txhash as we know the task exists in and will be updated
claimTime := time.Unix(int64(res.Blocktime), 0)
_, err = services.TaskStorage.UpsertTaskToClaimable(t.TaskId, common.Hash{}, claimTime)
if err != nil {
services.Logger.Error().Err(err).Msg("error updating task in storage")
}
}
solvedByMap[res.Validator] = solvedByMap[res.Validator] + 1
// Flag we need to delete both the commitment and the solution
solutionsToDelete = append(solutionsToDelete, t.TaskId)
//commitmentsToDelete = append(commitmentsToDelete, t.TaskId)
} else {
// No solution on-chain: Determine state based on local commitment and on-chain commitment
// We know we have a local solution because we are iterating through GetAllSolutions()
log.Printf("DEBUG: Task %s has no solution on-chain. Checking local/on-chain commitment...", t.TaskId.String())
taskStatusToSet := int64(0) // Default: Requeue/Generate Commitment (Status 0)
shouldDeleteCommitment := false
shouldDeleteSolution := false
commitmentData, hasLocalCommitment := commitmentsMap[t.TaskId]
if !hasLocalCommitment {
// Case 1: Orphaned local solution (no local commitment). Task needs to start over.
taskStatusToSet = 0
shouldDeleteSolution = true
services.Logger.Debug().Str("taskid", t.TaskId.String()).Msg("Local solution found, but no local commitment. Setting status to 0, deleting solution.")
} else {
// Case 2: Local commitment exists. Check its on-chain status and local solution presence.
isOnChainCommitment := false
if commitmentData.Commitment != [32]byte{} {
block, err := services.Engine.Engine.Commitments(nil, commitmentData.Commitment)
if err != nil {
services.Logger.Error().Err(err).Str("taskid", t.TaskId.String()).Msg("Error checking on-chain commitment status, skipping task update.")
continue // Skip update for this task if chain check fails
}
isOnChainCommitment = block.Uint64() > 0
} else {
// Commitment record exists locally but hash is zero - invalid state.
services.Logger.Warn().Str("taskid", t.TaskId.String()).Msg("Local commitment record found with zero hash, treating as invalid.")
// Treat as needing to start over.
taskStatusToSet = 0
shouldDeleteCommitment = true // Delete the invalid record
shouldDeleteSolution = true // Delete the solution as well
}
// Determine status based on on-chain commitment presence
if isOnChainCommitment {
// Subcase: Commitment is confirmed on-chain. Ready for solution submission.
taskStatusToSet = 2
shouldDeleteCommitment = true // Commitment is on-chain, remove local record
services.Logger.Debug().Str("taskid", t.TaskId.String()).Msg("Local commitment confirmed on-chain, local solution exists. Setting status to 2, deleting commitment record.")
} else {
// Subcase: Commitment is NOT yet on-chain. Local solution exists.
// This is a valid state (e.g., status 1, ready for commitment submission).
// DO NOT change status or delete local records.
services.Logger.Debug().Str("taskid", t.TaskId.String()).Msg("Local commitment NOT confirmed on-chain, local solution exists. State is valid, no changes needed.")
continue
}
}
// Perform deletions if flagged
if shouldDeleteCommitment {
err = services.TaskStorage.DeleteProcessedCommitments([]task.TaskId{t.TaskId})
if err != nil {
log.Printf("WARN: Failed to delete local commitment for task %s: %v", t.TaskId.String(), err)
}
}
if shouldDeleteSolution {
err = services.TaskStorage.DeleteProcessedSolutions([]task.TaskId{t.TaskId})
if err != nil {
log.Printf("WARN: Failed to delete local solution for task %s: %v", t.TaskId.String(), err)
}
}
// Update task status in storage
err = services.TaskStorage.AddOrUpdateTaskWithStatus(t.TaskId, common.Hash{}, taskStatusToSet)
if err != nil {
log.Printf("WARN: Failed to add/update task %s to status %d: %v", t.TaskId.String(), taskStatusToSet, err)
} else {
log.Printf("Set task %s status to %d", t.TaskId.String(), taskStatusToSet)
tasksUpdated++ // Count as added/updated
}
}
}
s.Suffix = " deleting commitments"
if err := deleteCommitments(commitmentsToDelete); err != nil {
return nil
}
s.Suffix = " deleting solutions"
if err := deleteSolutions(solutionsToDelete); err != nil {
return nil
}
s.Stop()
for owner, v := range solvedByMap {
services.Logger.Info().Int("tasks", v).Str("val", owner.String()).Msg("solved tasks per validator")
}
services.Logger.Info().Int("tasks_updated", tasksUpdated).Msg("tasks updated to push solutions")
services.Logger.Info().Int("tasks_to_claim", toClaim).Msg("tasks to claim")
services.Logger.Info().Int("tasks_claimed_already", claimedAlready).Msg("tasks claimed already")
return nil
}
func verifyCommitment(ctx context.Context) error {
// Get the services from the context
services, ok := ctx.Value(servicesKey{}).(*Services)
if !ok {
log.Fatal("Could not get services from context")
}
deleteCommitments := func(_commitmentsToDelete []task.TaskId) error {
const batchSize = 1000
if len(_commitmentsToDelete) > 0 {
for i := 0; i < len(_commitmentsToDelete); i += batchSize {
end := i + batchSize
if end > len(_commitmentsToDelete) {
end = len(_commitmentsToDelete)
}
batch := _commitmentsToDelete[i:end]
err := services.TaskStorage.DeleteProcessedCommitments(batch)
if err != nil {
services.Logger.Error().Err(err).Msg("error deleting commitment(s) from storage")
return err
}
services.Logger.Warn().Msgf("deleted %d commitments from storage", len(batch))
}
}
return nil
}
deleteSolutions := func(_solutionsToDelete []task.TaskId) error {
const batchSize = 1000
if len(_solutionsToDelete) > 0 {
for i := 0; i < len(_solutionsToDelete); i += batchSize {