newton-chainio 0.5.2

newton prover chainio
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
use alloy::primitives::{FixedBytes, Uint, U256};
use ark_bn254::{G1Affine, G2Affine};
use ark_ec::AffineRepr;
use async_trait::async_trait;
use eigensdk::{
    crypto_bls::{BlsG1Point, BlsG2Point, Signature},
    crypto_bn254::utils::verify_message,
    services_avsregistry::AvsRegistryService,
    types::{
        avs::{SignatureVerificationError, TaskResponseDigest},
        avs_state::OperatorAvsState,
        operator::{QuorumThresholdPercentage, QuorumThresholdPercentages},
    },
};
use newton_core::{newton_prover_task_manager::IBLSSignatureCheckerTypes, TaskId};
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
    time::Instant,
};
use tokio::{
    sync::{
        mpsc::{self, UnboundedReceiver, UnboundedSender},
        oneshot,
    },
    time::Duration,
};
use tracing::{debug, error, field, info, instrument, trace, warn};

/// Contains the aggregated operators signers information
#[derive(Debug, Clone)]
pub struct AggregatedOperators {
    signers_apk_g2: BlsG2Point,
    signers_agg_sig_g1: Signature,
    signers_total_stake_per_quorum: HashMap<u8, U256>,
    /// Contains the set of operator IDs that have signed the aggregated signature
    pub signers_operator_ids_set: HashMap<FixedBytes<32>, bool>,
}

/// Contains the metadata required to initialize a new task.
#[derive(Debug, Clone)]
pub struct TaskMetadata {
    /// Task ID
    pub task_id: TaskId,
    /// Quorum numbers which should respond to the task
    quorum_numbers: Vec<u8>,
    /// Thresholds for each quorum
    quorum_threshold_percentages: QuorumThresholdPercentages,
    /// Time before expiry of the task response aggregation
    time_to_expiry: Duration,
    // Duration of the window to wait for signatures after quorum is reached
    window_duration: Duration,
    /// Task created block
    task_created_block: u64,
}

impl TaskMetadata {
    /// Creates a new instance of [`TaskMetadata`]
    ///
    /// # Arguments
    ///
    /// * `task_id` - task ID
    /// * `quorum_numbers` - quorum numbers which should respond to the task
    /// * `quorum_threshold_percentages` - threshold percentages for each quorum
    /// * `time_to_expiry` - time until the task expires
    /// * `task_created_block` - block number when the task was created
    ///
    /// Use [`with_window_duration`](Self::with_window_duration) to set the window duration.
    /// If the window duration is not set, it will default to [`Duration::ZERO`].
    ///
    /// # Returns
    ///
    /// A new instance of [`TaskMetadata`]
    pub fn new(
        task_id: TaskId,
        task_created_block: u64,
        quorum_numbers: Vec<u8>,
        quorum_threshold_percentages: QuorumThresholdPercentages,
        time_to_expiry: Duration,
    ) -> Self {
        Self {
            task_id,
            task_created_block,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
            window_duration: Duration::ZERO,
        }
    }

    /// Sets the window duration for the task
    ///
    /// # Arguments
    /// * `window_duration` - The duration of the window to wait for signatures after quorum is reached
    ///
    /// # Returns
    ///
    /// An instance of [`TaskMetadata`] with the window duration set
    pub fn with_window_duration(mut self, window_duration: Duration) -> Self {
        self.window_duration = window_duration;
        self
    }
}

/// Contains the information of a signed task response
#[derive(Debug, Clone)]
pub struct TaskSignature {
    // Task ID
    task_id: TaskId,
    // Digest of the task response
    task_response_digest: TaskResponseDigest,
    // BLS signature of the task response
    bls_signature: Signature,
    // Operator ID of the operator that signed the task response
    operator_id: FixedBytes<32>,
}

impl TaskSignature {
    /// Creates a new instance of [`TaskSignature``]
    ///
    /// # Arguments
    /// * `task_id` - task ID
    /// * `task_response_digest` - digest of the task response
    /// * `bls_signature` - bls signature of the task response
    /// * `operator_id` - operator ID of the operator that signed the task response
    ///
    /// # Returns
    ///
    /// [`TaskSignature`] instance
    pub fn new(
        task_id: TaskId,
        task_response_digest: TaskResponseDigest,
        bls_signature: Signature,
        operator_id: FixedBytes<32>,
    ) -> Self {
        Self {
            task_id,
            task_response_digest,
            bls_signature,
            operator_id,
        }
    }
}

/// The response from the BLS aggregation service
#[allow(unused)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlsAggregationServiceResponse {
    /// Task ID
    pub task_id: TaskId,
    /// Task created block
    pub task_created_block: u64,
    /// Task response digest
    pub task_response_digest: TaskResponseDigest,
    /// Number of operators who signed this response
    pub signers_count: usize,
    /// Non-signers public keys
    pub non_signers_pub_keys_g1: Vec<BlsG1Point>,
    /// Non-signer operator IDs (sorted, for efficient index updates)
    pub non_signers_operators_ids: Vec<FixedBytes<32>>,
    /// Quorum APKs
    pub quorum_apks_g1: Vec<BlsG1Point>,
    /// Signers APK
    pub signers_apk_g2: BlsG2Point,
    /// Signers aggregated signature
    pub signers_agg_sig_g1: Signature,
    /// Non-signer quorum bitmap indices
    pub non_signer_quorum_bitmap_indices: Vec<u32>,
    /// Quorum APK indices
    pub quorum_apk_indices: Vec<u32>,
    /// Total stake indices
    pub total_stake_indices: Vec<u32>,
    /// Non-signer stake indices
    pub non_signer_stake_indices: Vec<Vec<u32>>,
}

use thiserror::Error;

use crate::avs::AvsRegistryServiceCaller;

/// Reason for task expiry
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskExpiryReason {
    /// Task expired because quorum was already met and task finished successfully
    /// This is expected when multiple operators respond after quorum threshold is met
    QuorumMet,
    /// Task expired without reaching quorum threshold
    QuorumNotMet,
    /// Task expired while window was open but no aggregated response available
    WindowOpenNoResponse,
    /// Window finished but no aggregated response available
    WindowFinishedNoResponse,
}

impl std::fmt::Display for TaskExpiryReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TaskExpiryReason::QuorumMet => write!(f, "task already finished (quorum reached and window closed)"),
            TaskExpiryReason::QuorumNotMet => write!(f, "task expired without reaching quorum threshold"),
            TaskExpiryReason::WindowOpenNoResponse => write!(
                f,
                "task expired while window was open but no aggregated response available"
            ),
            TaskExpiryReason::WindowFinishedNoResponse => {
                write!(f, "window finished but no aggregated response available")
            }
        }
    }
}

/// Reason for receiver error
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReceiverErrorReason {
    /// Oneshot receiver closed - can occur when task finished (quorum met) or service error
    OneshotReceiverClosed,
    /// Aggregate response channel closed
    AggregateChannelClosed,
}

impl std::fmt::Display for ReceiverErrorReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReceiverErrorReason::OneshotReceiverClosed => write!(f, "oneshot receiver closed"),
            ReceiverErrorReason::AggregateChannelClosed => write!(f, "aggregate response channel closed"),
        }
    }
}

/// Possible errors raised in BLS aggregation
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum BlsAggregationServiceError {
    /// Task expired error
    #[error("task {task_id} expired: {reason}")]
    TaskExpired {
        /// The task ID that expired
        task_id: TaskId,
        /// Reason for expiry
        reason: TaskExpiryReason,
    },
    /// Task not found error
    #[error("task {task_id} not found: {reason}")]
    TaskNotFound {
        /// The task ID that was not found
        task_id: TaskId,
        /// Reason why task was not found (e.g., "task not initialized yet", "task was evicted", "task never created")
        reason: String,
    },
    /// Signature verification error. Wraps the error from the [`SignatureVerificationError`] enum.
    #[error("signature verification failed for task {task_id}, operator {operator_id}: {verification_error}")]
    SignatureVerificationError {
        /// The task ID associated with the signature
        task_id: TaskId,
        /// The operator ID whose signature failed verification
        operator_id: FixedBytes<32>,
        /// The specific verification error
        verification_error: SignatureVerificationError,
    },
    /// Signature channel closed error
    #[error("signatures channel closed for task {task_id}: {reason}")]
    SignaturesChannelClosed {
        /// The task ID whose channel was closed
        task_id: TaskId,
        /// Reason why channel closed (e.g., "task aggregator finished", "task expired", "receiver dropped")
        reason: String,
    },
    /// AVS registry error
    #[error("AVS registry error for task {task_id}{operator_context}: {reason}")]
    RegistryError {
        /// The task ID associated with the registry error
        task_id: TaskId,
        /// Additional context about the operator if applicable (e.g., " from operator 0x1234...")
        operator_context: String,
        /// The specific reason for the registry error (e.g., "failed to get operator AVS state", "operator public keys not found")
        reason: String,
    },
    /// Duplicate task id error
    #[error("duplicate task id {task_id}: {reason}")]
    DuplicateTaskId {
        /// The task ID that was duplicated
        task_id: TaskId,
        /// Reason for duplicate (e.g., "task already initialized", "task already exists in task_channels")
        reason: String,
    },
    /// Sending to service error
    #[error("error sending {operation} message to service for task {task_id}{operator_context}: {reason}")]
    SenderError {
        /// The operation that failed (e.g., "InitializeTask", "ProcessSignature")
        operation: String,
        /// The task ID associated with the failed operation
        task_id: TaskId,
        /// Additional context about the operator if applicable (e.g., " from operator 0x1234...")
        operator_context: String,
        /// The specific reason for the failure (e.g., "channel closed: ...")
        reason: String,
    },
    /// Receiving from service error
    #[error("error receiving {operation} response from service for task {task_id}{operator_context}: {reason}")]
    ReceiverError {
        /// The operation that failed (e.g., "InitializeTask", "ProcessSignature")
        operation: String,
        /// The task ID associated with the failed operation
        task_id: TaskId,
        /// Additional context about the operator if applicable (e.g., " from operator 0x1234...")
        operator_context: String,
        /// The specific reason for the failure
        reason: ReceiverErrorReason,
    },
}

/// Valid messages to interact with the BLS Aggregator Service
#[derive(Debug)]
pub enum AggregationMessage {
    /// Initialize a new task
    /// Returns both initialization result and task-specific response receiver
    InitializeTask(
        TaskMetadata,
        oneshot::Sender<
            Result<
                UnboundedReceiver<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
                BlsAggregationServiceError,
            >,
        >,
    ),
    /// Process a signature
    ProcessSignature(TaskSignature, oneshot::Sender<Result<(), BlsAggregationServiceError>>),
    /// Cancel a task's aggregation loop without removing task_states.
    /// Drops the signature channel sender, causing the background loop to exit
    /// via "signature channel closed". Used when the two-phase path completes
    /// successfully and the background timeout loop is no longer needed.
    CancelAggregationLoop(TaskId),
}

#[async_trait]
/// A trait for handling BLS aggregation service messages
pub trait BlsServiceHandle: Send + Sync {
    /// Sends a message to the BLS Aggregator Service to initialize a new task.
    async fn initialize_task(
        &self,
        metadata: TaskMetadata,
    ) -> Result<
        UnboundedReceiver<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
        BlsAggregationServiceError,
    >;

    /// Sends a message to the BLS Aggregator Service to process a signature.
    async fn process_signature(&self, task_signature: TaskSignature) -> Result<(), BlsAggregationServiceError>;

    /// Cancel a task's background aggregation loop without removing task_states.
    /// Drops the signature channel, causing the spawned loop to exit cleanly.
    fn cancel_aggregation_loop(&self, task_id: TaskId);
}

/// Handler to interact with the BLS Aggregator Service
#[derive(Debug, Clone)]
pub struct ServiceHandle {
    /// Channel to send messages to the BLS Aggregator Service
    msg_sender: UnboundedSender<AggregationMessage>,
}

#[async_trait]
impl BlsServiceHandle for ServiceHandle {
    /// Sends a message to the BLS Aggregator Service to initialize a new task.
    ///
    /// # Arguments
    ///
    /// * `metadata` - The metadata of the task to initialize
    ///
    /// # Returns
    ///
    /// Returns error if the task index already exists
    #[instrument(skip(self), fields(task_id = %metadata.task_id, quorum_count = metadata.quorum_numbers.len()))]
    async fn initialize_task(
        &self,
        metadata: TaskMetadata,
    ) -> Result<
        UnboundedReceiver<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
        BlsAggregationServiceError,
    > {
        let start_time = std::time::Instant::now();
        info!(
            "[ServiceHandle] initializing task {} with {} quorums, expires in {} ms",
            metadata.task_id,
            metadata.quorum_numbers.len(),
            metadata.time_to_expiry.as_millis()
        );
        debug!(
            "[ServiceHandle] task {} details - quorums: {}, thresholds: {}, window: {} ms",
            metadata.task_id,
            String::from_utf8(metadata.quorum_numbers.clone()).unwrap_or_default(),
            String::from_utf8(metadata.quorum_threshold_percentages.clone()).unwrap_or_default(),
            metadata.window_duration.as_millis()
        );

        let (tx, rx) = oneshot::channel();
        if let Err(e) = self
            .msg_sender
            .send(AggregationMessage::InitializeTask(metadata.clone(), tx))
        {
            let reason = format!("channel closed: {:?}", e);
            error!(
                "[ServiceHandle] failed to send InitializeTask message for task {}: {}",
                metadata.task_id, reason
            );
            return Err(BlsAggregationServiceError::SenderError {
                operation: "InitializeTask".to_string(),
                task_id: metadata.task_id,
                operator_context: String::new(),
                reason,
            });
        }

        let response_receiver = rx.await.map_err(|e| {
            error!(
                "[ServiceHandle] failed to receive InitializeTask response for task {}: oneshot receiver closed: {:?}",
                metadata.task_id, e
            );
            BlsAggregationServiceError::ReceiverError {
                operation: "InitializeTask".to_string(),
                task_id: metadata.task_id,
                operator_context: String::new(),
                reason: ReceiverErrorReason::OneshotReceiverClosed,
            }
        })?;

        let duration = start_time.elapsed();
        match &response_receiver {
            Ok(_) => info!(
                "[ServiceHandle] task {} initialization completed in {} ms",
                metadata.task_id,
                duration.as_millis()
            ),
            Err(e) => error!(
                "[ServiceHandle] task {} initialization failed in {} ms: {}",
                metadata.task_id,
                duration.as_millis(),
                e.to_string()
            ),
        }

        response_receiver
    }

    /// Sends a message to the BLS Aggregator Service to process a signature.
    ///
    /// # Arguments
    ///
    /// * `task_signature` - The signed task response
    ///
    /// # Returns error:
    ///
    /// * `TaskNotFound` - If the task is not found
    /// * `ChannelError` - If there is an error while sending the task through the channel
    /// * `SignatureVerificationError` - If the signature verification fails
    #[instrument(skip(self, task_signature), fields(
        task_id = %task_signature.task_id,
        operator_id = %hex!(task_signature.operator_id.as_slice())
    ))]
    async fn process_signature(&self, task_signature: TaskSignature) -> Result<(), BlsAggregationServiceError> {
        let start_time = std::time::Instant::now();
        let operator_id_hex = hex!(task_signature.operator_id.as_slice());
        debug!(
            "[ServiceHandle] processing signature from operator {} for task {}",
            operator_id_hex, task_signature.task_id
        );
        debug!(
            "[ServiceHandle] signature details - task_response_digest: {}, signature: {:?}",
            hex!(task_signature.task_response_digest),
            task_signature.bls_signature
        );

        let (tx, rx) = oneshot::channel();
        if let Err(e) = self
            .msg_sender
            .send(AggregationMessage::ProcessSignature(task_signature.clone(), tx))
        {
            let reason = format!("channel closed: {:?}", e);
            error!(
                "[ServiceHandle] failed to send ProcessSignature message for task {} from operator {}: {}",
                task_signature.task_id, operator_id_hex, reason
            );
            return Err(BlsAggregationServiceError::SenderError {
                operation: "ProcessSignature".to_string(),
                task_id: task_signature.task_id,
                operator_context: format!(" from operator {}", operator_id_hex),
                reason,
            });
        }

        // Wait for result from BLS service
        // The oneshot receiver closure can occur in these scenarios:
        // 1. BLS service main loop crashes/panics before processing the message
        // 2. BLS service is shutting down and stops processing messages
        // 3. Task aggregator finishes before processing (handled by sending TaskExpired error)
        // 4. Unexpected error in message processing (should be handled by sending error)
        //
        // Resilience: This error is returned to the caller, allowing them to retry or handle gracefully
        // The BLS service main loop continues processing other messages, ensuring system-wide resilience
        let result = rx.await.map_err(|e| {
            error!(
                "[ServiceHandle] failed to receive ProcessSignature response for task {} from operator {}: oneshot receiver closed: {:?}",
                task_signature.task_id, operator_id_hex, e
            );
            BlsAggregationServiceError::ReceiverError {
                operation: "ProcessSignature".to_string(),
                task_id: task_signature.task_id,
                operator_context: format!(" from operator {}", operator_id_hex),
                reason: ReceiverErrorReason::OneshotReceiverClosed,
            }
        })?;

        let duration = start_time.elapsed();
        match &result {
            Ok(_) => info!(
                "[ServiceHandle] signature from operator {} for task {} processed in {} ms",
                operator_id_hex,
                task_signature.task_id,
                duration.as_millis()
            ),
            Err(e) => warn!(
                "[ServiceHandle] signature from operator {} for task {} failed in {} ms: {}",
                operator_id_hex,
                task_signature.task_id,
                duration.as_millis(),
                e.to_string()
            ),
        }

        result
    }

    fn cancel_aggregation_loop(&self, task_id: TaskId) {
        debug!(%task_id, "[ServiceHandle] sending CancelAggregationLoop");
        if let Err(e) = self.msg_sender.send(AggregationMessage::CancelAggregationLoop(task_id)) {
            warn!(
                %task_id,
                "[ServiceHandle] failed to send CancelAggregationLoop: channel closed: {:?}", e
            );
        }
    }
}

/// Receiver to receive the aggregated responses from the BLS Aggregator Service.
#[derive(Debug)]
pub struct AggregateReceiver {
    /// Channel to receive the aggregated responses from the BLS Aggregator Service
    aggregate_receiver: UnboundedReceiver<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
}

impl AggregateReceiver {
    /// Receives the aggregated response from the BLS Aggregator Service.
    ///
    /// # Returns
    ///
    /// Returns the aggregated response or an error if the channel is closed.
    #[instrument(skip(self))]
    pub async fn receive_aggregated_response(
        &mut self,
    ) -> Result<BlsAggregationServiceResponse, BlsAggregationServiceError> {
        debug!("[AggregateReceiver] waiting for aggregated response...");
        let start_time = std::time::Instant::now();

        match self.aggregate_receiver.recv().await {
            Some(Ok(response)) => {
                let duration = start_time.elapsed();
                info!(
                    "[AggregateReceiver] received successful aggregated response for task {} in {} ms",
                    response.task_id,
                    duration.as_millis()
                );
                debug!(
                    "[AggregateReceiver] response details - non-signer keys: {}",
                    response.non_signers_pub_keys_g1.len()
                );
                Ok(response)
            }
            Some(Err(e)) => {
                let duration = start_time.elapsed();
                error!(
                    "[AggregateReceiver] received error response in {} ms: {}",
                    duration.as_millis(),
                    e.to_string()
                );
                Err(e)
            }
            None => {
                let duration = start_time.elapsed();
                warn!(
                    "[AggregateReceiver] aggregate response channel closed after waiting {} ms",
                    duration.as_millis()
                );
                Err(BlsAggregationServiceError::ReceiverError {
                    operation: "ReceiveAggregatedResponse".to_string(),
                    task_id: TaskId::default(), // Unknown task_id when channel closes
                    operator_context: String::new(),
                    reason: ReceiverErrorReason::AggregateChannelClosed,
                })
            }
        }
    }
}

/// Type alias for task channel entries: (signature_sender, response_sender, timestamp)
/// Response channel is task-specific for direct routing (no mutex contention)
type TaskChannelEntry = (
    UnboundedSender<SignedTaskResponseDigest>,
    UnboundedSender<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
    Instant,
);

/// The BLS Aggregator Service main struct
#[derive(Debug)]
pub struct BlsAggregatorService<A: AvsRegistryService>
where
    A: Clone,
{
    avs_registry_service: A,
}

/// Represents a signed task response digest
#[derive(Debug)]
struct SignedTaskResponseDigest {
    task_response_digest: TaskResponseDigest,

    bls_signature: Signature,

    operator_id: FixedBytes<32>,

    result_channel: oneshot::Sender<Result<(), BlsAggregationServiceError>>,
}

impl<A: AvsRegistryService + Send + Sync + Clone + 'static> BlsAggregatorService<A> {
    /// Creates a new instance of the BlsAggregatorService with the given AVS registry service
    ///
    /// Creates a tokio unbounded_channel to send and received aggregated responses.
    ///
    /// # Arguments
    ///
    /// * `avs_registry_service` - The AVS registry service
    pub fn new(avs_registry_service: A) -> Self {
        info!("[BlsAggregatorService] creating new BLS aggregator service");
        Self { avs_registry_service }
    }

    /// Starts the BLS Aggregator Service running the main loop in background.
    ///
    /// # Returns
    ///
    /// Returns a tuple with the [`ServiceHandle`] and [`AggregateReceiver`] to interact with the service
    #[instrument(skip(self))]
    pub fn start(self) -> (ServiceHandle, AggregateReceiver) {
        info!("[BlsAggregatorService] starting BLS aggregator service");
        let (msg_tx, msg_rx) = mpsc::unbounded_channel();
        let (agg_tx, agg_rx) = mpsc::unbounded_channel();

        debug!("[BlsAggregatorService] created communication channels");

        tokio::spawn(async move {
            info!("[BlsAggregatorService] spawning main service loop");
            self.run(msg_rx, agg_tx).await;
            warn!("[BlsAggregatorService] main service loop ended");
        });

        // Create service handler and aggregate receiver to user can interact with the service
        let service_handler = ServiceHandle { msg_sender: msg_tx };
        let aggregate_receiver = AggregateReceiver {
            aggregate_receiver: agg_rx,
        };

        info!("[BlsAggregatorService] service started successfully");
        (service_handler, aggregate_receiver)
    }

    /// Maximum number of active tasks allowed in task_channels to prevent memory leaks.
    /// When this limit is reached, tasks older than 120 seconds are evicted first,
    /// then the oldest remaining task if still over the limit.
    const MAX_ACTIVE_TASKS: usize = 10000;
    /// Maximum number of different response digests per task in aggregated_operators to prevent memory bloat.
    /// When this limit is reached, oldest entries are evicted (FIFO).
    const MAX_AGGREGATED_OPERATORS_PER_TASK: usize = 100;

    /// Runs the main loop of the BLS Aggregator Service.
    ///
    /// This function continuously processes messages from `msg_receiver` and handles:
    /// * [`InitializeTask`]: Initializes a new aggregation task
    /// * [`ProcessSignature`]: Forwards a signature to the appropriate task aggregator and relays the verification result.
    ///
    /// The final aggregated response is sent through the `aggregate_sender` channel. In addition, each
    /// message (both [`InitializeTask`] and [`ProcessSignature`]) uses its own channel to return specific errors or results.
    ///
    /// # Arguments
    ///
    /// * `msg_receiver` - The receiver channel to receive the valid messages
    /// * `aggregate_sender` - The sender channel to send the aggregated responses
    #[instrument(skip(self, msg_receiver, aggregate_sender))]
    async fn run(
        self,
        mut msg_receiver: UnboundedReceiver<AggregationMessage>,
        aggregate_sender: UnboundedSender<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
    ) {
        info!("[BlsAggregatorService] main service loop started");
        // Store signature channel sender, response channel sender, and creation timestamp
        // Response channel is task-specific for direct routing (no mutex contention)
        let mut task_channels: HashMap<TaskId, TaskChannelEntry> = HashMap::new();
        // Track finished tasks to distinguish from never-initialized tasks
        // This allows returning TaskExpired instead of TaskNotFound for finished tasks
        let mut finished_tasks: HashSet<TaskId> = HashSet::new();
        let mut message_count = 0u64;
        let mut active_tasks = 0u32;

        // Proactive cleanup channel: task aggregators notify main loop when they complete
        // This enables O(1) cleanup per task instead of waiting for eviction or ProcessSignature
        let (cleanup_tx, mut cleanup_rx) = mpsc::unbounded_channel::<TaskId>();

        // Main loop with comprehensive error handling to ensure service resilience
        // Key resilience features:
        // 1. Message channel closure handled gracefully (clean shutdown)
        // 2. Oneshot senders always sent (prevents receiver closure errors)
        // 3. Task isolation (errors in one task don't affect others)
        // 4. Automatic cleanup on errors (prevents resource leaks)
        // 5. Proactive cleanup on task completion (O(1) per task, prevents memory bloat)
        loop {
            tokio::select! {
                message = msg_receiver.recv() => {
                    let message = match message {
                        Some(msg) => msg,
                        None => {
                            // Message channel closed - log and exit gracefully
                            // This prevents the service from hanging indefinitely if the channel closes
                            //
                            // Why we clear task_channels:
                            // 1. Service shutdown: When msg_receiver closes, it means the service is shutting down
                            //    (the sender side was dropped, typically during graceful shutdown)
                            // 2. Signal to task aggregators: Dropping signature_tx closes the signature channels,
                            //    which causes task aggregators to see signatures_rx.recv() return None
                            // 3. Graceful exit: Task aggregators handle channel closure gracefully (line 1151-1152),
                            //    sending final responses if quorum reached, then exiting
                            // 4. Prevent memory leaks: Without clearing, we'd keep references to channels that
                            //    are no longer needed (service is shutting down anyway)
                            // 5. No new messages: Since msg_receiver is closed, we can't process new InitializeTask
                            //    or ProcessSignature messages, so maintaining task_channels serves no purpose
                            //
                            // Note: The spawned task aggregators continue running independently and will:
                            // - Detect signature channel closure (signatures_rx.recv() returns None)
                            // - Send final aggregated response if quorum was reached
                            // - Exit gracefully without affecting other tasks
                            warn!(
                                "[BlsAggregatorService] message channel closed, shutting down main loop (processed {} messages, {} active tasks)",
                                message_count,
                                active_tasks
                            );
                            // Clear task_channels to signal shutdown and prevent resource leaks
                            // This closes signature channels, causing task aggregators to exit gracefully
                            task_channels.clear();
                            break;
                        }
                    };

                    // Process message (message is already Some(msg) from the match above)
                    message_count += 1;
                    trace!(
                        "[BlsAggregatorService] processing message #{} (active tasks: {})",
                        message_count,
                        active_tasks
                    );

                    // Wrap message processing in error handling to prevent one error from stopping the service
                    // and ensure the main loop continues even if individual message processing fails
                    // Oneshot senders are ALWAYS sent (success or error) to prevent receiver closure
                    match message {
                        AggregationMessage::InitializeTask(metadata, result_sender) => {
                            // Ensure result_sender is always sent to prevent receiver closure errors
                            // If the oneshot sender is dropped without sending, the receiver sees closure and returns an error
                            // This can happen if the service panics or crashes before processing the message
                            let task_id = metadata.task_id;

                            // Process initialization - keep original structure but ensure oneshot is always sent
                            info!(
                                "[BlsAggregatorService] received InitializeTask for task {} (message #{})",
                                task_id, message_count
                            );

                            if task_channels.contains_key(&task_id) {
                                // Task already exists - send error and continue (oneshot sent, prevents receiver closure)
                                let _ = result_sender.send(Err(BlsAggregationServiceError::DuplicateTaskId {
                                    task_id,
                                    reason: format!("task already exists in task_channels (message #{})", message_count),
                                }));
                                continue;
                            }

                            // Create channels: one for signatures, one for task-specific responses
                            let (signature_tx, signature_rx) = mpsc::unbounded_channel::<SignedTaskResponseDigest>();
                            let (response_tx, response_rx) =
                                mpsc::unbounded_channel::<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>();

                            // Store both channels and return response receiver to caller
                            task_channels.insert(task_id, (signature_tx, response_tx.clone(), Instant::now()));
                            active_tasks += 1;

                            // Return response receiver to caller via oneshot - ALWAYS send to prevent receiver closure
                            if result_sender.send(Ok(response_rx)).is_err() {
                                warn!(
                                    "[BlsAggregatorService] failed to send response receiver for task {} (caller dropped)",
                                    task_id
                                );
                                // Clean up since caller won't receive the channel
                                task_channels.remove(&task_id);
                                active_tasks = active_tasks.saturating_sub(1);
                                continue;
                            }

                            // Spawn task aggregator - we still have signature_rx and response_tx available here
                            let avs_registry_service = self.avs_registry_service.clone();
                            // Use task-specific response sender instead of shared aggregate_sender
                            let task_response_sender = response_tx;

                            // Spawn task aggregator - errors in one task don't affect others
                            // tokio::spawn automatically catches panics and converts them to JoinError
                            let cleanup_tx_clone = cleanup_tx.clone();
                            let join_handle = tokio::spawn(async move {
                                let result = Self::single_task_aggregator(
                                    avs_registry_service,
                                    metadata,
                                    task_response_sender,
                                    signature_rx,
                                )
                                .await;

                                match result {
                                    Ok(()) => {
                                        info!(
                                            task_id = %task_id,
                                            "[BlsAggregatorService] task aggregator finished successfully"
                                        );
                                    }
                                    Err(e) => {
                                        error!(
                                            task_id = %task_id,
                                            error = %e,
                                            "[BlsAggregatorService] task aggregator finished with error"
                                        );
                                    }
                                }

                                // Proactive cleanup: Notify main loop that this task has completed
                                // This enables O(1) cleanup per task instead of waiting for eviction or ProcessSignature
                                // If cleanup_tx is dropped (service shutdown), ignore the error
                                let _ = cleanup_tx_clone.send(task_id);
                            });

                            // Spawn a monitor task to log panics if they occur (without blocking the main loop)
                            let task_id_for_monitor = task_id;
                            tokio::spawn(async move {
                                if let Err(e) = join_handle.await {
                                    error!(
                                        task_id = %task_id_for_monitor,
                                        error = ?e,
                                        "[BlsAggregatorService] task aggregator panicked or was cancelled"
                                    );
                                }
                            });
                        }
                        AggregationMessage::ProcessSignature(task_signature, result_sender) => {
                            // Ensure result_sender is always sent to prevent receiver closure errors
                            // The oneshot is passed to the task aggregator via result_channel
                            // The task aggregator will send the result (success or error) via this channel
                            // If the task aggregator channel is closed, we send TaskExpired error
                            // If the task is not found, we send TaskNotFound error
                            // This ensures the receiver never sees closure - it always gets a result
                            let task_id = task_signature.task_id;

                            // Process signature - ensure oneshot is sent in all code paths
                            if let Some((sig_sender, _response_tx, _)) = task_channels.get_mut(&task_signature.task_id) {
                                // Send the signed task response to the task aggregator
                                // The oneshot (result_sender) is passed to the task aggregator
                                // Task aggregator will send result via result_channel (handles receiver drop gracefully)
                                let signed_digest = SignedTaskResponseDigest {
                                    task_response_digest: task_signature.task_response_digest,
                                    bls_signature: task_signature.bls_signature,
                                    operator_id: task_signature.operator_id,
                                    result_channel: result_sender, // Pass oneshot to task aggregator - it will send result
                                };

                                debug!(
                                    "[BlsAggregatorService] sending signed task response digest to task aggregator for task {}",
                                    task_signature.task_id
                                );

                                if let Err(send_error) = sig_sender.send(signed_digest) {
                                    // Channel closed - task aggregator has finished, remove from task_channels
                                    warn!(
                                        "[BlsAggregatorService] task {} aggregator channel closed (task finished), removing from task_channels",
                                        task_signature.task_id
                                    );
                                    task_channels.remove(&task_signature.task_id);
                                    active_tasks = active_tasks.saturating_sub(1);
                                    // Mark task as finished to distinguish from never-initialized tasks
                                    finished_tasks.insert(task_signature.task_id);

                                    error!(
                                        "[BlsAggregatorService] failed to send signed task response digest to task aggregator for task {}: task already finished",
                                        task_signature.task_id
                                    );
                                    // Send error via oneshot - ensures receiver doesn't see closure
                                    let _ = send_error
                                        .0
                                        .result_channel
                                        .send(Err(BlsAggregationServiceError::TaskExpired {
                                            task_id: task_signature.task_id,
                                            reason: TaskExpiryReason::QuorumMet,
                                        }));
                                }
                                // Note: If send succeeded, result_sender is passed to task aggregator
                                // Task aggregator will send result (success or error) via result_channel
                            } else {
                                // Task not found - check if it was finished or never initialized
                                if finished_tasks.contains(&task_signature.task_id) {
                                    // Task was finished (quorum reached, window closed, etc.)
                                    warn!(
                                        "[BlsAggregatorService] task {} not found in task_channels - task already finished",
                                        task_signature.task_id
                                    );
                                    // Always send error to prevent receiver closure
                                    let _ = result_sender.send(Err(BlsAggregationServiceError::TaskExpired {
                                        task_id: task_signature.task_id,
                                        reason: TaskExpiryReason::QuorumMet,
                                    }));
                                } else {
                                    // Task never initialized
                                    warn!(
                                        "[BlsAggregatorService] task {} not found in task_channels for signature processing (task may not be initialized yet or was never created)",
                                        task_signature.task_id
                                    );
                                    // Always send error to prevent receiver closure
                                    let _ = result_sender.send(Err(BlsAggregationServiceError::TaskNotFound {
                                        task_id: task_signature.task_id,
                                        reason:
                                            "task not found in task_channels (task may not be initialized yet or was never created)"
                                                .to_string(),
                                    }));
                                }
                            }
                        }
                        AggregationMessage::CancelAggregationLoop(task_id) => {
                            if task_channels.remove(&task_id).is_some() {
                                active_tasks = active_tasks.saturating_sub(1);
                                finished_tasks.insert(task_id);
                                debug!(
                                    %task_id,
                                    "[BlsAggregatorService] cancelled aggregation loop (two-phase completed)"
                                );
                            }
                        }
                    }
                }
                completed_task_id = cleanup_rx.recv() => {
                    // Proactive cleanup: Remove completed task from task_channels and mark as finished
                    // This happens immediately when task aggregator finishes (success or error)
                    // O(1) operation - no HashMap scans needed
                    if let Some(task_id) = completed_task_id {
                        if task_channels.remove(&task_id).is_some() {
                            active_tasks = active_tasks.saturating_sub(1);
                            // Mark task as finished to distinguish from never-initialized tasks
                            finished_tasks.insert(task_id);
                            trace!(
                                "[BlsAggregatorService] proactively cleaned up completed task {} (remaining: {})",
                                task_id,
                                active_tasks
                            );
                        }
                    }
                }
            }
        }
    }

    /// Processes each signed task responses given a task_id for a single task.
    ///
    /// It reads the signed task responses from the receiver channel and aggregates them.
    /// * If the quorum threshold is met, it sends the aggregated response to the aggregated response sender.
    /// * If the time to expiry is reached, it sends a task expired error to the aggregated response sender.
    /// * If the signature is incorrect, it sends an incorrect signature error to error channel.
    ///
    /// # Arguments
    ///
    /// * `metadata` - task metadata
    /// * `aggregated_response_sender` - The sender channel for the aggregated responses
    /// * `signatures_rx` - The receiver channel for the signed task responses
    #[instrument(skip(avs_registry_service, aggregated_response_sender, signatures_rx), fields(
        task_id = %metadata.task_id,
        quorum_count = metadata.quorum_numbers.len(),
    ))]
    async fn single_task_aggregator(
        avs_registry_service: A,
        metadata: TaskMetadata,
        aggregated_response_sender: UnboundedSender<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
        signatures_rx: UnboundedReceiver<SignedTaskResponseDigest>,
    ) -> Result<(), BlsAggregationServiceError> {
        let start_time = std::time::Instant::now();
        info!(
            task_id = %metadata.task_id,
            "[TaskAggregator] starting single task aggregator - quorums: {}, expires in: {} ms",
            String::from_utf8(metadata.quorum_numbers.clone()).unwrap_or_default(),
            metadata.time_to_expiry.as_millis()
        );
        debug!(task_id = %metadata.task_id, "[TaskAggregator] building quorum threshold map");
        let quorum_threshold_percentage_map: HashMap<u8, u8> = metadata
            .quorum_numbers
            .iter()
            .enumerate()
            .map(|(i, quorum_number)| (*quorum_number, metadata.quorum_threshold_percentages[i]))
            .collect();
        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] quorum thresholds: {}",
            quorum_threshold_percentage_map
                .iter()
                .map(|(k, v)| format!("{}:{}", k, v))
                .collect::<Vec<String>>()
                .join(", ")
        );
        debug!(task_id = %metadata.task_id, "[TaskAggregator] fetching operator AVS state...");
        let operator_fetch_start = std::time::Instant::now();
        let operator_state_avs = avs_registry_service
            .get_operators_avs_state_at_block(metadata.task_created_block, &metadata.quorum_numbers)
            .await
            .map_err(|e| {
                let duration = operator_fetch_start.elapsed();
                error!(
                    task_id = %metadata.task_id,
                    block = metadata.task_created_block,
                    quorum_count = metadata.quorum_numbers.len(),
                    duration_ms = duration.as_millis(),
                    error = %e,
                    "Failed to get operator AVS state from registry service"
                );
                BlsAggregationServiceError::RegistryError {
                    task_id: metadata.task_id,
                    operator_context: String::new(),
                    reason: format!(
                        "failed to get operator AVS state at block {}: {}",
                        metadata.task_created_block, e
                    ),
                }
            })?;

        let operator_fetch_duration = operator_fetch_start.elapsed();
        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] fetched {} operators in {} ms",
            operator_state_avs.len(),
            operator_fetch_duration.as_millis()
        );
        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] operator IDs: {:?}",
            operator_state_avs
                .keys()
                .map(|k| hex!(k.as_slice()))
                .collect::<Vec<_>>()
        );
        debug!(task_id = %metadata.task_id, "[TaskAggregator] fetching quorum AVS state...");
        let quorum_fetch_start = std::time::Instant::now();
        let quorums_avs_state = avs_registry_service
            .get_quorums_avs_state_at_block(&metadata.quorum_numbers, metadata.task_created_block)
            .await
            .map_err(|e| {
                let duration = quorum_fetch_start.elapsed();
                error!(
                    task_id = %metadata.task_id,
                    block = metadata.task_created_block,
                    quorum_count = metadata.quorum_numbers.len(),
                    duration_ms = duration.as_millis(),
                    error = %e,
                    "Failed to get quorum AVS state from registry service"
                );
                BlsAggregationServiceError::RegistryError {
                    task_id: metadata.task_id,
                    operator_context: String::new(),
                    reason: format!(
                        "failed to get quorum AVS state at block {}: {}",
                        metadata.task_created_block, e
                    ),
                }
            })?;

        let quorum_fetch_duration = quorum_fetch_start.elapsed();
        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] fetched quorum state in {} ms",
            quorum_fetch_duration.as_millis()
        );

        for (quorum_num, state) in &quorums_avs_state {
            debug!(
                task_id = %metadata.task_id,
                "[TaskAggregator] quorum {} - total stake: {}, block: {}",
                quorum_num, state.total_stake, state.block_num
            );
        }
        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] computing total stakes per quorum",
        );
        let total_stake_per_quorum: HashMap<_, _> =
            quorums_avs_state.iter().map(|(k, v)| (*k, v.total_stake)).collect();

        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] total stakes: {}",
            total_stake_per_quorum
                .iter()
                .map(|(quorum_num, stake)| format!("(quorum num: {}, stake: {})", quorum_num, stake))
                .collect::<Vec<String>>()
                .join(", ")
        );
        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] extracting quorum aggregate public keys",
        );
        let quorum_apks_g1: Vec<BlsG1Point> = metadata
            .quorum_numbers
            .iter()
            .filter_map(|quorum_num| quorums_avs_state.get(quorum_num))
            .map(|avs_state| avs_state.agg_pub_key_g1.clone())
            .collect();

        debug!(
            task_id = %metadata.task_id,
            "[TaskAggregator] extracted {} quorum aggregate keys",
            quorum_apks_g1.len()
        );

        // [DEBUG] Log quorum APK G1 coordinates at extraction time
        // This is the quorum aggregate pubkey from the AVS state at task_created_block
        for (idx, apk) in quorum_apks_g1.iter().enumerate() {
            if let (Some(x), Some(y)) = (apk.g1().x(), apk.g1().y()) {
                debug!(
                    "[DEBUG] BLS_QUORUM_APK_EXTRACT: Task {} quorum_idx={} G1_X={} G1_Y={}",
                    metadata.task_id, idx, x, y
                );
            } else {
                debug!(
                    "[DEBUG] BLS_QUORUM_APK_EXTRACT: Task {} quorum_idx={} APK is at infinity",
                    metadata.task_id, idx
                );
            }
        }

        let setup_duration = start_time.elapsed();
        info!(
            task_id = %metadata.task_id,
            "[TaskAggregator] setup completed in {} ms, starting signature aggregation loop",
            setup_duration.as_millis()
        );

        Self::loop_task_aggregator(
            avs_registry_service,
            metadata.task_id,
            metadata.task_created_block,
            metadata.time_to_expiry,
            aggregated_response_sender,
            signatures_rx,
            operator_state_avs,
            total_stake_per_quorum,
            quorum_threshold_percentage_map,
            quorum_apks_g1,
            metadata.quorum_numbers,
            metadata.window_duration,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    #[instrument(skip(avs_registry_service, aggregated_response_sender, signatures_rx, operator_state_avs, total_stake_per_quorum, quorum_threshold_percentage_map, quorum_apks_g1), fields(
        task_id = %task_id,
        quorum_count = quorum_nums.len(),
        operator_count = operator_state_avs.len(),
        window_duration = ?window_duration
    ))]
    async fn loop_task_aggregator(
        avs_registry_service: A,
        task_id: TaskId,
        task_created_block: u64,
        time_to_expiry: Duration,
        aggregated_response_sender: UnboundedSender<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
        mut signatures_rx: UnboundedReceiver<SignedTaskResponseDigest>,
        operator_state_avs: HashMap<FixedBytes<32>, OperatorAvsState>,
        total_stake_per_quorum: HashMap<u8, Uint<256, 4>>,
        quorum_threshold_percentage_map: HashMap<u8, u8>,
        quorum_apks_g1: Vec<BlsG1Point>,
        quorum_nums: Vec<u8>,
        window_duration: Duration,
    ) -> Result<(), BlsAggregationServiceError> {
        let start_time = std::time::Instant::now();
        debug!(
            task_id = %task_id,
            "[TaskAggregator] starting signature aggregation loop - {} operators, {} quorums, window: {} ms",
            operator_state_avs.len(),
            quorum_nums.len(),
            window_duration.as_millis()
        );
        debug!(
            task_id = %task_id,
            "[TaskAggregator] total stakes per quorum: {}",
            total_stake_per_quorum
                .iter()
                .map(|(quorum_num, stake)| format!("quorum num: {}, stake: {}", quorum_num, stake))
                .collect::<Vec<String>>()
                .join(", ")
        );
        debug!(
            task_id = %task_id,
            "[TaskAggregator] threshold percentages: {}",
            quorum_threshold_percentage_map
                .iter()
                .map(|(quorum_num, percentage)| format!("quorum num: {}, percentage: {}", quorum_num, percentage))
                .collect::<Vec<String>>()
                .join(", ")
        );

        let mut aggregated_operators: HashMap<FixedBytes<32>, AggregatedOperators> = HashMap::new();
        let mut open_window = false;
        let mut current_aggregated_response: Option<BlsAggregationServiceResponse> = None;
        let (window_tx, mut window_rx) = tokio::sync::mpsc::unbounded_channel::<bool>();
        let task_expired_timer = tokio::time::sleep(time_to_expiry);
        tokio::pin!(task_expired_timer);

        let mut signature_count = 0u32;
        let mut duplicate_count = 0u32;
        let mut invalid_count = 0u32;

        debug!(
            task_id = %task_id,
            "[TaskAggregator] entering main aggregation loop, expires in {} ms",
            time_to_expiry.as_millis()
        );

        loop {
            tokio::select! {
                _ = &mut task_expired_timer => {
                    let loop_duration = start_time.elapsed();
                    warn!(
                        task_id = %task_id,
                        "[TaskAggregator] task expired after {} ms - processed {} signatures ({} duplicates, {} invalid), quorum reached: {}",
                        loop_duration.as_millis(), signature_count, duplicate_count, invalid_count, current_aggregated_response.is_some()
                    );
                    // If the task is expired, send the aggregated response
                    Self::handle_task_expired(
                        &aggregated_response_sender,
                        task_id,
                        open_window,
                        &current_aggregated_response,
                    )?;
                    return Ok(());
                },
                _ = window_rx.recv() => {
                    info!(
                        task_id = %task_id,
                        "[TaskAggregator] aggregation window closed - sending response",
                    );
                    // If the window is finished, send the aggregated response
                    Self::handle_window_finished(
                        &aggregated_response_sender,
                        task_id,
                        &current_aggregated_response,
                    )?;
                    return Ok(());
                },
                signed_task_digest = signatures_rx.recv() => {
                    match signed_task_digest {
                        Some(digest) => {
                            signature_count += 1;
                            let operator_id_hex = hex!(digest.operator_id.as_slice());
                            debug!(
                                task_id = %task_id,
                                "[TaskAggregator] received signature #{} from operator {}",
                                signature_count, operator_id_hex
                            );

                            // If a new signature is received, handle it
                            match Self::handle_new_signature(
                                &avs_registry_service,
                                &mut aggregated_operators,
                                &mut open_window,
                                &mut current_aggregated_response,
                                &window_tx,
                                task_id,
                                task_created_block,
                                &operator_state_avs,
                                &total_stake_per_quorum,
                                &quorum_threshold_percentage_map,
                                &quorum_apks_g1,
                                &quorum_nums,
                                window_duration,
                                Some(digest),
                            ).await {
                                Ok(_) => {
                                    trace!(task_id = %task_id, "[TaskAggregator] successfully processed signature from {}", operator_id_hex);
                                },
                                Err(BlsAggregationServiceError::SignatureVerificationError { verification_error: SignatureVerificationError::DuplicateSignature, .. }) => {
                                    duplicate_count += 1;
                                    debug!(task_id = %task_id, "[TaskAggregator] duplicate signature from {} (total duplicates: {})", operator_id_hex, duplicate_count);
                                },
                                Err(BlsAggregationServiceError::SignatureVerificationError { verification_error, .. }) => {
                                    invalid_count += 1;
                                    warn!(task_id = %task_id, "[TaskAggregator] invalid signature from {} (total invalid: {}, error: {:?})", operator_id_hex, invalid_count, verification_error);
                                },
                                Err(e) => {
                                    error!(task_id = %task_id, "[TaskAggregator] error processing signature from {}: {}", operator_id_hex, e.to_string());
                                    return Err(e);
                                }
                            }
                        },
                        None => {
                            warn!(task_id = %task_id, "[TaskAggregator] signature channel closed");
                            return Ok(());
                        }
                    }
                }
            }
        }
    }

    /// Handles a new signature in the [`loop_task_aggregator`] function.
    ///
    /// # Arguments
    ///
    /// * `avs_registry_service` - The avs registry service.
    /// * `aggregated_operators` - The aggregated operators.
    /// * `open_window` - Whether the window is open.
    /// * `current_aggregated_response` - The current aggregated response.
    /// * `window_tx` - The window tx.
    /// * `task_id` - The task index.
    /// * `task_created_block` - The task created block.
    /// * `operator_state_avs` - The operator state avs.
    /// * `total_stake_per_quorum` - The total stake per quorum.
    /// * `quorum_threshold_percentage_map` - The quorum threshold percentage map.
    /// * `quorum_apks_g1` - The quorum apks g1.
    /// * `quorum_nums` - The quorum numbers.
    /// * `window_duration` - The window duration.
    /// * `signed_task_digest` - The signed task digest.
    #[allow(clippy::too_many_arguments)]
    #[instrument(skip_all)]
    async fn handle_new_signature(
        avs_registry_service: &A,
        aggregated_operators: &mut HashMap<FixedBytes<32>, AggregatedOperators>,
        open_window: &mut bool,
        current_aggregated_response: &mut Option<BlsAggregationServiceResponse>,
        window_tx: &UnboundedSender<bool>,
        task_id: TaskId,
        task_created_block: u64,
        operator_state_avs: &HashMap<FixedBytes<32>, OperatorAvsState>,
        total_stake_per_quorum: &HashMap<u8, Uint<256, 4>>,
        quorum_threshold_percentage_map: &HashMap<u8, u8>,
        quorum_apks_g1: &[BlsG1Point],
        quorum_nums: &[u8],
        window_duration: Duration,
        signed_task_digest: Option<SignedTaskResponseDigest>,
    ) -> Result<(), BlsAggregationServiceError> {
        let start_time = std::time::Instant::now();

        let signed_digest = signed_task_digest.ok_or_else(|| BlsAggregationServiceError::SignaturesChannelClosed {
            task_id,
            reason: "signature channel receiver dropped (task aggregator may have finished or expired)".to_string(),
        })?;

        // Input validation
        if signed_digest.operator_id == FixedBytes::ZERO {
            error!(
                task_id = %task_id,
                "Invalid operator_id: zero operator ID"
            );
            return Err(BlsAggregationServiceError::RegistryError {
                task_id,
                operator_context: String::new(),
                reason: "invalid operator_id: zero operator ID".to_string(),
            });
        }
        if signed_digest.task_response_digest == FixedBytes::ZERO {
            error!(
                task_id = %task_id,
                operator_id = %hex!(signed_digest.operator_id.as_slice()),
                "Invalid task_response_digest: zero digest"
            );
            return Err(BlsAggregationServiceError::RegistryError {
                task_id,
                operator_context: format!(" from operator {}", hex!(signed_digest.operator_id.as_slice())),
                reason: "invalid task_response_digest: zero digest".to_string(),
            });
        }
        if quorum_nums.is_empty() {
            error!(
                task_id = %task_id,
                "Invalid quorum_nums: empty quorum numbers"
            );
            return Err(BlsAggregationServiceError::RegistryError {
                task_id,
                operator_context: String::new(),
                reason: "invalid quorum_nums: empty quorum numbers".to_string(),
            });
        }

        let operator_id_hex = hex!(signed_digest.operator_id.as_slice());
        debug!(
            task_id = %task_id,
            "[TaskAggregator] processing signature from operator {} for digest {}",
            operator_id_hex,
            hex!(signed_digest.task_response_digest)
        );

        // Verify if the operator has already signed for this digest
        if Self::is_duplicate_signature(aggregated_operators, &signed_digest) {
            debug!(
                task_id = %task_id,
                "[TaskAggregator] duplicate signature detected from operator {}",
                operator_id_hex
            );
            // Handle receiver drop gracefully instead of propagating error.
            // When a request times out or is cancelled (e.g., client disconnects, load-induced queue backups), the
            // `process_signature` future is dropped, which drops the oneshot::Receiver that was waiting
            // for this result. However, the task aggregator may still be processing the signature
            // verification when this happens.
            if signed_digest
                .result_channel
                .send(Err(BlsAggregationServiceError::SignatureVerificationError {
                    task_id,
                    operator_id: signed_digest.operator_id,
                    verification_error: SignatureVerificationError::DuplicateSignature,
                }))
                .is_err()
            {
                warn!(
                    task_id = %task_id,
                    "[TaskAggregator] failed to send duplicate signature error to result channel for operator {} (receiver dropped - likely request timeout or cancellation)",
                    operator_id_hex
                );
                // Don't propagate error - the caller has already cancelled/timeout, so this is expected
            }
            return Ok(());
        }

        debug!(
            task_id = %task_id,
            "[TaskAggregator] verifying signature from operator {}",
            operator_id_hex
        );
        let verification_start = std::time::Instant::now();

        // Verify the signature
        let verification_result = verify_signature(task_id, &signed_digest, operator_state_avs)
            .await
            .map_err(|e| BlsAggregationServiceError::SignatureVerificationError {
                task_id,
                operator_id: signed_digest.operator_id,
                verification_error: e,
            });

        let verification_duration = verification_start.elapsed();
        let verification_has_error = verification_result.is_err();

        match &verification_result {
            Ok(_) => {
                debug!(
                    task_id = %task_id,
                    "[TaskAggregator] signature verification passed for operator {} in {} ms",
                    operator_id_hex,
                    verification_duration.as_millis()
                );
            }
            Err(e) => {
                warn!(
                    task_id = %task_id,
                    "[TaskAggregator] signature verification failed for operator {} in {} ms: {}",
                    operator_id_hex,
                    verification_duration.as_millis(),
                    e.to_string()
                );
            }
        }

        // Handle receiver drop gracefully instead of propagating error.
        if signed_digest.result_channel.send(verification_result).is_err() {
            warn!(
                task_id = %task_id,
                "[TaskAggregator] failed to send verification result to result channel for operator {} (receiver dropped - likely request timeout or cancellation)",
                operator_id_hex
            );
            // Don't propagate error - the caller has already cancelled/timeout, so this is expected
            return Ok(());
        }

        // If the signature is incorrect, return
        if verification_has_error {
            return Ok(());
        }

        debug!(
            task_id = %task_id,
            "[TaskAggregator] looking up operator state for {}",
            operator_id_hex
        );
        let operator_state = operator_state_avs.get(&signed_digest.operator_id).ok_or_else(|| {
            let duration = start_time.elapsed();
            error!(
                task_id = %task_id,
                operator_id = %operator_id_hex,
                digest = %hex!(signed_digest.task_response_digest),
                duration_ms = duration.as_millis(),
                total_operators = operator_state_avs.len(),
                "Operator state not found in operator_state_avs map"
            );
            BlsAggregationServiceError::RegistryError {
                task_id,
                operator_context: format!(" from operator {}", operator_id_hex),
                reason: format!(
                    "operator state not found in operator_state_avs map (total operators: {}, duration: {} ms)",
                    operator_state_avs.len(),
                    duration.as_millis()
                ),
            }
        })?;

        debug!(
            task_id = %task_id,
            "[TaskAggregator] operator {} stakes: {:?}",
            operator_id_hex, operator_state.stake_per_quorum
        );

        debug!(
            task_id = %task_id,
            "[TaskAggregator] updating aggregated operators with signature from {}",
            operator_id_hex
        );

        // Update the aggregated operators with the new operator info
        let update_start = std::time::Instant::now();
        let updated_aggregated = update_aggregated_operators(
            task_id,
            aggregated_operators,
            operator_state,
            signed_digest.task_response_digest,
            signed_digest.bls_signature,
            signed_digest.operator_id,
        )
        .map_err(|e| {
            error!(
                task_id = %task_id,
                operator_id = %operator_id_hex,
                ?e,
                "Failed to update aggregated operators: missing operator public keys"
            );
            e
        })?;

        // Enforce size limit - ignore new digest if limit reached (should never happen)
        let is_new_digest = !aggregated_operators.contains_key(&signed_digest.task_response_digest);
        if is_new_digest && aggregated_operators.len() >= Self::MAX_AGGREGATED_OPERATORS_PER_TASK {
            warn!(
                task_id = %task_id,
                operator_id = %operator_id_hex,
                digest = %hex!(signed_digest.task_response_digest.as_slice()),
                current_size = aggregated_operators.len(),
                max_size = Self::MAX_AGGREGATED_OPERATORS_PER_TASK,
                "Ignoring new digest - aggregated_operators limit reached (this should never happen)"
            );
            // Note: Verification result already sent earlier, so we just return early
            // The operator got their verification result, but this digest won't be aggregated
            return Ok(());
        }

        // Only insert if it's a new digest (existing entries were already modified in place)
        if is_new_digest {
            aggregated_operators.insert(signed_digest.task_response_digest, updated_aggregated);
        }
        let update_duration = update_start.elapsed();

        // Get the aggregated operators from HashMap (either newly inserted or already modified in place)
        let aggregated = aggregated_operators
            .get(&signed_digest.task_response_digest)
            .expect("aggregated operators should exist after update");

        debug!(
            task_id = %task_id,
            "[TaskAggregator] aggregated operators updated in {} ms - total signers: {}",
            update_duration.as_millis(),
            aggregated.signers_operator_ids_set.len()
        );

        // Check if the stake thresholds are met. If not, return
        let threshold_check_start = std::time::Instant::now();
        let threshold_met = Self::check_if_stake_thresholds_met(
            &aggregated.signers_total_stake_per_quorum,
            total_stake_per_quorum,
            quorum_threshold_percentage_map,
        );
        let threshold_check_duration = threshold_check_start.elapsed();

        if !threshold_met {
            debug!(
                task_id = %task_id,
                "[TaskAggregator] stake thresholds not yet met (checked in {} ms) - current stakes: {:?}",
                threshold_check_duration.as_millis(),
                aggregated.signers_total_stake_per_quorum
            );
            return Ok(());
        }

        info!(
            task_id = %task_id,
            "[TaskAggregator] stake thresholds met! ({} signers, checked in {} ms)",
            aggregated.signers_operator_ids_set.len(),
            threshold_check_duration.as_millis()
        );

        // If the window is not open, open it
        if !*open_window {
            *open_window = true;
            info!(
                task_id = %task_id,
                "[TaskAggregator] opening aggregation window for {} ms",
                window_duration.as_millis()
            );
            Self::start_window(window_tx, window_duration, task_id);
        } else {
            debug!(
                task_id = %task_id,
                "[TaskAggregator] aggregation window already open, updating response",
            );
        }

        debug!(task_id = %task_id, "[TaskAggregator] building aggregated response...");
        let response_build_start = std::time::Instant::now();
        *current_aggregated_response = Some(
            Self::build_aggregated_response(
                task_id,
                task_created_block,
                signed_digest.task_response_digest,
                operator_state_avs,
                aggregated.clone(),
                avs_registry_service,
                quorum_apks_g1,
                quorum_nums,
            )
            .await?,
        );
        let response_build_duration = response_build_start.elapsed();

        let total_duration = start_time.elapsed();
        debug!(
            task_id = %task_id,
            "[TaskAggregator] signature processing completed in {} ms (response built in {} ms) for operator {}",
            total_duration.as_millis(),
            response_build_duration.as_millis(),
            operator_id_hex
        );

        Ok(())
    }

    /// Handles when the task expired in the [`loop_task_aggregator`] function.
    /// If the window is open, send the aggregated response. Else, send the error.
    ///
    /// # Arguments
    ///
    /// * `aggregated_response_sender` - The aggregated response sender.
    /// * `task_id` - The task index.
    /// * `open_window` - Whether the window is open.
    /// * `current_aggregated_response` - The current aggregated response.
    #[instrument(skip_all, fields(task_id = %task_id, open_window = open_window))]
    fn handle_task_expired(
        aggregated_response_sender: &UnboundedSender<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
        task_id: TaskId,
        open_window: bool,
        current_aggregated_response: &Option<BlsAggregationServiceResponse>,
    ) -> Result<(), BlsAggregationServiceError> {
        if open_window {
            info!(
                task_id = %task_id,
                "[TaskAggregator] task expired while aggregation window was open - sending current response",
            );
            if let Some(response) = current_aggregated_response {
                debug!(
                    task_id = %task_id,
                    "[TaskAggregator] sending response with {} non-signer keys",
                    response.non_signers_pub_keys_g1.len()
                );
                aggregated_response_sender.send(Ok(response.clone())).map_err(|e| {
                    let reason = format!("failed to send expired task response: {:?}", e);
                    error!(task_id = %task_id, "[TaskAggregator] {}", reason);
                    BlsAggregationServiceError::SenderError {
                        operation: "SendExpiredTaskResponse".to_string(),
                        task_id,
                        operator_context: String::new(),
                        reason,
                    }
                })?;
            } else {
                error!(task_id = %task_id, "[TaskAggregator] window was open but no response available");
                // Handle receiver drop gracefully instead of propagating error
                if aggregated_response_sender
                    .send(Err(BlsAggregationServiceError::TaskExpired {
                        task_id,
                        reason: TaskExpiryReason::WindowOpenNoResponse,
                    }))
                    .is_err()
                {
                    warn!(
                        task_id = %task_id,
                        "[TaskAggregator] handle_task_expired:window_open_no_response - failed to send task expired error",
                    );
                    return Ok(());
                }
            }
        } else {
            warn!(
                task_id = %task_id,
                "[TaskAggregator] task expired without reaching quorum threshold",
            );
            // Handle receiver drop gracefully instead of propagating error
            if aggregated_response_sender
                .send(Err(BlsAggregationServiceError::TaskExpired {
                    task_id,
                    reason: TaskExpiryReason::QuorumNotMet,
                }))
                .is_err()
            {
                warn!(
                    task_id = %task_id,
                    "[TaskAggregator] handle_task_expired:quorum_not_reached - failed to send task expired error",
                );
                return Ok(());
            }
        }
        Ok(())
    }

    /// Handles when the window is finished in the [`loop_task_aggregator`] function.
    ///
    /// # Arguments
    ///
    /// * `aggregated_response_sender` - The aggregated response sender.
    /// * `task_id` - The task index.
    /// * `current_aggregated_response` - The current aggregated response.
    #[instrument(skip_all, fields(task_id = %task_id))]
    fn handle_window_finished(
        aggregated_response_sender: &UnboundedSender<Result<BlsAggregationServiceResponse, BlsAggregationServiceError>>,
        task_id: TaskId,
        current_aggregated_response: &Option<BlsAggregationServiceResponse>,
    ) -> Result<(), BlsAggregationServiceError> {
        info!(
            task_id = %task_id,
            "[TaskAggregator] aggregation window finished - sending final response",
        );

        if let Some(response) = current_aggregated_response {
            debug!(
                task_id = %task_id,
                "[TaskAggregator] sending final response with {} non-signer keys",
                response.non_signers_pub_keys_g1.len()
            );
            aggregated_response_sender.send(Ok(response.clone())).map_err(|e| {
                let reason = format!("failed to send window finished response: {}", e);
                error!(task_id = %task_id, "[TaskAggregator] {}", reason);
                BlsAggregationServiceError::SenderError {
                    operation: "SendWindowFinishedResponse".to_string(),
                    task_id,
                    operator_context: String::new(),
                    reason,
                }
            })?;
        } else {
            error!(task_id = %task_id, "[TaskAggregator] window finished but no response available");
            // Handle receiver drop gracefully instead of propagating error
            if aggregated_response_sender
                .send(Err(BlsAggregationServiceError::TaskExpired {
                    task_id,
                    reason: TaskExpiryReason::WindowFinishedNoResponse,
                }))
                .is_err()
            {
                warn!(
                    task_id = %task_id,
                    "[TaskAggregator] handle_window_finished:no_response - failed to send task expired error",
                );
                return Ok(());
            }
        }

        Ok(())
    }

    /// Builds the aggregated response containing all the aggregation info.
    ///
    /// # Arguments
    ///
    /// * `task_id` - The index of the task.
    /// * `task_created_block` - The block in which the task was created.
    /// * `signed_task_digest` - The signed task.
    /// * `operator_state_avs` - A hashmap with the operator state per operator id.
    /// * `digest_aggregated_operators` - The aggregated operators.
    /// * `avs_registry_service` - The avs registry service.
    /// * `quorum_apks_g1` - The quorum aggregated public keys.
    /// * `quorum_nums` - The quorum numbers.
    ///
    /// # Returns
    ///
    /// The BLS aggregation service response.
    #[allow(clippy::too_many_arguments)]
    #[instrument(skip_all)]
    pub async fn build_aggregated_response(
        task_id: TaskId,
        task_created_block: u64,
        task_response_digest: FixedBytes<32>,
        operator_state_avs: &HashMap<FixedBytes<32>, OperatorAvsState>,
        digest_aggregated_operators: AggregatedOperators,
        avs_registry_service: &A,
        quorum_apks_g1: &[BlsG1Point],
        quorum_nums: &[u8],
    ) -> Result<BlsAggregationServiceResponse, BlsAggregationServiceError> {
        let start_time = std::time::Instant::now();
        debug!(
            task_id = %task_id,
            "[TaskAggregator] building aggregated response for digest {}",
            task_response_digest
        );
        debug!(
            task_id = %task_id,
            "[TaskAggregator] signers count: {}, quorums: {:?}",
            digest_aggregated_operators.signers_operator_ids_set.len(),
            quorum_nums
        );

        debug!(
            task_id = %task_id,
            "[TaskAggregator] computing non-signers from {} total operators",
            operator_state_avs.len()
        );
        let mut non_signers_operators_ids: Vec<FixedBytes<32>> = operator_state_avs
            .keys()
            .filter(|operator_id| {
                !digest_aggregated_operators
                    .signers_operator_ids_set
                    .contains_key(*operator_id)
            })
            .cloned()
            .collect();

        non_signers_operators_ids.sort();
        debug!(
            task_id = %task_id,
            "[TaskAggregator] identified {} non-signers out of {} operators",
            non_signers_operators_ids.len(),
            operator_state_avs.len()
        );
        debug!(
            task_id = %task_id,
            "[TaskAggregator] non-signer IDs: {}",
            non_signers_operators_ids
                .iter()
                .map(|id| hex!(id.as_slice()))
                .collect::<Vec<_>>()
                .join(", ")
        );

        debug!(
            task_id = %task_id,
            "[TaskAggregator] extracting public keys for {} non-signers",
            non_signers_operators_ids.len()
        );
        let non_signers_pub_keys_g1: Vec<BlsG1Point> = non_signers_operators_ids
            .iter()
            .filter_map(|operator_id| {
                let state = operator_state_avs.get(operator_id);
                if state.is_none() {
                    warn!(
                        task_id = %task_id,
                        "[TaskAggregator] operator state not found for non-signer {}",
                        hex!(operator_id.as_slice())
                    );
                }
                state
            })
            .filter_map(|operator_avs_state| {
                if operator_avs_state.operator_info.pub_keys.is_none() {
                    warn!(task_id = %task_id, "[TaskAggregator] public keys not found for non-signer");
                }
                operator_avs_state.operator_info.pub_keys.clone()
            })
            .map(|pub_keys| pub_keys.g1_pub_key)
            .collect();

        debug!(
            task_id = %task_id,
            "[TaskAggregator] extracted {} public keys for non-signers",
            non_signers_pub_keys_g1.len()
        );

        debug!(
            task_id = %task_id,
            "[TaskAggregator] fetching signature check indices for block {}",
            task_created_block
        );
        let indices_start = std::time::Instant::now();
        let indices = avs_registry_service
            .get_check_signatures_indices(
                task_created_block,
                quorum_nums.into(),
                non_signers_operators_ids.clone(),
            )
            .await
            .map_err(|err| {
                let duration = indices_start.elapsed();
                error!(
                    task_id = %task_id,
                    block = task_created_block,
                    quorum_count = quorum_nums.len(),
                    non_signer_count = non_signers_operators_ids.len(),
                    duration_ms = duration.as_millis(),
                    error = ?err,
                    "Failed to get check signatures indices from registry service"
                );
                BlsAggregationServiceError::RegistryError {
                    task_id,
                    operator_context: String::new(),
                    reason: format!(
                        "failed to get check signatures indices at block {}: {:?}",
                        task_created_block, err
                    ),
                }
            })?;

        let indices_duration = indices_start.elapsed();
        debug!(
            task_id = %task_id,
            "[TaskAggregator] fetched signature check indices in {} ms",
            indices_duration.as_millis()
        );

        let total_duration = start_time.elapsed();
        info!(
            task_id = %task_id,
            "[TaskAggregator] aggregated response built in {} ms - signers: {}, non-signers: {}",
            total_duration.as_millis(),
            digest_aggregated_operators.signers_operator_ids_set.len(),
            non_signers_operators_ids.len()
        );
        debug!(
            task_id = %task_id,
            "[TaskAggregator] aggregated response stakes: {:?}",
            digest_aggregated_operators.signers_total_stake_per_quorum
        );

        // [DEBUG] Log critical BLS point information for BN254 debugging
        let signers_apk_g2_is_infinity = digest_aggregated_operators.signers_apk_g2.g2().infinity;
        let signers_agg_sig_is_infinity = digest_aggregated_operators.signers_agg_sig_g1.g1_point().g1().infinity;

        debug!(
            task_id = %task_id,
            signers_apk_g2_is_infinity = signers_apk_g2_is_infinity,
            signers_agg_sig_is_infinity = signers_agg_sig_is_infinity,
            non_signers_pub_keys_count = non_signers_pub_keys_g1.len(),
            quorum_apks_count = quorum_apks_g1.len(),
            "[DEBUG] BLS aggregation result - checking for point-at-infinity issues"
        );

        // [DEBUG] Check for critical point-at-infinity cases
        if signers_apk_g2_is_infinity {
            error!(
                task_id = %task_id,
                signers_count = digest_aggregated_operators.signers_operator_ids_set.len(),
                "[DEBUG] CRITICAL: Signers APK G2 is point at infinity - BN254 pairing will fail. \
                This likely means no valid BLS signatures were aggregated."
            );
        }

        if signers_agg_sig_is_infinity {
            error!(
                task_id = %task_id,
                signers_count = digest_aggregated_operators.signers_operator_ids_set.len(),
                "[DEBUG] CRITICAL: Aggregated signature is point at infinity - BN254 verification will fail. \
                This likely means no valid signatures were collected."
            );
        }

        // [DEBUG] Log the signer operator IDs for traceability
        let signer_ids: Vec<String> = digest_aggregated_operators
            .signers_operator_ids_set
            .keys()
            .map(|id| hex!(id.as_slice()))
            .collect();
        debug!(
            task_id = %task_id,
            signer_ids = ?signer_ids,
            "[DEBUG] Signer operator IDs in aggregated response"
        );

        // [DEBUG] Compute and log the mathematical verification for BN254 debugging
        // This verifies: signers_APK_G1 = quorum_APK - non_signers_G1
        // The contract computes signers_APK_G1 this way, and we submit signers_APK_G2
        // Both must represent the same point for pairing to succeed
        // Guard expensive EC computations with tracing level check to avoid cost when debug is disabled
        if tracing::enabled!(tracing::Level::DEBUG) {
            use ark_ec::CurveGroup;

            // Compute sum of signers' G1 pubkeys
            let mut signers_g1_sum = ark_bn254::G1Affine::identity();
            for signer_id in digest_aggregated_operators.signers_operator_ids_set.keys() {
                if let Some(state) = operator_state_avs.get(signer_id) {
                    if let Some(ref pub_keys) = state.operator_info.pub_keys {
                        signers_g1_sum =
                            (signers_g1_sum.into_group() + pub_keys.g1_pub_key.g1().into_group()).into_affine();
                    }
                }
            }

            // Compute quorum_APK - non_signers for verification
            let mut quorum_apk_sum = ark_bn254::G1Affine::identity();
            for apk in quorum_apks_g1.iter() {
                quorum_apk_sum = (quorum_apk_sum.into_group() + apk.g1().into_group()).into_affine();
            }

            let mut non_signers_sum = ark_bn254::G1Affine::identity();
            for ns_pk in non_signers_pub_keys_g1.iter() {
                non_signers_sum = (non_signers_sum.into_group() + ns_pk.g1().into_group()).into_affine();
            }

            // expected_signers = quorum_apk - non_signers
            let expected_signers = (quorum_apk_sum.into_group() - non_signers_sum.into_group()).into_affine();

            // Log the computed values
            if let (Some(x1), Some(y1)) = (signers_g1_sum.x(), signers_g1_sum.y()) {
                if let (Some(x2), Some(y2)) = (expected_signers.x(), expected_signers.y()) {
                    let matches = x1 == x2 && y1 == y2;
                    debug!(
        "[DEBUG] BLS_APK_VERIFY: Task {} SIGNERS_G1_SUM X={} Y={} | EXPECTED (quorum-non_signers) X={} Y={} | MATCH={}",
                        task_id, x1, y1, x2, y2, matches
                    );
                    if !matches {
                        error!(
                            "[DEBUG] BLS_APK_MISMATCH: signers_G1_sum != quorum_APK - non_signers! This will cause BN254 failure."
                        );
                    }
                }
            }

            // [DEBUG] Log the aggregated G2 APK coordinates
            // This must correspond to the same point as signers_G1_sum for BN254 pairing to succeed
            // If any operator registered mismatched G1/G2 keys, this will fail
            let signers_apk_g2 = digest_aggregated_operators.signers_apk_g2.g2();
            if let (Some(x), Some(y)) = (signers_apk_g2.x(), signers_apk_g2.y()) {
                debug!(
                    "[DEBUG] BLS_SIGNERS_APK_G2: Task {} G2_X_c0={} G2_X_c1={} G2_Y_c0={} G2_Y_c1={}",
                    task_id, x.c0, x.c1, y.c0, y.c1
                );
            } else {
                error!(
                    "[DEBUG] BLS_SIGNERS_APK_G2: Task {} G2 point is at infinity - BN254 pairing will fail",
                    task_id
                );
            }
        }

        Ok(BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: digest_aggregated_operators.signers_operator_ids_set.len(),
            non_signers_pub_keys_g1,
            non_signers_operators_ids,
            quorum_apks_g1: quorum_apks_g1.into(),
            signers_apk_g2: digest_aggregated_operators.signers_apk_g2,
            signers_agg_sig_g1: digest_aggregated_operators.signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: indices.clone().nonSignerQuorumBitmapIndices,
            quorum_apk_indices: indices.quorumApkIndices,
            total_stake_indices: indices.totalStakeIndices,
            non_signer_stake_indices: indices.nonSignerStakeIndices,
        })
    }

    /// Checks if the stake thresholds are met for the given set of quorum members.
    ///
    /// # Arguments
    ///
    /// * `signed_stake_per_quorum` - The signed stake per quorum.
    /// * `total_stake_per_quorum` - The total stake per quorum.
    /// * `quorum_threshold_percentages_map` - The quorum threshold percentages map,
    ///   containing the quorum id as a key and its corresponding quorum threshold percentage.
    ///
    /// # Returns
    ///
    /// Returns `true` if the stake thresholds are met for all the members, otherwise `false`.
    fn check_if_stake_thresholds_met(
        signed_stake_per_quorum: &HashMap<u8, U256>,
        total_stake_per_quorum: &HashMap<u8, U256>,
        quorum_threshold_percentages_map: &HashMap<u8, QuorumThresholdPercentage>,
    ) -> bool {
        for (quorum_num, quorum_threshold_percentage) in quorum_threshold_percentages_map {
            let (Some(signed_stake_by_quorum), Some(total_stake_by_quorum)) = (
                signed_stake_per_quorum.get(quorum_num),
                total_stake_per_quorum.get(quorum_num),
            ) else {
                return false;
            };

            let signed_stake = signed_stake_by_quorum * U256::from(100);
            let threshold_stake = *total_stake_by_quorum * U256::from(*quorum_threshold_percentage);

            if signed_stake < threshold_stake {
                return false;
            }
        }
        true
    }

    /// Checks if the signature is a duplicate.
    ///
    /// # Arguments
    ///
    /// * `aggregated_operators` - The aggregated operators.
    /// * `signed_digest` - The signed task response digest.
    ///
    /// # Returns
    ///
    /// Returns `true` if the signature is a duplicate, otherwise `false`.
    #[instrument(skip_all, fields(
        operator_id = %hex!(signed_digest.operator_id.as_slice()),
        digest = %hex!(signed_digest.task_response_digest.as_slice())
    ))]
    fn is_duplicate_signature(
        aggregated_operators: &HashMap<FixedBytes<32>, AggregatedOperators>,
        signed_digest: &SignedTaskResponseDigest,
    ) -> bool {
        let operator_id_hex = hex!(signed_digest.operator_id.as_slice());
        let digest_hex = hex!(signed_digest.task_response_digest.as_slice());

        let is_duplicate = aggregated_operators
            .get(&signed_digest.task_response_digest)
            .map(|ops| {
                let has_signed = ops.signers_operator_ids_set.contains_key(&signed_digest.operator_id);
                trace!(
                    "[BlsAggregatorService] operator {} duplicate check for digest {}: {}",
                    operator_id_hex,
                    digest_hex,
                    has_signed
                );
                has_signed
            })
            .unwrap_or_else(|| {
                trace!(
                    "[BlsAggregatorService] no existing signatures for digest {} from operator {}",
                    digest_hex,
                    operator_id_hex
                );
                false
            });

        if is_duplicate {
            debug!(
                "[BlsAggregatorService] duplicate signature detected from operator {} for digest {}",
                operator_id_hex, digest_hex
            );
        }

        is_duplicate
    }

    /// Starts the window to wait for new signatures.
    ///
    /// # Arguments
    ///
    /// * `window_tx` - The unbounded sender to send the window signal.
    /// * `window_duration` - The duration of the window.
    /// * `task_id` - The task index.
    #[instrument(skip_all, fields(task_id = %task_id, window_duration = ?window_duration))]
    fn start_window(window_tx: &UnboundedSender<bool>, window_duration: Duration, task_id: TaskId) {
        let sender = window_tx.clone();

        if window_duration.is_zero() {
            debug!(
                task_id = %task_id,
                "[TaskAggregator] window duration is zero - closing immediately",
            );
            if sender.send(true).is_err() {
                error!(
                    task_id = %task_id,
                    "[TaskAggregator] failed to send immediate window close signal",
                );
            }
            return;
        }

        info!(
            task_id = %task_id,
            "[TaskAggregator] starting aggregation window for {} ms",
            window_duration.as_millis()
        );

        tokio::spawn(async move {
            tokio::time::sleep(window_duration).await;
            info!(task_id = %task_id, "[TaskAggregator] aggregation window expired");
            if sender.send(true).is_err() {
                error!(task_id = %task_id, "[TaskAggregator] failed to send window expiry signal");
            }
        });
    }
}

/// Verifies the signature of the task response given a `operator_avs_state`.
/// If the signature is correct, it returns `Ok(())`, otherwise it returns an error.
///
/// # Arguments
///
/// * `task_id` - The index of the task
/// * `signed_task_response_digest` - The signed task response digest
/// * `operator_avs_state` - A hashmap containing the staked of all the operator indexed by operator_id.
///   This is used to get the `operator_state` to obtain the operator public key.
///
/// # Error
///
/// Returns error:
/// - `SignatureVerificationError::OperatorNotFound` if the operator is not found,
/// - `SignatureVerificationError::OperatorPublicKeyNotFound` if the operator public key is not found,
/// - `SignatureVerificationError::IncorrectSignature` if the signature is incorrect.
#[instrument(skip_all)]
async fn verify_signature(
    task_id: TaskId,
    signed_task_response_digest: &SignedTaskResponseDigest,
    operator_avs_state: &HashMap<FixedBytes<32>, OperatorAvsState>,
) -> Result<(), SignatureVerificationError> {
    debug!(
        "operator_avs_state: {}",
        operator_avs_state
            .iter()
            .map(|(k, v)| format!(
                "{}: [{}]",
                hex!(k),
                v.stake_per_quorum
                    .iter()
                    .map(|(quorum_num, stake)| format!("{}:{}", quorum_num, stake))
                    .collect::<Vec<String>>()
                    .join(", ")
            ))
            .collect::<Vec<String>>()
            .join(", ")
    );
    info!(
        "signed_task_response_digest: {}",
        hex!(signed_task_response_digest.task_response_digest.as_slice())
    );

    let Some(operator_state) = operator_avs_state.get(&signed_task_response_digest.operator_id) else {
        error!("Operator Not Found for task index: {task_id}");
        return Err(SignatureVerificationError::OperatorNotFound);
    };

    let Some(pub_keys) = &operator_state.operator_info.pub_keys else {
        error!("Operator Public Key Not Found for task index: {task_id}");
        return Err(SignatureVerificationError::OperatorPublicKeyNotFound);
    };

    let message = signed_task_response_digest
        .task_response_digest
        .as_slice()
        .try_into()
        .map_err(|_| SignatureVerificationError::IncorrectSignature)?;

    verify_message(
        pub_keys.g2_pub_key.g2(),
        message,
        signed_task_response_digest.bls_signature.g1_point().g1(),
    )
    .then_some(())
    .ok_or(SignatureVerificationError::IncorrectSignature)
    .inspect(|_| {
        debug!("Signature verification successful for task index: {task_id}");
    })
    .inspect_err(|_| {
        error!("Signature verification failed for task index: {task_id}");
    })
}

/// Updates the aggregated operators with the new operator info.
///
/// # Arguments
///
/// * `task_id` - The task ID for error context.
/// * `aggregated_operators` - The aggregated operators.
/// * `operator_state` - The operator state.
/// * `task_response_digest` - The task response digest.
/// * `bls_signature` - The BLS signature.
/// * `operator_id` - The operator id.
///
/// # Returns
///
/// The updated aggregated operators or an error if operator public keys are missing.
pub fn update_aggregated_operators(
    task_id: TaskId,
    aggregated_operators: &mut HashMap<FixedBytes<32>, AggregatedOperators>,
    operator_state: &OperatorAvsState,
    task_response_digest: FixedBytes<32>,
    bls_signature: Signature,
    operator_id: FixedBytes<32>,
) -> Result<AggregatedOperators, BlsAggregationServiceError> {
    debug!("Update aggregated operators");

    let bls_signature_g1_point = bls_signature.g1_point().g1();

    if let Some(existing) = aggregated_operators.get_mut(&task_response_digest) {
        // If the operator is already in the aggregated operators, aggregate the new operator
        aggregate_new_operator(
            task_id,
            existing,
            operator_state.clone(),
            operator_id,
            bls_signature_g1_point,
        )?;
        // Return the modified value from the HashMap (already updated in place via &mut)
        // Clone is necessary because we can't move out of a mutable reference
        Ok(existing.clone())
    } else {
        // If the operator is not in the aggregated operators, create a new aggregated operator
        let operator_pub_keys = operator_state.operator_info.pub_keys.clone().ok_or_else(|| {
            error!(
                task_id = %task_id,
                operator_id = %hex!(operator_id.as_slice()),
                "Operator public keys not found in operator state"
            );
            BlsAggregationServiceError::RegistryError {
                task_id,
                operator_context: format!(" from operator {}", hex!(operator_id.as_slice())),
                reason: "operator public keys not found in operator state".to_string(),
            }
        })?;

        let operator_g2_pubkey = operator_pub_keys.g2_pub_key.g2();
        let operator_g1_pubkey = operator_pub_keys.g1_pub_key.g1();

        // [DEBUG] Log first signer's G1 pubkey coordinates for BN254 verification
        if let (Some(x), Some(y)) = (operator_g1_pubkey.x(), operator_g1_pubkey.y()) {
            debug!(
                "[DEBUG] BLS_SIGNER_G1: First operator {} G1_X={} G1_Y={}",
                hex!(operator_id.as_slice()),
                x,
                y
            );
        } else {
            debug!(
                "[DEBUG] BLS_SIGNER_G1: First operator {} G1 point is at infinity",
                hex!(operator_id.as_slice())
            );
        }

        // [DEBUG] Log first signer's G2 pubkey coordinates for BN254 verification
        // This is critical - if G2 doesn't match what's registered on-chain, pairing will fail
        if let (Some(x), Some(y)) = (operator_g2_pubkey.x(), operator_g2_pubkey.y()) {
            debug!(
                "[DEBUG] BLS_SIGNER_G2: First operator {} G2_X_c0={} G2_X_c1={} G2_Y_c0={} G2_Y_c1={}",
                hex!(operator_id.as_slice()),
                x.c0,
                x.c1,
                y.c0,
                y.c1
            );
        } else {
            debug!(
                "[DEBUG] BLS_SIGNER_G2: First operator {} G2 point is at infinity",
                hex!(operator_id.as_slice())
            );
        }

        // [DEBUG] Log first signer's individual signature for aggregation verification
        if let (Some(x), Some(y)) = (bls_signature_g1_point.x(), bls_signature_g1_point.y()) {
            debug!(
                "[DEBUG] BLS_SIGNER_SIG: First operator {} SIG_X={} SIG_Y={}",
                hex!(operator_id.as_slice()),
                x,
                y
            );
        } else {
            debug!(
                "[DEBUG] BLS_SIGNER_SIG: First operator {} signature is point at infinity",
                hex!(operator_id.as_slice())
            );
        }

        // Add the operator's G2 pubkey and signature N times where N is the number of quorums.
        // The BLSSignatureChecker contract multiplies each operator's contribution by their
        // quorum count (see scalar_mul_tiny with countNumOnes in checkSignatures). This means
        // the aggregated APK_G2 and signature must include each operator's contribution
        // N times for N quorums they're staked in, to match the contract's computation.
        let quorum_count = operator_state.stake_per_quorum.len();
        let mut signers_apk_g2 = BlsG2Point::new(G2Affine::zero());
        let mut signers_agg_sig_g1 = Signature::new(G1Affine::zero());
        for _ in 0..quorum_count {
            signers_apk_g2 = BlsG2Point::new((signers_apk_g2.g2() + operator_g2_pubkey).into());
            signers_agg_sig_g1 = Signature::new((signers_agg_sig_g1.g1_point().g1() + bls_signature_g1_point).into());
        }

        debug!(
            "[DEBUG] BLS_FIRST_SIGNER_AGG: Operator {} added G2/sig {} times (quorum_count={})",
            hex!(operator_id.as_slice()),
            quorum_count,
            quorum_count
        );

        Ok(AggregatedOperators {
            signers_apk_g2,
            signers_agg_sig_g1,
            signers_operator_ids_set: HashMap::from([(operator_state.operator_id, true)]),
            signers_total_stake_per_quorum: operator_state.stake_per_quorum.clone(),
        })
    }
}

/// Adds a new operator to the aggregated operators by aggregating its public key, signature and stake.
///
/// # Arguments
///
/// - `task_id` - The task ID for error context.
/// - `aggregated_operators` - Contains the information of all the aggregated operators.
/// - `operator_state` - The state of the operator, contains information about its stake.
/// - `operator_id` - The operator ID.
/// - `signature_g1_point` - The signature G1 point.
///
/// # Returns
///
/// The given aggregated operators, aggregated with the new operator info, or an error if operator public keys are missing.
#[instrument(skip_all)]
pub fn aggregate_new_operator(
    task_id: TaskId,
    aggregated_operators: &mut AggregatedOperators,
    operator_state: OperatorAvsState,
    operator_id: FixedBytes<32>,
    signature_g1_point: G1Affine,
) -> Result<AggregatedOperators, BlsAggregationServiceError> {
    let operator_pub_keys = operator_state.operator_info.pub_keys.clone().ok_or_else(|| {
        error!(
            task_id = %task_id,
            operator_id = %hex!(operator_id.as_slice()),
            "Operator public keys not found in operator state for aggregate_new_operator"
        );
        BlsAggregationServiceError::RegistryError {
            task_id,
            operator_context: format!(" from operator {}", hex!(operator_id.as_slice())),
            reason: "operator public keys not found in operator state for aggregate_new_operator".to_string(),
        }
    })?;

    let operator_g2_pubkey = operator_pub_keys.g2_pub_key.g2();
    let operator_g1_pubkey = operator_pub_keys.g1_pub_key.g1();
    aggregated_operators.signers_operator_ids_set.insert(operator_id, true);

    debug!("operator {operator_id} inserted in signers_operator_ids_set");

    // [DEBUG] Log signer's G1 pubkey coordinates for BN254 verification
    // This allows us to compute expected signers_APK_G1 = sum(signers_G1)
    // and verify it matches quorum_APK - non_signers
    if let (Some(x), Some(y)) = (operator_g1_pubkey.x(), operator_g1_pubkey.y()) {
        debug!(
            "[DEBUG] BLS_SIGNER_G1: Operator {} G1_X={} G1_Y={}",
            hex!(operator_id.as_slice()),
            x,
            y
        );
    } else {
        debug!(
            "[DEBUG] BLS_SIGNER_G1: Operator {} G1 point is at infinity",
            hex!(operator_id.as_slice())
        );
    }

    // [DEBUG] Also log G2 pubkey to verify G1/G2 consistency
    // If G1 and G2 keys don't correspond to the same private key, BN254 pairing will fail
    if let (Some(x), Some(y)) = (operator_g2_pubkey.x(), operator_g2_pubkey.y()) {
        debug!(
            "[DEBUG] BLS_SIGNER_G2: Operator {} G2_X_c0={} G2_X_c1={} G2_Y_c0={} G2_Y_c1={}",
            hex!(operator_id.as_slice()),
            x.c0,
            x.c1,
            y.c0,
            y.c1
        );
    } else {
        debug!(
            "[DEBUG] BLS_SIGNER_G2: Operator {} G2 point is at infinity",
            hex!(operator_id.as_slice())
        );
    }

    // [DEBUG] Log operator's individual signature for aggregation verification
    if let (Some(x), Some(y)) = (signature_g1_point.x(), signature_g1_point.y()) {
        debug!(
            "[DEBUG] BLS_SIGNER_SIG: Operator {} SIG_X={} SIG_Y={}",
            hex!(operator_id.as_slice()),
            x,
            y
        );
    } else {
        debug!(
            "[DEBUG] BLS_SIGNER_SIG: Operator {} signature is point at infinity",
            hex!(operator_id.as_slice())
        );
    }

    // Add the operator's G2 pubkey and signature N times where N is the number of quorums.
    // The BLSSignatureChecker contract multiplies each operator's contribution by their
    // quorum count (see scalar_mul_tiny with countNumOnes in checkSignatures). This means
    // the aggregated APK_G2 and signature must include each operator's contribution
    // N times for N quorums they're staked in, to match the contract's computation.
    let quorum_count = operator_state.stake_per_quorum.len();
    for _ in 0..quorum_count {
        aggregated_operators.signers_agg_sig_g1 =
            Signature::new((aggregated_operators.signers_agg_sig_g1.g1_point().g1() + signature_g1_point).into());
        aggregated_operators.signers_apk_g2 =
            BlsG2Point::new((aggregated_operators.signers_apk_g2.g2() + operator_g2_pubkey).into());
    }

    debug!(
        "[DEBUG] BLS_SIGNER_AGG: Operator {} added G2/sig {} times (quorum_count={})",
        hex!(operator_id.as_slice()),
        quorum_count,
        quorum_count
    );

    // Update stake per quorum separately
    for (quorum_num, stake) in operator_state.stake_per_quorum.iter() {
        aggregated_operators
            .signers_total_stake_per_quorum
            .entry(*quorum_num)
            .and_modify(|v| *v += stake)
            .or_insert(*stake);
    }
    Ok(aggregated_operators.clone())
}

/// Converts a `BlsAggregationServiceResponse` to `NonSignerStakesAndSignature` contract format.
///
/// This function handles the conversion of BLS signatures from the aggregation service
/// response format to the contract-compatible format. It's used by both the standalone
/// aggregator service and the gateway's aggregator implementation to avoid code duplication.
///
/// # Arguments
///
/// * `response` - The BLS aggregation service response containing aggregated signatures
///
/// # Returns
///
/// Returns the contract-compatible `NonSignerStakesAndSignature` structure
///
/// # Errors
///
/// Returns `ChainIoError` if conversion fails (e.g., invalid BLS keys)
#[allow(clippy::result_large_err)]
pub fn convert_bls_response_to_contract_format(
    response: &BlsAggregationServiceResponse,
) -> Result<IBLSSignatureCheckerTypes::NonSignerStakesAndSignature, crate::error::ChainIoError> {
    use ark_ec::AffineRepr;
    use eigensdk::crypto_bls::{convert_to_g1_point, convert_to_g2_point};
    use newton_core::r#newton_prover_task_manager::BN254::{G1Point, G2Point};

    let task_id_hex = newton_core::hex!(response.task_id);

    // [DEBUG] Log input response summary for BN254 debugging - INFO level for CSV
    debug!(
        "[DEBUG] BLS_CONVERT_START: Task {} SIGNERS={} NON_SIGNERS={} QUORUM_APKS={} CREATED_BLOCK={} MSG_HASH={}",
        task_id_hex,
        response.signers_count,
        response.non_signers_pub_keys_g1.len(),
        response.quorum_apks_g1.len(),
        response.task_created_block,
        response.task_response_digest
    );

    let mut non_signer_pub_keys = Vec::<G1Point>::new();
    for (idx, pub_key) in response.non_signers_pub_keys_g1.iter().enumerate() {
        let has_x = pub_key.g1().x().is_some();

        if has_x {
            let g1 = convert_to_g1_point(pub_key.g1()).map_err(|e| {
                error!(
                    task_id = %task_id_hex,
                    non_signer_idx = idx,
                    error = %e,
                    "[DEBUG] Failed to convert non-signer G1 point"
                );
                crate::error::ChainIoError::BlsResponseConversionError {
                    reason: format!("Failed to convert G1 point: {}", e),
                }
            })?;

            // [DEBUG] Log the actual G1 point coordinates - INFO level for CSV visibility
            debug!(
                "[DEBUG] BLS_G1_NON_SIGNER: Task {} idx={} X={} Y={}",
                task_id_hex, idx, g1.X, g1.Y
            );

            non_signer_pub_keys.push(G1Point { X: g1.X, Y: g1.Y });
        } else {
            debug!(
                task_id = %task_id_hex,
                non_signer_idx = idx,
                "[DEBUG] Non-signer G1 public key has no X coordinate (skipping)"
            );
        }
    }

    let mut quorum_apks = Vec::<G1Point>::new();
    for (idx, pub_key) in response.quorum_apks_g1.iter().enumerate() {
        let is_infinity = pub_key.g1().infinity;

        if is_infinity {
            error!(
                task_id = %task_id_hex,
                quorum_idx = idx,
                "[DEBUG] Quorum APK is point at infinity - this will cause BN254 failure"
            );
            return Err(crate::error::ChainIoError::BlsResponseConversionError {
                reason: format!("Invalid BLS key found for task {}", task_id_hex),
            });
        }
        let g1 = convert_to_g1_point(pub_key.g1()).map_err(|e| {
            error!(
                task_id = %task_id_hex,
                quorum_idx = idx,
                error = %e,
                "[DEBUG] Failed to convert quorum APK G1 point"
            );
            crate::error::ChainIoError::BlsResponseConversionError {
                reason: format!("Failed to convert G1 point: {}", e),
            }
        })?;

        // [DEBUG] Log the actual quorum APK G1 coordinates - INFO level for CSV visibility
        debug!(
            "[DEBUG] BLS_G1_QUORUM_APK: Task {} idx={} X={} Y={}",
            task_id_hex, idx, g1.X, g1.Y
        );

        quorum_apks.push(G1Point { X: g1.X, Y: g1.Y });
    }

    // [DEBUG] Log signers APK G2 point - INFO level for CSV
    let signers_apk_g2_is_infinity = response.signers_apk_g2.g2().infinity;
    debug!(
        "[DEBUG] BLS_G2_CHECK: Task {} APK_G2_INFINITY={}",
        task_id_hex, signers_apk_g2_is_infinity
    );

    if signers_apk_g2_is_infinity {
        error!(
            task_id = %task_id_hex,
            "[DEBUG] Signers APK G2 is point at infinity - this will cause BN254 pairing failure"
        );
    }

    let apk_g2 = convert_to_g2_point(response.signers_apk_g2.g2()).map_err(|e| {
        error!(
            task_id = %task_id_hex,
            error = %e,
            "[DEBUG] Failed to convert signers APK G2 point"
        );
        crate::error::ChainIoError::BlsResponseConversionError {
            reason: format!("Failed to convert G2 point: {}", e),
        }
    })?;

    // [DEBUG] Log the actual signers APK G2 coordinates - INFO level for CSV visibility
    debug!(
        "[DEBUG] BLS_G2: Task {} APK_G2 X=[{}, {}] Y=[{}, {}]",
        task_id_hex, apk_g2.X[0], apk_g2.X[1], apk_g2.Y[0], apk_g2.Y[1]
    );

    // [DEBUG] Log aggregated signature G1 point - INFO level for CSV
    let agg_sig_is_infinity = response.signers_agg_sig_g1.g1_point().g1().infinity;
    debug!(
        "[DEBUG] BLS_G1_SIG_CHECK: Task {} SIG_INFINITY={}",
        task_id_hex, agg_sig_is_infinity
    );

    if agg_sig_is_infinity {
        error!(
            task_id = %task_id_hex,
            "[DEBUG] Aggregated signature is point at infinity - this will cause BN254 pairing failure"
        );
    }

    let sigma = convert_to_g1_point(response.signers_agg_sig_g1.g1_point().g1()).map_err(|e| {
        error!(
            task_id = %task_id_hex,
            error = %e,
            "[DEBUG] Failed to convert aggregated signature G1 point"
        );
        crate::error::ChainIoError::BlsResponseConversionError {
            reason: format!("Failed to convert G1 point: {}", e),
        }
    })?;

    // [DEBUG] Log the actual aggregated signature G1 coordinates - INFO level for CSV visibility
    debug!("[DEBUG] BLS_G1_SIGMA: Task {} X={} Y={}", task_id_hex, sigma.X, sigma.Y);

    // [DEBUG] Log the indices being used - INFO level for CSV
    debug!(
        "[DEBUG] BLS_INDICES: Task {} NON_SIGNER_BITMAP_IDX={:?} QUORUM_APK_IDX={:?} TOTAL_STAKE_IDX={:?} NON_SIGNER_STAKE_IDX_COUNT={}",
        task_id_hex,
        response.non_signer_quorum_bitmap_indices,
        response.quorum_apk_indices,
        response.total_stake_indices,
        response.non_signer_stake_indices.len()
    );

    let non_signer_stakes_and_signature =
        newton_core::r#newton_prover_task_manager::IBLSSignatureCheckerTypes::NonSignerStakesAndSignature {
            nonSignerPubkeys: non_signer_pub_keys.clone(),
            nonSignerQuorumBitmapIndices: response.non_signer_quorum_bitmap_indices.clone(),
            quorumApks: quorum_apks.clone(),
            apkG2: G2Point {
                X: apk_g2.X,
                Y: apk_g2.Y,
            },
            sigma: G1Point { X: sigma.X, Y: sigma.Y },
            quorumApkIndices: response.quorum_apk_indices.clone(),
            totalStakeIndices: response.total_stake_indices.clone(),
            nonSignerStakeIndices: response.non_signer_stake_indices.clone(),
        };

    // [DEBUG] Final summary before returning - include values in message text for CSV
    info!(
        task_id = %task_id_hex,
        non_signer_pubkeys_count = non_signer_pub_keys.len(),
        quorum_apks_count = quorum_apks.len(),
        signers_apk_g2_is_infinity = signers_apk_g2_is_infinity,
        agg_sig_is_infinity = agg_sig_is_infinity,
        "[DEBUG] BLS_CONVERT: Complete for task {} - NON_SIGNER_PUBKEYS={}, QUORUM_APKS={}, APK_G2_INFINITY={}, SIG_INFINITY={}",
        task_id_hex,
        non_signer_pub_keys.len(),
        quorum_apks.len(),
        signers_apk_g2_is_infinity,
        agg_sig_is_infinity
    );

    Ok(non_signer_stakes_and_signature)
}

#[cfg(test)]
mod tests {
    use super::{
        BlsAggregationServiceError, BlsAggregationServiceResponse, BlsAggregatorService, BlsServiceHandle,
        TaskMetadata, TaskSignature,
    };
    use alloy::primitives::{keccak256, FixedBytes, B256, U256};
    use eigensdk::crypto_bls::{BlsG1Point, BlsG2Point, BlsKeyPair, Signature};

    use eigensdk::{
        services_avsregistry::fake_avs_registry_service::FakeAvsRegistryService,
        types::{
            avs::{
                SignatureVerificationError,
                SignatureVerificationError::{DuplicateSignature, IncorrectSignature},
            },
            operator::{QuorumNum, QuorumThresholdPercentages},
            test::TestOperator,
        },
    };
    use newton_core::TaskId;
    use sha2::{Digest, Sha256};
    use std::{collections::HashMap, time::Duration, vec};
    use tokio::time::{sleep, Instant};

    const PRIVATE_KEY_1: &str = "13710126902690889134622698668747132666439281256983827313388062967626731803599";
    const PRIVATE_KEY_2: &str = "14610126902690889134622698668747132666439281256983827313388062967626731803500";
    const PRIVATE_KEY_3: &str = "15610126902690889134622698668747132666439281256983827313388062967626731803501";

    fn hash(task_response: u64) -> B256 {
        let mut hasher = Sha256::new();
        hasher.update(task_response.to_be_bytes());
        B256::from_slice(hasher.finalize().as_ref())
    }

    fn aggregate_g1_public_keys(operators: &[TestOperator]) -> BlsG1Point {
        operators
            .iter()
            .map(|op| op.bls_keypair.public_key().g1())
            .reduce(|a, b| (a + b).into())
            .map(BlsG1Point::new)
            .unwrap()
    }

    fn aggregate_g2_public_keys(operators: &[TestOperator]) -> BlsG2Point {
        operators
            .iter()
            .map(|op| op.bls_keypair.public_key_g2().g2())
            .reduce(|a, b| (a + b).into())
            .map(BlsG2Point::new)
            .unwrap()
    }

    fn aggregate_g1_signatures(signatures: &[Signature]) -> Signature {
        let agg = signatures
            .iter()
            .map(|s| s.g1_point().g1())
            .reduce(|a, b| (a + b).into())
            .unwrap();
        Signature::new(agg)
    }

    #[tokio::test]
    async fn test_1_quorum_1_operator_1_correct_signature() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(1).into();
        let task_created_block = 1;
        let quorum_numbers = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data

        let task_response_digest = hash(task_response);
        let bls_signature = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, vec![test_operator_1.clone()]);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_signature,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: 1,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![test_operator_1.bls_keypair.public_key()],
            signers_apk_g2: test_operator_1.bls_keypair.public_key_g2(),
            signers_agg_sig_g1: test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref()),
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
    }

    #[tokio::test]
    async fn test_1_quorum_2_operator_2_duplicated_signatures() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(1).into();
        let task_created_block = block_number;
        let quorum_numbers = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();
        let bls_signature_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_signature_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let second_signature_processing_result = handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_signature_1.clone(),
                test_operator_1.operator_id,
            ))
            .await;

        assert!(matches!(
            second_signature_processing_result,
            Err(BlsAggregationServiceError::SignatureVerificationError {
                task_id: t,
                operator_id: op_id,
                verification_error: SignatureVerificationError::DuplicateSignature,
            }) if t == task_id && op_id == test_operator_1.operator_id
        ));

        let bls_signature_2 = test_operator_2.bls_keypair.sign_message(task_response_digest.as_ref());

        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_signature_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let quorum_apks_g1 = aggregate_g1_public_keys(&test_operators);
        let signers_apk_g2 = aggregate_g2_public_keys(&test_operators);
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_signature_1, bls_signature_2]);
        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![quorum_apks_g1],
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
    }

    #[tokio::test]
    async fn test_1_quorum_3_operator_3_correct_signatures() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operator_3 = TestOperator {
            operator_id: U256::from(3).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(300)), (1u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_3.into()).unwrap(),
        };
        let test_operators = vec![
            test_operator_1.clone(),
            test_operator_2.clone(),
            test_operator_3.clone(),
        ];

        let block_number = 1;
        let task_id: TaskId = U256::from(1).into();
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_op_2 = test_operator_2.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_op_3 = test_operator_3.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_3.clone(),
                test_operator_3.operator_id,
            ))
            .await
            .unwrap();

        let quorum_apks_g1 = aggregate_g1_public_keys(&test_operators);
        let signers_apk_g2 = aggregate_g2_public_keys(&test_operators);
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1, bls_sig_op_2, bls_sig_op_3]);

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block: block_number,
            task_response_digest,
            signers_count: 3,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![quorum_apks_g1],
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
    }

    #[tokio::test]
    async fn test_2_quorum_2_operator_2_correct_signatures() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100u8, 100u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_op_2 = test_operator_2.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let quorum_apks_g1 = aggregate_g1_public_keys(&test_operators);
        // Each operator's G2 pubkey and signature is added N times where N is the number of
        // quorums they're staked in. The BLSSignatureChecker contract multiplies each operator's
        // contribution by their quorum count (scalar_mul_tiny with countNumOnes in checkSignatures).
        let signers_apk_g2 = aggregate_g2_public_keys(&[test_operators.clone(), test_operators].concat());
        let signers_agg_sig_g1 =
            aggregate_g1_signatures(&[bls_sig_op_1.clone(), bls_sig_op_1, bls_sig_op_2.clone(), bls_sig_op_2]);

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![quorum_apks_g1.clone(), quorum_apks_g1],
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
    }

    #[tokio::test]
    async fn test_2_concurrent_tasks_2_quorum_2_operator_2_correct_signatures() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100u8, 100u8];
        let time_to_expiry = Duration::from_secs(1);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        // initialize 2 concurrent tasks
        let task_1_id: TaskId = U256::from(1).into();
        let task_1_response = 123; // Initialize with appropriate data
        let task_1_response_digest = hash(task_1_response);
        let metadata1 = TaskMetadata::new(
            task_1_id,
            block_number,
            quorum_numbers.clone(),
            quorum_threshold_percentages.clone(),
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_1_receiver = handle.initialize_task(metadata1).await.unwrap();

        let task_2_id: TaskId = U256::from(2).into();
        let task_2_response = 234; // Initialize with appropriate data
        let task_2_response_digest = hash(task_2_response);
        let metadata2 = TaskMetadata::new(
            task_2_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let mut task_2_receiver = handle.initialize_task(metadata2).await.unwrap();

        let bls_sig_task_1_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_1_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_1_id,
                task_1_response_digest,
                bls_sig_task_1_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_task_1_op_2 = test_operator_2
            .bls_keypair
            .sign_message(task_1_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_1_id,
                task_1_response_digest,
                bls_sig_task_1_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_task_2_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_2_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_2_id,
                task_2_response_digest,
                bls_sig_task_2_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_task_2_op_2 = test_operator_2
            .bls_keypair
            .sign_message(task_2_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_2_id,
                task_2_response_digest,
                bls_sig_task_2_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let quorum_apks_g1 = aggregate_g1_public_keys(&test_operators);
        // Each operator's G2 pubkey and signature is added N times where N is the number of
        // quorums they're staked in. The BLSSignatureChecker contract multiplies each operator's
        // contribution by their quorum count (scalar_mul_tiny with countNumOnes in checkSignatures).
        let signers_apk_g2 = aggregate_g2_public_keys(&[test_operators.clone(), test_operators].concat());
        let signers_agg_sig_g1_task_1 = aggregate_g1_signatures(&[
            bls_sig_task_1_op_1.clone(),
            bls_sig_task_1_op_1,
            bls_sig_task_1_op_2.clone(),
            bls_sig_task_1_op_2,
        ]);

        let expected_response_task_1 = BlsAggregationServiceResponse {
            task_id: task_1_id,
            task_created_block: block_number,
            task_response_digest: task_1_response_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![quorum_apks_g1.clone(), quorum_apks_g1.clone()],
            signers_apk_g2: signers_apk_g2.clone(),
            signers_agg_sig_g1: signers_agg_sig_g1_task_1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let signers_agg_sig_g1_task_2 = aggregate_g1_signatures(&[
            bls_sig_task_2_op_1.clone(),
            bls_sig_task_2_op_1,
            bls_sig_task_2_op_2.clone(),
            bls_sig_task_2_op_2,
        ]);

        let expected_response_task_2 = BlsAggregationServiceResponse {
            task_id: task_2_id,
            task_created_block: block_number,
            task_response_digest: task_2_response_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![quorum_apks_g1.clone(), quorum_apks_g1.clone()],
            signers_apk_g2,
            signers_agg_sig_g1: signers_agg_sig_g1_task_2,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let first_response = task_1_receiver
            .recv()
            .await
            .expect("task 1 receiver channel should not be closed")
            .expect("should receive response from task 1");
        let second_response = task_2_receiver
            .recv()
            .await
            .expect("task 2 receiver channel should not be closed")
            .expect("should receive response from task 2");

        let (task_1_response, task_2_response) = if first_response.task_id == task_1_id {
            (first_response, second_response)
        } else {
            (second_response, first_response)
        };

        assert_eq!(expected_response_task_1, task_1_response);
        assert_eq!(expected_response_task_2, task_2_response);
    }

    #[tokio::test]
    async fn test_1_quorum_1_operator_0_signatures_task_expired() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100];
        let time_to_expiry = Duration::from_secs(1);
        let _task_response = 123; // Initialize with appropriate data

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, vec![test_operator_1.clone()]);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_1_quorum_2_operator_1_signatures_50_threshold() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![50u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);
        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let quorum_apks_g1 = aggregate_g1_public_keys(&test_operators);

        let signers_apk_g2: BlsG2Point = test_operator_1.bls_keypair.public_key_g2();

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: 1,
            non_signers_pub_keys_g1: vec![test_operator_2.bls_keypair.public_key()],
            non_signers_operators_ids: vec![test_operator_2.operator_id],
            quorum_apks_g1: vec![quorum_apks_g1],
            signers_apk_g2,
            signers_agg_sig_g1: bls_sig_op_1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
    }

    #[tokio::test]
    async fn test_1_quorum_2_operator_1_signatures_60_threshold() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![60u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);
        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_2_quorums_2_operators_which_just_take_1_quorum_2_correct_signatures() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            // Note the quorums is [0, 1], but operator id 1 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            // Note the quorums is [0, 1], but operator id 2 just stake 1.
            stake_per_quorum: HashMap::from([(1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };

        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100u8, 100u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_op_2 = test_operator_2.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let signers_apk_g2 = aggregate_g2_public_keys(&test_operators);
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1, bls_sig_op_2]);

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![
                test_operator_1.bls_keypair.public_key(),
                test_operator_2.bls_keypair.public_key(),
            ],
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
    }

    #[tokio::test]
    async fn test_2_quorums_3_operators_which_just_stake_1_quorum_50_threshold() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            // Note the quorums is [0, 1], but operator id 1 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            // Note the quorums is [0, 1], but operator id 2 just stake 1.
            stake_per_quorum: HashMap::from([(1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };

        let test_operator_3 = TestOperator {
            operator_id: U256::from(3).into(),
            // Note the quorums is [0, 1], but operator id 3 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_3.into()).unwrap(),
        };

        let test_operators = vec![
            test_operator_1.clone(),
            test_operator_2.clone(),
            test_operator_3.clone(),
        ];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![50u8, 50u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators.clone());
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_op_2 = test_operator_2.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();
        let signers_apk_g2 = aggregate_g2_public_keys(&[test_operator_1.clone(), test_operator_2.clone()]);
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1, bls_sig_op_2]);
        let quorum_apks_g1 = vec![
            aggregate_g1_public_keys(&[test_operator_1, test_operator_3.clone()]),
            aggregate_g1_public_keys(&[test_operator_2, test_operator_3.clone()]),
        ];

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![test_operator_3.bls_keypair.public_key()],
            non_signers_operators_ids: vec![test_operator_3.operator_id],
            quorum_apks_g1,
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
    }

    #[tokio::test]
    async fn test_2_quorums_3_operators_which_just_stake_1_quorum_60_threshold() {
        // results in `task expired`
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            // Note the quorums is [0, 1], but operator id 1 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            // Note the quorums is [0, 1], but operator id 2 just stake 1.
            stake_per_quorum: HashMap::from([(1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };

        let test_operator_3 = TestOperator {
            operator_id: U256::from(3).into(),
            // Note the quorums is [0, 1], but operator id 3 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_3.into()).unwrap(),
        };

        let test_operators = vec![
            test_operator_1.clone(),
            test_operator_2.clone(),
            test_operator_3.clone(),
        ];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![60u8, 60u8];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let bls_sig_op_2 = test_operator_2.bls_keypair.sign_message(task_response_digest.as_ref());

        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_2,
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_2_quorums_1_operator_which_just_take_1_quorum_1_signature_task_expired() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            // Note the quorums is [0, 1], but operator id 1 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100, 100];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, vec![test_operator_1.clone()]);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());

        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_2_quorums_2_operators_where_1_operator_just_take_1_quorum_1_signature_task_expired() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            // Note the quorums is [0, 1], but operator id 1 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            // Note the quorums is [0, 1], but operator id 2 just stake 1.
            stake_per_quorum: HashMap::from([(1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers: Vec<QuorumNum> = vec![0, 1];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100, 100];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn send_signature_of_task_not_initialized() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            // Note the quorums is [0, 1], but operator id 1 just stake 0.
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_response = 123; // Initialize with appropriate data
        let task_response_digest = hash(task_response);

        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, vec![test_operator_1.clone()]);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let bls_sig_op_1 = test_operator_1.bls_keypair.sign_message(task_response_digest.as_ref());
        let (handle, _) = bls_agg_service.start();
        let result = handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_digest,
                bls_sig_op_1,
                test_operator_1.operator_id,
            ))
            .await;

        assert!(matches!(
            result,
            Err(BlsAggregationServiceError::TaskNotFound { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_1_quorum_2_operator_2_signatures_on_2_different_msgs() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100u8];
        let time_to_expiry = Duration::from_secs(1);
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let task_response_1 = 123; // Initialize with appropriate data
        let task_response_1_digest = hash(task_response_1);
        let bls_sig_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_response_1_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_1_digest,
                bls_sig_op_1,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let task_response_2 = 456; // Initialize with appropriate data
        let task_response_2_digest = hash(task_response_2);
        let bls_sig_op_2 = test_operator_1
            .bls_keypair
            .sign_message(task_response_2_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_2_digest,
                bls_sig_op_2,
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_1_quorum_1_operator_1_invalid_signature() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let quorum_numbers = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123; // Initialize with appropriate data

        let wrong_task_response_digest = hash(task_response + 1);
        let bls_signature = test_operator_1.bls_keypair.sign_message(hash(task_response).as_ref());
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, vec![test_operator_1.clone()]);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let result = handle
            .process_signature(TaskSignature::new(
                task_id,
                wrong_task_response_digest,
                bls_signature.clone(),
                test_operator_1.operator_id,
            ))
            .await;

        assert!(matches!(
            result,
            Err(BlsAggregationServiceError::SignatureVerificationError {
                task_id: t,
                operator_id: op_id,
                verification_error: SignatureVerificationError::IncorrectSignature,
            }) if t == task_id && op_id == test_operator_1.operator_id
        ));

        // Also test that the aggregator service is not affected by the invalid signature, so the task should expire
        let response = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed");

        assert!(matches!(
            response,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));
    }

    #[tokio::test]
    async fn test_signatures_are_processed_during_window_after_quorum() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operator_3 = TestOperator {
            operator_id: U256::from(3).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_3.into()).unwrap(),
        };
        let test_operators = vec![
            test_operator_1.clone(),
            test_operator_2.clone(),
            test_operator_3.clone(),
        ];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let task_response = 123;
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![50_u8];
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let time_to_expiry = Duration::from_secs(5);
        let window_duration = Duration::from_secs(1);

        let start = Instant::now();
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        )
        .with_window_duration(window_duration);

        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let task_response_1_digest = hash(task_response);
        let bls_sig_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_response_1_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_1_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let task_response_2_digest = hash(task_response);
        let bls_sig_op_2 = test_operator_2
            .bls_keypair
            .sign_message(task_response_2_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_2_digest,
                bls_sig_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        // quorum reached here, window should be open receiving signatures for 1 second
        sleep(Duration::from_millis(500)).await;
        let task_response_3_digest = hash(task_response);
        let bls_sig_op_3 = test_operator_3
            .bls_keypair
            .sign_message(task_response_3_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_3_digest,
                bls_sig_op_3.clone(),
                test_operator_3.operator_id,
            ))
            .await
            .unwrap();

        let signers_apk_g2 = aggregate_g2_public_keys(&[
            test_operator_1.clone(),
            test_operator_2.clone(),
            test_operator_3.clone(),
        ]);
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1, bls_sig_op_2, bls_sig_op_3]);
        let quorum_apks_g1 = vec![aggregate_g1_public_keys(&[
            test_operator_1,
            test_operator_2,
            test_operator_3,
        ])];

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest: task_response_3_digest,
            signers_count: 3,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1,
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");

        let elapsed = start.elapsed();
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
        assert!(elapsed < time_to_expiry);
        assert!(elapsed >= window_duration);
    }

    #[tokio::test]
    async fn test_if_quorum_has_been_reached_and_the_task_expires_during_window_the_response_is_sent() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let task_response = 123;
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![40_u8];
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let time_to_expiry = Duration::from_secs(2);
        let window_duration = Duration::from_secs(10);

        let start = Instant::now();
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        )
        .with_window_duration(window_duration);
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let task_response_1_digest = hash(task_response);
        let bls_sig_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_response_1_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_1_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        // quorum reached here, window should be open receiving signatures

        let task_response_2_digest = hash(task_response);
        let bls_sig_op_2 = test_operator_2
            .bls_keypair
            .sign_message(task_response_2_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_2_digest,
                bls_sig_op_2.clone(),
                test_operator_2.operator_id,
            ))
            .await
            .unwrap();

        let signers_apk_g2 = aggregate_g2_public_keys(&[test_operator_1.clone(), test_operator_2.clone()]);
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1, bls_sig_op_2]);
        let quorum_apks_g1 = vec![aggregate_g1_public_keys(&[test_operator_1, test_operator_2])];

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest: task_response_2_digest,
            signers_count: 2,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1,
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");

        let elapsed = start.elapsed();
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
        assert!(elapsed >= time_to_expiry);
        assert!(elapsed < window_duration);
    }

    #[tokio::test]
    async fn test_if_window_duration_is_zero_no_signatures_are_aggregated_after_reaching_quorum() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let task_response = 123;
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![40_u8];
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let time_to_expiry = Duration::from_secs(2);
        let window_duration = Duration::ZERO;

        let start = Instant::now();
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        )
        .with_window_duration(window_duration);
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let task_response_1_digest = hash(task_response);
        let bls_sig_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_response_1_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_1_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        // quorum reached here but window duration is zero, so no more signatures should be aggregated
        sleep(Duration::from_millis(1)).await;

        let task_response_2_digest = hash(task_response);
        let bls_sig_op_2 = test_operator_2
            .bls_keypair
            .sign_message(task_response_2_digest.as_ref());
        let process_signature_result = handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_2_digest,
                bls_sig_op_2,
                test_operator_2.operator_id,
            ))
            .await;
        assert!(matches!(
            process_signature_result,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));

        let signers_apk_g2 = aggregate_g2_public_keys(std::slice::from_ref(&test_operator_1));
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1]);
        let quorum_apks_g1 = vec![aggregate_g1_public_keys(&[test_operator_1, test_operator_2.clone()])];

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest: task_response_1_digest,
            signers_count: 1,
            non_signers_pub_keys_g1: vec![test_operator_2.bls_keypair.public_key()],
            non_signers_operators_ids: vec![test_operator_2.operator_id],
            quorum_apks_g1,
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");

        let elapsed = start.elapsed();
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
        assert!(elapsed < time_to_expiry);
    }

    #[tokio::test]
    async fn test_no_signatures_are_aggregated_after_window() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };
        let test_operator_2 = TestOperator {
            operator_id: U256::from(2).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_2.into()).unwrap(),
        };
        let test_operators = vec![test_operator_1.clone(), test_operator_2.clone()];
        let block_number = 1;
        let task_id: TaskId = U256::from(0).into();
        let task_created_block = block_number;
        let task_response = 123;
        let quorum_numbers: Vec<QuorumNum> = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![40_u8];
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, test_operators);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);

        let time_to_expiry = Duration::from_secs(5);
        let window_duration = Duration::from_secs(1);

        let start = Instant::now();
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        )
        .with_window_duration(window_duration);
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        let task_response_1_digest = hash(task_response);
        let bls_sig_op_1 = test_operator_1
            .bls_keypair
            .sign_message(task_response_1_digest.as_ref());
        handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_1_digest,
                bls_sig_op_1.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        // quorum reached here, window should be open for 1 second
        sleep(Duration::from_secs(2)).await;

        let task_response_2_digest = hash(task_response);
        let bls_sig_op_2 = test_operator_2
            .bls_keypair
            .sign_message(task_response_2_digest.as_ref());
        let process_signature_result = handle
            .process_signature(TaskSignature::new(
                task_id,
                task_response_2_digest,
                bls_sig_op_2,
                test_operator_2.operator_id,
            ))
            .await;
        assert!(matches!(
            process_signature_result,
            Err(BlsAggregationServiceError::TaskExpired { task_id: t, .. }) if t == task_id
        ));

        let signers_apk_g2 = aggregate_g2_public_keys(std::slice::from_ref(&test_operator_1));
        let signers_agg_sig_g1 = aggregate_g1_signatures(&[bls_sig_op_1]);
        let quorum_apks_g1 = vec![aggregate_g1_public_keys(&[test_operator_1, test_operator_2.clone()])];

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest: task_response_1_digest,
            signers_count: 1,
            non_signers_pub_keys_g1: vec![test_operator_2.bls_keypair.public_key()],
            non_signers_operators_ids: vec![test_operator_2.operator_id],
            quorum_apks_g1,
            signers_apk_g2,
            signers_agg_sig_g1,
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");

        let elapsed = start.elapsed();
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
        assert!(elapsed < time_to_expiry);
    }

    #[tokio::test]
    async fn test_1_quorum_1_operator_1_correct_signature_multichain() {
        let test_operator_1 = TestOperator {
            operator_id: U256::from(1).into(),
            stake_per_quorum: HashMap::from([(0u8, U256::from(100)), (1u8, U256::from(200))]),
            bls_keypair: BlsKeyPair::new(PRIVATE_KEY_1.into()).unwrap(),
        };

        let block_number = 1;
        let task_id: TaskId = U256::from(1).into();
        let task_created_block = 1;
        let quorum_numbers = vec![0];
        let quorum_threshold_percentages: QuorumThresholdPercentages = vec![100];
        let time_to_expiry = Duration::from_secs(1);
        let task_response = 123;
        let reference_timestamp: u32 = 1000;

        let task_response_digest = hash(task_response);

        let bn254_certificate_typehash = keccak256("BN254Certificate(uint32 referenceTimestamp,bytes32 messageHash)");
        let mut hasher = Sha256::new();
        hasher.update(bn254_certificate_typehash);
        hasher.update([0u8; 28]);
        hasher.update(reference_timestamp.to_be_bytes());
        hasher.update(task_response_digest);
        let digest = FixedBytes::from_slice(hasher.finalize().as_ref());

        let bls_signature = test_operator_1.bls_keypair.sign_message(digest.as_ref());
        let fake_avs_registry_service = FakeAvsRegistryService::new(block_number, vec![test_operator_1.clone()]);
        let bls_agg_service = BlsAggregatorService::new(fake_avs_registry_service);
        let metadata = TaskMetadata::new(
            task_id,
            block_number,
            quorum_numbers,
            quorum_threshold_percentages,
            time_to_expiry,
        );
        let (handle, _aggregator_response) = bls_agg_service.start();
        let mut task_receiver = handle.initialize_task(metadata).await.unwrap();

        handle
            .process_signature(TaskSignature::new(
                task_id,
                digest,
                bls_signature.clone(),
                test_operator_1.operator_id,
            ))
            .await
            .unwrap();

        let expected_agg_service_response = BlsAggregationServiceResponse {
            task_id,
            task_created_block,
            task_response_digest: digest,
            signers_count: 1,
            non_signers_pub_keys_g1: vec![],
            non_signers_operators_ids: vec![],
            quorum_apks_g1: vec![test_operator_1.bls_keypair.public_key()],
            signers_apk_g2: test_operator_1.bls_keypair.public_key_g2(),
            signers_agg_sig_g1: test_operator_1.bls_keypair.sign_message(digest.as_ref()),
            non_signer_quorum_bitmap_indices: vec![],
            quorum_apk_indices: vec![],
            total_stake_indices: vec![],
            non_signer_stake_indices: vec![],
        };

        let actual = task_receiver
            .recv()
            .await
            .expect("task receiver channel should not be closed")
            .expect("should receive successful response");
        assert_eq!(expected_agg_service_response, actual);
        assert_eq!(task_id, actual.task_id);
        assert_eq!(actual.signers_apk_g2, test_operator_1.bls_keypair.public_key_g2());
        assert_eq!(actual.signers_agg_sig_g1.g1_point(), bls_signature.g1_point());
        assert!(actual.non_signers_pub_keys_g1.is_empty());
    }
}