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
//! Crucial structs, enums, functions and types to create computation graphs.
use atomic_refcell::AtomicRefCell;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::hash::Hasher;
use std::ptr;
use std::sync::Arc;
use std::sync::Weak;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::constants;
use crate::custom_ops::CustomOperation;
use crate::data_types::{get_size_estimation_in_bits, ArrayShape, ScalarType, Type};
use crate::data_values::Value;
use crate::errors::Result;
use crate::type_inference::{create_type_inference_worker, TypeInferenceWorker};

use crate::version::{VersionedData, DATA_VERSION};

/// This enum represents different types of slice elements that are used to create indexing slices (see [Slice] and [Graph::get_slice]).
///
/// The semantics is similar to [the NumPy slice indexing](https://numpy.org/doc/stable/user/basics.indexing.html).

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum SliceElement {
    /// Single index of a given array dimension.
    ///
    /// The index is given by a signed integer. If negative, the index is interpreted as in [NumPy](https://numpy.org/doc/stable/user/basics.indexing.html).
    ///
    /// For example, to choose all the elements of an array with the last index in the first dimension and the first index in the second dimension, one can use a slice `vec![SingleIndex(-1), SingleIndex(0)]`.
    SingleIndex(i64),
    /// Sub-array denotes a range of indices of a given array dimension.
    ///
    /// It follows the description of [the NumPy basic slice](https://numpy.org/doc/stable/user/basics.indexing.html), which is defined by 3 signed integers: `start`, `stop`, `step`. `step` can't be equal to zero.
    ///
    /// For example, to choose all the elements of an array with even indices in the first dimension, one can use a slice `vec![SubArray(Some(0), None, Some(2))].
    SubArray(Option<i64>, Option<i64>, Option<i64>),
    /// Ellipsis denotes several dimensions where indices are not restricted.
    ///
    /// For example, to choose all the elements of an array with index `0` in the first dimension and index `2` in the last dimension, one can use a slice `vec![SingleIndex(0), Ellipsis, SingleIndex(2)]`.
    Ellipsis,
}

/// Slice type denotes an indexing slice (see [NumPy slicing](https://numpy.org/doc/stable/user/basics.indexing.html)).
///
/// It is a vector of slice elements that describes the indices of a sub-array in any appropriate array.
pub type Slice = Vec<SliceElement>;

#[doc(hidden)]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum Operation {
    Input(Type),
    Add,
    Subtract,
    Multiply,
    // Dot operation follows the numpy (tensor)dot semantics: https://numpy.org/doc/stable/reference/generated/numpy.dot.html
    Dot,
    // Matmul operation follows the numpy matmul semantics: https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
    // In particular, unlike Dot, it doesn't support scalar inputs.
    Matmul,
    Truncate(u64),
    Sum(ArrayShape),
    PermuteAxes(ArrayShape),
    Get(ArrayShape),
    GetSlice(Slice),
    Reshape(Type),
    NOP,
    Random(Type),
    PRF(u64, Type),
    Stack(ArrayShape),
    Constant(Type, Value),
    A2B,
    B2A(ScalarType),
    CreateTuple,
    CreateNamedTuple(Vec<String>),
    CreateVector(Type),
    TupleGet(u64),
    NamedTupleGet(String),
    VectorGet,
    Zip,
    Repeat(u64),
    Call,
    Iterate,
    ArrayToVector,
    VectorToArray,
    Custom(CustomOperation),
}

impl fmt::Display for Operation {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let operation_name = if let Operation::Custom(custom_op) = self {
            custom_op.get_name()
        } else {
            let operation_w_type_str = format!("{:?}", *self);
            let split_for_operation = operation_w_type_str.split('(');
            let vec_operation_and_types: Vec<&str> = split_for_operation.collect();
            if vec_operation_and_types.is_empty() {
                "-null-".to_owned()
            } else {
                vec_operation_and_types[0].to_owned()
            }
        };
        write!(f, "{}", operation_name)
    }
}

struct NodeBody {
    graph: WeakGraph,
    node_dependencies: Vec<WeakNode>,
    graph_dependencies: Vec<WeakGraph>,
    operation: Operation,
    id: u64,
}

#[derive(Serialize, Deserialize)]
struct SerializableNodeBody {
    node_dependencies: Vec<u64>,
    graph_dependencies: Vec<u64>,
    operation: Operation,
}

type NodeBodyPointer = Arc<AtomicRefCell<NodeBody>>;

/// A structure that stores a pointer to a computation graph node that corresponds to an operation.
///
/// [Clone] trait duplicates the pointer, not the underlying nodes.
///
/// [PartialEq] trait compares pointers, not the related nodes.
///
/// # Example
///
/// ```
/// # use ciphercore_base::graphs::create_context;
/// # use ciphercore_base::data_types::{scalar_type, BIT};
/// let c = create_context().unwrap();
/// let g = c.create_graph().unwrap();
/// let t = scalar_type(BIT);
/// let n1 = g.input(t.clone()).unwrap();
/// let n2 = g.input(t).unwrap();
/// assert!(n1 != n2);
/// let n3 = n1.clone();
/// assert!(n1 == n3);
/// ```
pub struct Node {
    body: NodeBodyPointer,
}

type SerializableNode = Arc<SerializableNodeBody>;

impl Clone for Node {
    /// Returns a new [Node] value with a copy of the pointer to a node.
    fn clone(&self) -> Self {
        Node {
            body: self.body.clone(),
        }
    }
}

impl PartialEq for Node {
    /// Tests whether `self` and `other` nodes are equal via comparison of their respective pointers.
    ///
    /// # Arguments
    ///
    /// `other` - another [Node] value
    ///
    /// # Returns
    ///
    /// `true` if `self` and `other` are equal, `false` otherwise
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.body, &other.body)
    }
}

impl Eq for Node {}

impl Hash for Node {
    /// Hashes the node pointer.
    ///
    /// # Arguments
    ///
    /// `state` - state of a hash function that is changed after hashing the node
    fn hash<H: Hasher>(&self, state: &mut H) {
        ptr::hash(&*self.body, state);
    }
}

impl Node {
    /// Returns the parent graph that contains the node.
    ///
    /// # Returns
    ///
    /// Parent graph of the node
    pub fn get_graph(&self) -> Graph {
        self.body.borrow().graph.upgrade()
    }

    /// Returns the dependency nodes that are used to compute the value in the current node.
    ///
    /// # Returns
    ///
    /// Vector of nodes used by the node to perform its operation
    pub fn get_node_dependencies(&self) -> Vec<Node> {
        self.body
            .borrow()
            .node_dependencies
            .iter()
            .map(|n| n.upgrade())
            .collect()
    }

    /// Returns the dependency graphs that are used to compute the value in the current node.
    ///
    /// These dependencies are non-empty only for `Call` and `Iterate` operations.
    ///
    /// # Returns
    ///
    /// Vector of graphs used by the node to perform its operation
    pub fn get_graph_dependencies(&self) -> Vec<Graph> {
        self.body
            .borrow()
            .graph_dependencies
            .iter()
            .map(|g| g.upgrade())
            .collect()
    }

    /// Returns the operation associated with the node.
    ///
    /// # Returns
    ///
    /// Operation associated with the node
    pub fn get_operation(&self) -> Operation {
        self.body.borrow().operation.clone()
    }

    /// Returns the ID of the node.
    ///
    /// A node ID is a serial number of a node between `0` and `n-1` where `n` is the number of nodes in the parent graph.
    /// This number is equal to the number of nodes in the parent graph before this node was added to it.
    ///
    /// # Returns
    ///
    /// Node ID
    pub fn get_id(&self) -> u64 {
        self.body.borrow().id
    }

    /// Returns the pair of the parent graph ID and node ID
    ///
    /// # Returns
    ///
    /// (Graph ID, Node ID)
    pub fn get_global_id(&self) -> (u64, u64) {
        (self.get_graph().get_id(), self.get_id())
    }

    fn make_serializable(&self) -> SerializableNode {
        Arc::new(SerializableNodeBody {
            node_dependencies: self
                .get_node_dependencies()
                .iter()
                .map(|n| n.get_id())
                .collect(),
            graph_dependencies: self
                .get_graph_dependencies()
                .iter()
                .map(|n| n.get_id())
                .collect(),
            operation: self.get_operation(),
        })
    }

    /// Returns the type of the value computed by the node.
    ///
    /// # Returns
    ///
    /// Output type of the node operation
    pub fn get_type(&self) -> Result<Type> {
        let context = self.get_graph().get_context();
        let mut context_body = context.body.borrow_mut();
        if let Some(tc) = &mut context_body.type_checker {
            tc.process_node(self.clone())
        } else {
            Err(runtime_error!("Type checker is not available"))
        }
    }
}

impl Node {
    fn downgrade(&self) -> WeakNode {
        WeakNode {
            body: Arc::downgrade(&self.body),
        }
    }
}
type WeakNodeBodyPointer = Weak<AtomicRefCell<NodeBody>>;

struct WeakNode {
    body: WeakNodeBodyPointer,
}

impl WeakNode {
    //upgrade function panics if the the Node pointer it downgraded from went out of scope
    fn upgrade(&self) -> Node {
        Node {
            body: self.body.upgrade().unwrap(),
        }
    }
}

impl Clone for WeakNode {
    fn clone(&self) -> Self {
        WeakNode {
            body: self.body.clone(),
        }
    }
}

struct GraphBody {
    finalized: bool,
    nodes: Vec<Node>,
    output_node: Option<WeakNode>,
    id: u64,
    context: WeakContext,
}

#[derive(Serialize, Deserialize)]
struct SerializableGraphBody {
    finalized: bool,
    nodes: Vec<SerializableNode>,
    output_node: Option<u64>,
}

type GraphBodyPointer = Arc<AtomicRefCell<GraphBody>>;

/// A structure that stores a pointer to a computation graph, where every node corresponds to an operation.
///
/// [Clone] trait duplicates the pointer, not the underlying graph.
///
/// [PartialEq] trait compares pointers, not the related graphs.
///
/// # Example
///
/// ```
/// # use ciphercore_base::graphs::create_context;
/// let c = create_context().unwrap();
/// let g1 = c.create_graph().unwrap();
/// let g2 = c.create_graph().unwrap();
/// assert_ne!(g1, g2);
/// let g3 = g1.clone();
/// assert_eq!(g1, g3);
/// ```
pub struct Graph {
    body: GraphBodyPointer,
}

type SerializableGraph = Arc<SerializableGraphBody>;

impl fmt::Debug for Graph {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Graph")
            .field("body", &self.body.as_ptr())
            .finish()
    }
}

impl Clone for Graph {
    /// Returns a new [Graph] value with a copy of the pointer to a computation graph.
    fn clone(&self) -> Self {
        Graph {
            body: self.body.clone(),
        }
    }
}

impl PartialEq for Graph {
    /// Tests whether `self` and `other` graphs are equal via comparison of their respective pointers.
    ///
    /// # Arguments
    ///
    /// `other` - another [Graph] value
    ///
    /// # Returns
    ///
    /// `true` if `self` and `other` are equal, `false` otherwise
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.body, &other.body)
    }
}

impl Eq for Graph {}

impl Hash for Graph {
    /// Hashes the graph pointer.
    ///
    /// # Arguments
    ///
    /// `state` - state of a hash function that is changed after hashing the graph
    fn hash<H: Hasher>(&self, state: &mut H) {
        ptr::hash(&*self.body, state);
    }
}

impl Graph {
    /// Adds an operation node to the graph and returns it.
    ///
    /// # Arguments
    ///
    /// * `node_dependencies` - vector of nodes necessary to perform the given operation
    /// * `graph_dependencies` - vector of graphs necessary to perform the given operation
    /// * `operation` - operation performed by the node
    ///
    /// # Returns
    ///
    /// New operation node that gets added
    pub(crate) fn add_node(
        &self,
        node_dependencies: Vec<Node>,
        graph_dependencies: Vec<Graph>,
        operation: Operation,
    ) -> Result<Node> {
        if self.is_finalized() {
            return Err(runtime_error!("Can't add a node to a finalized graph"));
        }
        for dependency in &node_dependencies {
            if dependency.get_graph() != *self
                || dependency.get_id() >= self.body.borrow().nodes.len() as u64
                || self.body.borrow().nodes[dependency.get_id() as usize] != *dependency
            {
                return Err(runtime_error!(
                    "Can't add a node with invalid node dependencies"
                ));
            }
        }
        for dependency in &graph_dependencies {
            if dependency.get_context() != self.get_context()
                || !dependency.is_finalized()
                || dependency.get_id() >= self.get_id()
            {
                return Err(runtime_error!(
                    "Can't add a node with invalid graph dependencies"
                ));
            }
        }
        let id = self.body.borrow().nodes.len() as u64;
        let result = Node {
            body: Arc::new(AtomicRefCell::new(NodeBody {
                graph: self.downgrade(),
                node_dependencies: node_dependencies.iter().map(|n| n.downgrade()).collect(),
                graph_dependencies: graph_dependencies.iter().map(|g| g.downgrade()).collect(),
                operation,
                id,
            })),
        };
        {
            let mut cell = self.body.borrow_mut();
            cell.nodes.push(result.clone());
        }
        let mut context_has_type_checker = false;
        {
            let context = self.get_context();
            let mut context_cell = context.body.borrow_mut();
            let type_checker = &mut context_cell.type_checker;
            if type_checker.is_some() {
                context_has_type_checker = true;
            }
        }
        if context_has_type_checker {
            let type_checking_result = result.get_type();
            if type_checking_result.is_err() {
                self.remove_last_node(result)?;
                return Err(type_checking_result.err().expect("Should not be here"));
            }
            let type_result = type_checking_result?;

            let size_estimate = get_size_estimation_in_bits(type_result);
            if size_estimate.is_err() {
                self.remove_last_node(result)?;
                return Err(runtime_error!("Trying to add a node with invalid size"));
            }
            if size_estimate? > constants::MAX_INDIVIDUAL_NODE_SIZE {
                self.remove_last_node(result)?;
                return Err(runtime_error!(
                    "Trying to add a node larger than MAX_INDIVIDUAL_NODE_SIZE"
                ));
            }

            let context = self.get_context();
            let size_checking_result = context.try_update_total_size(result.clone());
            if size_checking_result.is_err() {
                self.remove_last_node(result)?;
                return Err(size_checking_result.err().expect("Should not be here"));
            }
        }
        Ok(result)
    }

    fn remove_last_node(&self, n: Node) -> Result<()> {
        if n.get_graph() != *self {
            return Err(runtime_error!(
                "The node to be removed from a different graph"
            ));
        }
        {
            let cell = self.body.borrow();
            if n != *cell
                .nodes
                .last()
                .ok_or_else(|| runtime_error!("Nodes list is empty"))?
            {
                return Err(runtime_error!(
                    "The node to be removed is not the last node"
                ));
            }
        };
        let context = self.get_context();
        context.unregister_node(n.clone())?;
        let mut context_body = context.body.borrow_mut();
        if let Some(tc) = &mut context_body.type_checker {
            tc.unregister_node(n)?;
        }
        let mut cell = self.body.borrow_mut();
        cell.nodes.pop();
        Ok(())
    }

    /// Adds an input node to the graph and returns it.
    ///
    /// During evaluation, input nodes require values to be supplied.
    ///
    /// # Arguments
    ///
    /// `input_type` - type of a new input node
    ///
    /// # Returns
    ///
    /// New input node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// ```
    pub fn input(&self, input_type: Type) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Input(input_type))
    }

    /// Adds a node that sums two arrays or scalars of the same scalar type elementwise.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, adding two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first term (array or scalar)
    /// * `b` - node containing the second term (array or scalar)
    ///
    /// # Returns
    ///
    /// New addition node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.add(n1, n2).unwrap();
    /// ```
    pub fn add(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Add)
    }

    /// Adds a node that subtracts two arrays or scalars of the same scalar type elementwise.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, subtracting two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the minuend (array of scalar)
    /// * `b` - node containing the subtrahend (array of scalar)
    ///
    /// # Returns
    ///
    /// New subtraction node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.subtract(n1, n2).unwrap();
    /// ```
    pub fn subtract(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Subtract)
    }

    /// Adds a node that multiplies two arrays or scalars of the same scalar type elementwise.
    ///
    /// If input shapes are different, the broadcasting rules are applied (see [the NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)). For example, multiplication of two arrays of shapes `[10,1,7]` and `[8,1]` results in an array of shape `[10,8,7]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first factor (array of scalar)
    /// * `b` - node containing the second factor (array of scalar)
    ///
    /// # Returns
    ///
    /// New multiplication node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.multiply(n1, n2).unwrap();
    /// ```
    pub fn multiply(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Multiply)
    }

    /// Adds a node that computes the dot product according to [the NumPy rules](https://numpy.org/doc/stable/reference/generated/numpy.dot.html):
    /// * if both factors are 1-dimensional arrays, return their inner product;
    /// * if both factors are 2-dimensional arrays, return their matrix product;
    /// * if one of the factors is scalar, return the result of [multiply](Graph::multiply);
    /// * if the first factor is n-dimensional and the second one is 1-dimensional,
    /// compute the elementwise multiplication and return the sum over the last axis.
    /// * if both factors are n-dimensional (n>2), return the sum product
    /// over the last axis of the first factor and the second-to-last axis of the second factor, i.e.
    ///
    /// `dot(A, B)[i,j,k,m] = sum(A[i,j,:] * B[k,:,m])` (in the NumPy notation).
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first factor (array or scalar)
    /// * `b` - node containing the second factor (array or scalar)
    ///
    /// # Returns
    ///
    /// New dot product node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![10], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = g.dot(n1, n2).unwrap();
    /// ```
    pub fn dot(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Dot)
    }

    /// Adds a node that computes the matrix product of two arrays according to [the NumPy rules](https://numpy.org/doc/stable/reference/generated/numpy.matmul.html).
    ///
    /// Each array is represented as an array of 2-dimensional matrix elements and this node returns the elementwise product of such matrix arrays.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing the first array
    /// * `b` - node containing the second array
    ///
    /// # Returns
    ///
    /// New matrix product node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![2, 3], INT32);
    /// let t2 = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.matmul(n1, n2).unwrap();
    /// ```
    pub fn matmul(&self, a: Node, b: Node) -> Result<Node> {
        self.add_node(vec![a, b], vec![], Operation::Matmul)
    }

    /// Adds a node that divides a scalar or each entry of an array by a positive constant integer `scale`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing a scalar or an array
    /// * `scale` - positive integer
    ///
    /// # Returns
    ///
    /// New truncate node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.truncate(n1, 4).unwrap();
    /// ```
    pub fn truncate(&self, a: Node, scale: u64) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Truncate(scale))
    }

    /// Adds a node that computes the sum of entries of an array along given axes (see [numpy.sum](https://numpy.org/doc/stable/reference/generated/numpy.sum.html)).
    ///
    /// For example, summing the array `[[1000, 200], [30, 4]]` along the first or the second axes results in the arrays `[1030,204]` or `[1200,34]`, respectively. Summing along both axes yields `1234`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `axes` - indices of the axes of `a`
    ///
    /// # Returns
    ///
    /// New sum node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.sum(n1, axes).unwrap();
    /// ```
    pub fn sum(&self, a: Node, axes: ArrayShape) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Sum(axes))
    }

    /// Adds a node that permutes an array along given axes (see [numpy.transpose](https://numpy.org/doc/stable/reference/generated/numpy.transpose.html)). This function generalizes matrix transposition.
    ///
    /// For example, permutation of an array of shape `[a,b,c]` with permutation `[2,0,1]` results in an array of shape `[c,a,b]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `axes` - indices of the axes of `a`
    ///
    /// # Returns
    ///
    /// New node with permuted axes
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0, 2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.permute_axes(n1, axes).unwrap();
    /// ```
    pub fn permute_axes(&self, a: Node, axes: ArrayShape) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::PermuteAxes(axes))
    }

    /// Adds a node that extracts a sub-array with a given index. This is a special case of [get_slice](Graph::get_slice) and corresponds to single element indexing as in [NumPy](https://numpy.org/doc/stable/user/basics.indexing.html).
    ///
    /// For example, given an array `A` of shape `[a,b,c,d]`, its subarray `B` of shape `[c,d]` with index `[i,j]` can be extracted as follows
    ///
    /// `B = A[i,j,:,:]` (in the NumPy notation)
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `index` - index of a sub-array
    ///
    /// # Returns
    ///
    /// New node containing an extracted sub-array
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let index = vec![2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.get(n1, index).unwrap();
    /// ```
    pub fn get(&self, a: Node, index: ArrayShape) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Get(index))
    }

    /// Adds a node that extracts a sub-array corresponding to a given slice.
    ///
    /// Our slicing conventions follow [the NumPy rules](https://numpy.org/doc/stable/user/basics.indexing.html).
    ///
    /// For example, given an array `A` of shape `[a,b]`, its subarray `B` containing only the last 3 rows of `A` can be extracted as follows
    ///
    /// `get_slice(A, [-3::])[i,j] = A[a-3+i,j]`.
    ///
    /// Slices are defined as vectors of [SliceElements](SliceElement) that have 3 possible types:
    ///
    /// * [SingleIndex(`i64`)](SliceElement::SingleIndex) is used to extract all the elements with a given index in a respective dimension,
    /// * [SubArray(`Option<i64>, Option<i64>, Option<i64>`)](SliceElement::SubArray) describes the range of indices that should be extracted over a certain dimension (similar to the `a:b:c` notation in [NumPy](https://numpy.org/doc/stable/user/basics.indexing.html))
    /// * [Ellipsis](SliceElement::Ellipsis) describes several consecutive dimensions that must be extracted in full, e.g. the slice `[i,...,j]` can be used to extract all the elements with the index `i` in the first dimension and the index `j` in the last one, while the indices of all the other dimensions have no constraints. See [the NumPy slicing](https://numpy.org/doc/stable/user/basics.indexing.html) for more details.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array
    /// * `slice` - array slice
    ///
    /// # Returns
    ///
    /// New node containing an extracted sub-array
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, SliceElement};
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let slice = vec![SliceElement::Ellipsis, SliceElement::SubArray(None, None, Some(-2))];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.get_slice(n1, slice).unwrap();
    /// ```
    pub fn get_slice(&self, a: Node, slice: Slice) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::GetSlice(slice))
    }

    /// Adds a node that reshapes a value to a given compatible type (similar to [numpy.reshape](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.reshape.html?highlight=reshape#numpy.ndarray.reshape), but more general). Specifically,
    ///
    /// * if the input value is an array, it can be reshaped to any array with the same number of elements;
    /// * if the input value in the flattened form contains `n` arrays or scalars, it can be reshaped to any type with the same number of arrays and scalars. Each array can be reshaped as in the above rule.
    ///
    /// For example, an array of shape `[3,10,5]` can be reshaped to `[2,75]`. A tuple with arrays of shapes `[3,4]`, `[12]`, `[2,6]` can be reshaped to a vector with 3 array elements of shape `[2,2,3]`.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing a value
    /// * `new_type` - type
    ///
    /// # Returns
    ///
    /// New node with a reshaped value
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let old_t = array_type(vec![3, 2, 3], INT32);
    /// let new_t = array_type(vec![3,6], INT32);
    /// let n1 = g.input(old_t).unwrap();
    /// let n2 = g.reshape(n1, new_t).unwrap();
    /// ```
    pub fn reshape(&self, a: Node, new_type: Type) -> Result<Node> {
        let size_estimate = get_size_estimation_in_bits(new_type.clone());
        if size_estimate.is_err() {
            return Err(runtime_error!(
                "Trying to add a reshape node with invalid type size"
            ));
        }
        if size_estimate? > constants::MAX_INDIVIDUAL_NODE_SIZE {
            return Err(runtime_error!(
                "Trying to add a reshape node larger than MAX_INDIVIDUAL_NODE_SIZE"
            ));
        }
        self.add_node(vec![a], vec![], Operation::Reshape(new_type))
    }

    pub(crate) fn nop(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::NOP)
    }

    /// Adds a node creating a random value of a given type.
    ///
    /// **WARNING**: this function should not be used before MPC compilation.
    ///
    /// # Arguments
    ///
    /// `output_type` - type of a constant
    ///
    /// # Returns
    ///
    /// New random node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.random(t).unwrap();
    /// ```
    #[doc(hidden)]
    pub fn random(&self, output_type: Type) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Random(output_type))
    }

    pub(crate) fn prf(&self, key: Node, iv: u64, output_type: Type) -> Result<Node> {
        self.add_node(vec![key], vec![], Operation::PRF(iv, output_type))
    }

    /// Adds a node that joins a sequence of arrays governed by a given shape.
    ///
    /// The input arrays should have the same shape or be able to be broadcast to the same shape.
    ///
    /// For example, stacking 2 arrays of shapes `[2,2]` and `[2,1]` with the outer shape `[2]` works as follows
    ///
    /// `stack(arrays=[[[1,2],[3,4]], [5,6]], shape=[2]) = [[[1,2],[3,4]], [[5,5], [6,6]]]`
    ///
    /// # Arguments
    ///
    /// * `nodes` - vector of nodes containing arrays
    /// * `outer_shape` - shape defining how the input arrays are arranged in the resulting array
    ///
    /// # Returns
    ///
    /// New stack node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let shape = vec![2];
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.stack(vec![n1,n2], shape).unwrap();
    /// ```
    pub fn stack(&self, nodes: Vec<Node>, outer_shape: ArrayShape) -> Result<Node> {
        self.add_node(nodes, vec![], Operation::Stack(outer_shape))
    }

    /// Adds a node creating a constant of a given type and value.
    ///
    /// # Arguments
    ///
    /// * `output_type` - type of a constant
    /// * `value` - value of a constant
    ///
    /// # Returns
    ///
    /// New constant node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let v = Value::from_scalar(0, BIT).unwrap();
    /// let n = g.constant(t, v).unwrap();
    /// ```
    pub fn constant(&self, output_type: Type, value: Value) -> Result<Node> {
        self.add_node(vec![], vec![], Operation::Constant(output_type, value))
    }

    /// Adds a node converting an integer array or scalar to the binary form.
    ///
    /// Given an array of shape `[a,b,c]` and scalar type `st`, this node returns an array of shape `[a,b,c,s]` where `s` is the bit size of `st`. For example, an array of shape `[1,2,3]` with `INT32` entries will be converted to a binary array of shape `[1,2,3,32]`.
    ///
    /// # Arguments
    ///
    /// `a` - node containing an array or scalar
    ///
    /// # Returns
    ///
    /// New node converting an array/scalar to the binary form
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.a2b(n1).unwrap();
    /// ```
    pub fn a2b(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::A2B)
    }

    /// Adds a node converting a binary array to an array of a given scalar type.
    ///
    /// Given a binary array of shape `[a,b,c]` and a scalar type `st` of bit size `c`, this node returns an array of shape `[a,b]` with `st` entries. For example, a binary array of shape `[2,3,32]` can be converted to an array of shape `[2,3]` with `INT32` entries.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing an array or scalar
    /// * `scalar_type` - scalar type
    ///
    /// # Returns
    ///
    /// New node converting an array from the binary form
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 32], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.b2a(n1, INT32).unwrap();
    /// ```
    pub fn b2a(&self, a: Node, scalar_type: ScalarType) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::B2A(scalar_type))
    }

    /// Adds a node that creates a tuple from several (possibly, zero) elements.
    ///
    /// # Arguments
    ///
    /// `elements` - vector of nodes
    ///
    /// # Returns
    ///
    /// New node with a tuple
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_tuple(vec![n1,n2]).unwrap();
    /// ```
    pub fn create_tuple(&self, elements: Vec<Node>) -> Result<Node> {
        self.add_node(elements, vec![], Operation::CreateTuple)
    }

    /// Adds a node that creates a vector from several (possibly, zero) elements of the same type.
    ///
    /// # Arguments
    ///
    /// `elements` - vector of nodes
    ///
    /// # Returns
    ///
    /// New node with a created vector
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// let n3 = g.create_vector(t, vec![n1,n2]).unwrap();
    /// ```
    pub fn create_vector(&self, element_type: Type, elements: Vec<Node>) -> Result<Node> {
        self.add_node(elements, vec![], Operation::CreateVector(element_type))
    }

    /// Adds a node that creates a named tuple from several (possibly, zero) elements.
    ///
    /// # Arguments
    ///
    /// `elements` - vector of pairs (node name, node)
    ///
    /// # Returns
    ///
    /// New node creating a named tuple
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_named_tuple(vec![("node1".to_owned(), n1), ("node2".to_owned(), n2)]).unwrap();
    /// ```
    pub fn create_named_tuple(&self, elements: Vec<(String, Node)>) -> Result<Node> {
        let mut nodes = vec![];
        let mut names = vec![];
        for (name, node) in elements {
            nodes.push(node);
            names.push(name);
        }
        self.add_node(nodes, vec![], Operation::CreateNamedTuple(names))
    }

    /// Adds a node that extracts an element of a tuple.
    ///
    /// # Arguments
    ///
    /// * `tuple` - node containing a tuple
    /// * `index` - index of a tuple element between 0 and tuple length minus 1
    ///
    /// # Returns
    ///
    /// New node with an extracted element
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_tuple(vec![n1, n2]).unwrap();
    /// let n4 = g.tuple_get(n3, 1).unwrap();
    /// ```
    pub fn tuple_get(&self, tuple: Node, index: u64) -> Result<Node> {
        self.add_node(vec![tuple], vec![], Operation::TupleGet(index))
    }

    /// Adds a node that extracts an element of a named tuple.
    ///
    /// # Arguments
    ///
    /// * `tuple` - node containing a named tuple
    /// * `key` - key of a tuple element
    ///
    /// # Returns
    ///
    /// New node extracting a tuple element
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_named_tuple(vec![("node1".to_owned(), n1), ("node2".to_owned(), n2)]).unwrap();
    /// let n4 = g.named_tuple_get(n3, "node2".to_owned()).unwrap();
    /// ```
    pub fn named_tuple_get(&self, tuple: Node, key: String) -> Result<Node> {
        self.add_node(vec![tuple], vec![], Operation::NamedTupleGet(key))
    }

    /// Adds a node that extracts an element of a vector.
    ///
    /// # Arguments
    ///
    /// * `vec` - node containing a vector
    /// * `index` - node containing the index of a tuple element
    ///
    /// # Returns
    ///
    /// New node extracting a vector element
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{UINT32, INT32, array_type, scalar_type};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// let n3 = g.create_vector(t, vec![n1,n2]).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n4 = g.vector_get(n3, index).unwrap();
    /// ```
    pub fn vector_get(&self, vec: Node, index: Node) -> Result<Node> {
        self.add_node(vec![vec, index], vec![], Operation::VectorGet)
    }

    /// Adds a node that takes vectors V<sub>1</sub>(n, t<sub>1</sub>), V<sub>2</sub>(n, t<sub>2</sub>), ..., V<sub>k</sub>(n, t<sub>k</sub>) of the same length and returns a vector V(n, tuple(t<sub>1</sub>, ..., t<sub>k</sub>)) (similar to [zip](https://doc.rust-lang.org/stable/std/iter/fn.zip.html)).
    ///
    /// # Arguments
    ///
    /// `nodes` - vector of nodes containing input vectors
    ///
    /// # Returns
    ///
    /// New zip node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type, vector_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let vec_t = vector_type(3, t);
    /// let n1 = g.input(vec_t.clone()).unwrap();
    /// let n2 = g.input(vec_t.clone()).unwrap();
    /// let n3 = g.zip(vec![n1,n2]).unwrap();
    /// ```
    pub fn zip(&self, nodes: Vec<Node>) -> Result<Node> {
        self.add_node(nodes, vec![], Operation::Zip)
    }

    /// Adds a node that creates a vector with `n` copies of a value of a given node.
    ///
    /// # Arguments
    ///
    /// * `a` - node containing a value
    /// * `n` - number of copies
    ///
    /// # Returns
    ///
    /// New repeat node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.repeat(n1, 10).unwrap();
    /// ```
    pub fn repeat(&self, a: Node, n: u64) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::Repeat(n))
    }

    /// Adds a node that calls another graph with inputs contained in given nodes.
    ///
    /// The input graph must be finalized and have as many inputs as the number of provided arguments.
    ///
    /// For example, let `G` be a graph implementing the function `max(x,0)`, then `call(G, [17]) = max(17, 0)`.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph with `n` input nodes
    /// * `arguments` - vector of `n` nodes
    ///
    /// # Returns
    ///
    /// New call node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    ///
    /// let g1 = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g1.input(t.clone()).unwrap();
    /// let n2 = g1.repeat(n1, 10).unwrap();
    /// let n3 = g1.vector_to_array(n2).unwrap();
    /// n3.set_as_output().unwrap();
    /// g1.finalize().unwrap();
    ///
    /// let g2 = c.create_graph().unwrap();
    /// let n4 = g2.input(t).unwrap();
    /// let n5 = g2.add(n4.clone(), n4).unwrap();
    /// let n6 = g2.call(g1, vec![n5]).unwrap();
    /// ```
    pub fn call(&self, graph: Graph, arguments: Vec<Node>) -> Result<Node> {
        self.add_node(arguments, vec![graph], Operation::Call)
    }

    /// Adds a node that iteratively computes a given finalized graph on the elements of a given vector and updates the state value accordingly.
    ///
    /// This node calls another `graph` with 2 input nodes `old_state` and `input` and an output node that returns a [tuple](Type::Tuple) `(new_state, output)`. This graph is used to map the elements of a given vector `V` to another vector `W` as follows:
    /// ```text
    /// graph(state_0, V[0]) -> (state1, W[0]),
    /// graph(state_1, V[1]) -> (state2, W[1]),
    /// ...
    /// graph(state_k, V[k]) -> (final_state, W[k]).
    /// ```
    /// The output is a [tuple](Type::Tuple) `(final_state, W)`. The initial state `state_0` should be provided as an argument.
    ///
    /// This node generalize `map` and `reduce` procedures (see [MapReduce](https://en.wikipedia.org/wiki/MapReduce) for more details).
    ///
    /// For example, let `G` be a graph implementing the function `max(x,0)` and incrementing `state` if its output is negative, then `iterate(G, 0, [-1,2,0,3,2]) = (1, [0,2,0,3,2])`. The final state is equal to the number of negative values in the input vector.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph with 2 input nodes of types T<sub>s</sub> and T<sub>i</sub> and returning a tuple of type (T<sub>s</sub>, T<sub>o</sub>)
    /// * `state` - node containing an initial state of type T<sub>s</sub>
    /// * `input` - node containing a vector with elements of type T<sub>i</sub>
    ///
    /// # Returns
    ///
    /// New iterate node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, scalar_type, vector_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    ///
    /// let t_s = scalar_type(INT32);
    /// let t = scalar_type(INT32);
    /// let vec_t = vector_type(10, t.clone());
    ///
    /// let g1 = c.create_graph().unwrap();
    /// {
    ///     let old_state = g1.input(t_s.clone()).unwrap();
    ///     let input = g1.input(t.clone()).unwrap();
    ///     let sum = g1.add(old_state.clone(), input).unwrap();
    ///     let out_tuple = g1.create_tuple(vec![sum, old_state]).unwrap();
    ///     out_tuple.set_as_output().unwrap();
    ///     g1.finalize().unwrap();
    /// }
    ///
    /// let g2 = c.create_graph().unwrap();
    /// let initial_state = g2.input(t).unwrap();
    /// let input_vector = g2.input(vec_t).unwrap();
    /// g2.iterate(g1, initial_state, input_vector).unwrap();
    /// ```
    pub fn iterate(&self, graph: Graph, state: Node, input: Node) -> Result<Node> {
        self.add_node(vec![state, input], vec![graph], Operation::Iterate)
    }

    /// Adds a node converting an array to a vector.
    ///
    /// Given an array of shape `[a,b,c]`, this node returns a vector of `a` arrays of shape `[b,c]`.
    ///
    /// # Arguments
    ///
    /// `a` - node containing an array
    ///
    /// # Returns
    ///
    /// New node converting an array to a vector
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, scalar_type, INT32, UINT32};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![4, 3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.array_to_vector(n1).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n3 = g.vector_get(n2.clone(), index).unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_vector());
    /// assert_eq!(n3.get_type().unwrap().get_shape(), vec![3,2]);
    /// ```    
    pub fn array_to_vector(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::ArrayToVector)
    }

    /// Adds a node converting a vector to an array.
    ///
    /// Given a vector of `a` arrays of shape `[b,c]`, this node returns an array of shape `[a,b,c]`.
    ///
    /// # Arguments
    ///
    /// `a` - node containing a vector
    ///
    /// # Returns
    ///
    /// New node converting a vector to an array
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_array());
    /// assert_eq!(n2.get_type().unwrap().get_shape(), vec![4, 3, 2]);
    /// ```
    pub fn vector_to_array(&self, a: Node) -> Result<Node> {
        self.add_node(vec![a], vec![], Operation::VectorToArray)
    }

    /// Adds a node computing a given custom operation.
    ///
    /// Custom operations can be created by the user as public structs implementing the [CustomOperationBody](../custom_ops/trait.CustomOperationBody.html).
    ///
    /// # Arguments
    ///
    /// * `op` - custom operation
    /// * `arguments` - vector of nodes used as input for the custom operation
    ///
    /// # Returns
    ///
    /// New custom operation node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, BIT};
    /// # use ciphercore_base::custom_ops::{CustomOperation, Not};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.custom_op(CustomOperation::new(Not {}), vec![n1]).unwrap();
    /// ```
    pub fn custom_op(&self, op: CustomOperation, arguments: Vec<Node>) -> Result<Node> {
        self.add_node(arguments, vec![], Operation::Custom(op))
    }

    /// Checks that the graph has an output node and finalizes the graph.
    ///
    /// After finalization the graph can't be changed.
    ///
    /// # Returns
    ///
    /// Finalized graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// n2.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// ```
    pub fn finalize(&self) -> Result<Graph> {
        let output_node = self.body.borrow_mut().output_node.clone();
        match output_node {
            Some(_) => {
                self.body.borrow_mut().finalized = true;
                Ok(self.clone())
            }
            None => Err(runtime_error!("Output node is not set")),
        }
    }

    pub(super) fn is_finalized(&self) -> bool {
        self.body.borrow().finalized
    }

    pub(super) fn check_finalized(&self) -> Result<()> {
        if !self.is_finalized() {
            return Err(runtime_error!("Graph is not finalized"));
        }
        Ok(())
    }

    /// Returns the vector of nodes contained in the graph in order of construction.
    ///
    /// # Returns
    ///
    /// Vector of nodes of the graph
    pub fn get_nodes(&self) -> Vec<Node> {
        self.body.borrow().nodes.clone()
    }

    /// Promotes a given node to the output node of the parent graph.
    ///
    /// # Arguments
    ///
    /// `output_node` - node to be set as output
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// g.set_output_node(n2).unwrap();
    /// g.finalize().unwrap();
    /// ```
    pub fn set_output_node(&self, output_node: Node) -> Result<()> {
        let current_output_node = self.body.borrow().output_node.clone();
        match current_output_node {
            Some(_) => Err(runtime_error!("Output node is already set")),
            None => {
                if output_node.get_graph() != *self {
                    Err(runtime_error!("Output node has to be from the same graph"))
                } else {
                    self.body.borrow_mut().output_node = Some(output_node.downgrade());
                    Ok(())
                }
            }
        }
    }

    /// Returns the output node of the graph.
    ///
    /// # Returns
    ///
    /// Output node of the graph
    pub fn get_output_node(&self) -> Result<Node> {
        let current_output_node = self.body.borrow().output_node.clone();
        match current_output_node {
            Some(output_node) => Ok(output_node.upgrade()),
            None => Err(runtime_error!("Output node is not set")),
        }
    }

    /// Returns the ID of the graph.
    ///
    /// A graph ID is a serial number of a graph between `0` and `n-1` where `n` is the number of graphs in the parent context.
    ///
    /// # Returns
    ///
    /// Graph ID
    pub fn get_id(&self) -> u64 {
        self.body.borrow().id
    }

    /// Returns the number of the graph nodes.
    ///
    /// # Returns
    ///
    /// Number of the graph nodes
    pub fn get_num_nodes(&self) -> u64 {
        self.body.borrow().nodes.len() as u64
    }

    /// Returns the node corresponding to a given ID.
    ///
    /// # Arguments
    ///
    /// `id` - node ID
    ///
    /// # Returns
    ///
    /// Node with a given ID
    pub fn get_node_by_id(&self, id: u64) -> Result<Node> {
        let nodes = &self.body.borrow().nodes;
        if id >= nodes.len() as u64 {
            Err(runtime_error!("Invalid id for the node retrieval"))
        } else {
            Ok(nodes[id as usize].clone())
        }
    }

    /// Returns the context of the graph nodes.
    ///
    /// # Returns
    ///
    /// Context of the graph
    pub fn get_context(&self) -> Context {
        self.body.borrow().context.upgrade()
    }

    fn make_serializable(&self) -> SerializableGraph {
        let output_node = match self.get_output_node() {
            Ok(n) => Some(n.get_id()),
            Err(_) => None,
        };
        Arc::new(SerializableGraphBody {
            finalized: self.is_finalized(),
            nodes: self
                .get_nodes()
                .iter()
                .map(|n| n.make_serializable())
                .collect(),
            output_node,
        })
    }
}

impl Graph {
    fn downgrade(&self) -> WeakGraph {
        WeakGraph {
            body: Arc::downgrade(&self.body),
        }
    }
}
type WeakGraphBodyPointer = Weak<AtomicRefCell<GraphBody>>;

struct WeakGraph {
    body: WeakGraphBodyPointer,
}

impl WeakGraph {
    //upgrade function panics if the the Graph pointer it downgraded from went out of scope
    fn upgrade(&self) -> Graph {
        Graph {
            body: self.body.upgrade().unwrap(),
        }
    }
}
impl Clone for WeakGraph {
    fn clone(&self) -> Self {
        WeakGraph {
            body: self.body.clone(),
        }
    }
}

#[doc(hidden)]
/// Various node-related properties which aren't used in the graph building
/// or type inference, but can be used in node expansion or MPC compilation.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum NodeAnnotation {
    AssociativeOperation,
    Private,
    Send(u64, u64), // (sender_index, receiver_index); indices belong to the set 0..PARTIES
    PRFMultiplication,
    PRFB2A,
}

#[doc(hidden)]
/// Various graph-related properties which aren't used in the graph building
/// or type inference, but can be used in node expansion or MPC compilation.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum GraphAnnotation {
    AssociativeOperation,
    OneBitState,
    SmallState,
}

struct ContextBody {
    finalized: bool,
    graphs: Vec<Graph>,
    main_graph: Option<WeakGraph>,
    /// graph_id -> name
    graphs_names: HashMap<u64, String>,
    /// name -> graph_id
    graphs_names_inverse: HashMap<String, u64>,
    /// (graph_id, node_id) -> name
    nodes_names: HashMap<(u64, u64), String>,
    /// graph_id -> (name -> node_id)
    nodes_names_inverse: HashMap<u64, HashMap<String, u64>>,
    /// (graph_id, node_id) -> NodeAnnotation's
    nodes_annotations: HashMap<(u64, u64), Vec<NodeAnnotation>>,
    /// (graph_id) -> GraphAnnotation's
    graphs_annotations: HashMap<u64, Vec<GraphAnnotation>>,
    total_size_nodes: u64,
    type_checker: Option<TypeInferenceWorker>,
}

type ContextBodyPointer = Arc<AtomicRefCell<ContextBody>>;

/// A structure that stores a pointer to a computation context that contains related computation graphs.
///
/// Context is a basic object to create computation graphs, arrange data flow between them and keep necessary information about them that is used for optimization, secure compilation and evaluation.
///
/// Context should have a main graph and be finalized in order to evaluate any of its graphs.
///
/// [Clone] trait duplicates the pointer, not the underlying context.
///
/// [PartialEq] trait compares pointers, not the related contexts.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate maplit;
/// # fn main() {
/// # use ciphercore_base::graphs::{Context, create_context};
/// # use ciphercore_base::data_values::Value;
/// # use ciphercore_base::evaluators::random_evaluate;
/// # use ciphercore_base::data_types::{INT32, scalar_type};
/// # use ciphercore_base::errors::Result;
/// let context = || -> Result<Context> {
///     let context = create_context()?;
///     let graph = context.create_graph()?.set_name("main")?;
///     graph
///         .input(scalar_type(INT32))?
///         .set_name("a")?
///         .add(graph
///             .input(scalar_type(INT32))?
///             .set_name("b")?)?
///         .set_as_output()?;
///     graph.finalize()?.set_as_main()?;
///     context.finalize()?;
///     Ok(context)
/// }().unwrap();
///
/// let result = || -> Result<i32> {
///     let g = context.retrieve_graph("main")?;
///     let result = random_evaluate(
///         g.clone(),
///         g.prepare_input_values(
///             hashmap!{
///                 "a" => Value::from_scalar(123, INT32)?,
///                 "b" => Value::from_scalar(654, INT32)?,
///             },
///         )?,
///     )?;
///     let result = result.to_i32(INT32)?;
///     Ok(result)
/// }().unwrap();
///
/// assert_eq!(result, 777);
/// # }
/// ```
pub struct Context {
    body: ContextBodyPointer,
}

impl fmt::Debug for Context {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Context")
            .field("body", &self.body.as_ptr())
            .finish()
    }
}

#[derive(Serialize, Deserialize)]
struct SerializableContextBody {
    finalized: bool,
    graphs: Vec<SerializableGraph>,
    main_graph: Option<u64>,
    /// graph_id -> name
    graphs_names: Vec<(u64, String)>,
    /// (graph_id, node_id) -> name
    nodes_names: Vec<((u64, u64), String)>,
    /// (graph_id, node_id) -> NodeAnnotation's
    nodes_annotations: Vec<((u64, u64), Vec<NodeAnnotation>)>,
    /// (graph_id) -> GraphAnnotation's
    graphs_annotations: Vec<(u64, Vec<GraphAnnotation>)>,
}

impl SerializableContextBody {
    fn recover_original_graph(
        serializable_graph: SerializableGraph,
        context: Context,
    ) -> Result<Graph> {
        let result_graph = context.create_graph()?;
        for node in &serializable_graph.nodes {
            let mut node_dependencies = vec![];
            for id in &node.node_dependencies {
                let current_nodes = &result_graph.body.borrow().nodes;
                if *id >= current_nodes.len() as u64 {
                    return Err(runtime_error!("Non-existent node dependency"));
                }
                node_dependencies.push(current_nodes[*id as usize].clone());
            }
            let mut graph_dependencies = vec![];
            for id in &node.graph_dependencies {
                let context = result_graph.get_context();
                let current_graphs = &context.body.borrow().graphs;
                if *id >= current_graphs.len() as u64 {
                    return Err(runtime_error!("Non-existent graph dependency"));
                }
                graph_dependencies.push(current_graphs[*id as usize].clone());
            }
            result_graph.add_node(
                node_dependencies,
                graph_dependencies,
                node.operation.clone(),
            )?;
        }
        if let Some(id) = serializable_graph.output_node {
            let rebuilt_output_node = {
                let current_nodes = &result_graph.body.borrow().nodes;
                if id >= current_nodes.len() as u64 {
                    return Err(runtime_error!("Non-existent output node"));
                }
                current_nodes[id as usize].clone()
            };
            result_graph.set_output_node(rebuilt_output_node)?;
        }
        if serializable_graph.finalized {
            result_graph.finalize()?;
        }
        Ok(result_graph)
    }

    fn recover_original_context(&self) -> Result<Context> {
        let result_context = create_context()?;
        for graph in &self.graphs {
            let _result_graph =
                Self::recover_original_graph(graph.clone(), result_context.clone())?;
        }
        if let Some(id) = self.main_graph {
            let rebuilt_main_graph = {
                let current_graphs = &result_context.body.borrow().graphs;
                if id >= current_graphs.len() as u64 {
                    return Err(runtime_error!("Non-existent main graph"));
                }
                current_graphs[id as usize].clone()
            };
            result_context.set_main_graph(rebuilt_main_graph)?;
        }
        for (id, _) in &self.graphs_names {
            let current_graphs = &result_context.body.borrow().graphs;
            if *id >= current_graphs.len() as u64 {
                return Err(runtime_error!("graphs_names contain an invalid ID"));
            }
        }
        for ((graph_id, node_id), _) in &self.nodes_names {
            let current_graphs = &result_context.body.borrow().graphs;
            if *graph_id >= current_graphs.len() as u64 {
                return Err(runtime_error!("nodes_names contain an invalid graph ID"));
            }
            let current_nodes = &current_graphs[*graph_id as usize].body.borrow().nodes;
            if *node_id >= current_nodes.len() as u64 {
                return Err(runtime_error!("nodes_names contain an invalid node ID"));
            }
        }
        for (id, name) in &self.graphs_names {
            let current_graph = {
                let current_graphs = &result_context.body.borrow().graphs;
                current_graphs[*id as usize].clone()
            };
            result_context.set_graph_name(current_graph, name)?;
        }
        for ((graph_id, node_id), name) in &self.nodes_names {
            let current_node = {
                let current_graphs = &result_context.body.borrow().graphs;
                let current_nodes = &current_graphs[*graph_id as usize].body.borrow().nodes;
                current_nodes[*node_id as usize].clone()
            };
            result_context.set_node_name(current_node, name)?;
        }
        for (id, annotations) in &self.graphs_annotations {
            let current_graph = {
                let current_graphs = &result_context.body.borrow().graphs;
                current_graphs[*id as usize].clone()
            };
            for annotation in annotations {
                result_context.add_graph_annotation(&current_graph, annotation.clone())?;
            }
        }
        for ((graph_id, node_id), annotations) in &self.nodes_annotations {
            let current_node = {
                let current_graphs = &result_context.body.borrow().graphs;
                let current_nodes = &current_graphs[*graph_id as usize].body.borrow().nodes;
                current_nodes[*node_id as usize].clone()
            };
            for annotation in annotations {
                result_context.add_node_annotation(&current_node, annotation.clone())?;
            }
        }
        if self.finalized {
            result_context.finalize()?;
        }
        Ok(result_context)
    }
}

type SerializableContext = Arc<SerializableContextBody>;

impl Clone for Context {
    /// Returns a new [Context] value with a copy of the pointer to a node.
    fn clone(&self) -> Self {
        Context {
            body: self.body.clone(),
        }
    }
}

impl PartialEq for Context {
    /// Tests whether `self` and `other` contexts are equal via comparison of their respective pointers.
    ///
    /// # Arguments
    ///
    /// `other` - another [Context] value
    ///
    /// # Returns
    ///
    /// `true` if `self` and `other` are equal, `false` otherwise
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.body, &other.body)
    }
}

impl Eq for Context {}

impl Context {
    /// Creates an empty computation graph in this context.
    ///
    /// # Returns
    ///
    /// New computation graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// ```
    pub fn create_graph(&self) -> Result<Graph> {
        if self.body.borrow().finalized {
            return Err(runtime_error!("Can't add a graph to a finalized context"));
        }
        let id = self.body.borrow().graphs.len() as u64;
        let result = Graph {
            body: Arc::new(AtomicRefCell::new(GraphBody {
                finalized: false,
                nodes: vec![],
                output_node: None,
                id,
                context: self.downgrade(),
            })),
        };
        self.body.borrow_mut().graphs.push(result.clone());
        Ok(result)
    }

    /// Finalizes the context if all its graphs are finalized and the main graph is set.
    ///
    /// After finalization the context can't be changed.
    ///
    /// # Returns
    ///
    /// Finalized context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// n2.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// c.set_main_graph(g).unwrap();
    /// c.finalize().unwrap();
    /// ```
    pub fn finalize(&self) -> Result<Context> {
        for graph in self.get_graphs() {
            graph.check_finalized()?;
        }
        let main_graph = self.body.borrow().main_graph.clone();
        match main_graph {
            Some(_) => {
                self.body.borrow_mut().finalized = true;
                Ok(self.clone())
            }
            _ => Err(runtime_error!(
                "Can't finalize the context without the main graph"
            )),
        }
    }

    /// Promotes a graph to the main one in this context.
    ///
    /// # Arguments
    ///
    /// `graph` - graph
    ///
    /// # Returns
    ///
    /// This context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n = g.input(t).unwrap();
    /// n.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// c.set_main_graph(g).unwrap();
    /// ```
    pub fn set_main_graph(&self, graph: Graph) -> Result<Context> {
        let current_main_graph = self.body.borrow().main_graph.clone();
        match current_main_graph {
            Some(_) => Err(runtime_error!("Main graph is already set")),
            None => {
                if graph.get_context() != *self {
                    return Err(runtime_error!("Main graph is from the wrong context"));
                }
                graph.check_finalized()?;
                self.body.borrow_mut().main_graph = Some(graph.downgrade());
                Ok(self.clone())
            }
        }
    }

    /// Returns the vector of graphs contained in this context in order of creation.
    ///
    /// # Returns
    ///
    /// Vector of the graphs in this context
    pub fn get_graphs(&self) -> Vec<Graph> {
        self.body.borrow().graphs.clone()
    }

    pub(super) fn is_finalized(&self) -> bool {
        self.body.borrow().finalized
    }

    /// Does nothing if the context is finalized; otherwise returns a runtime error.
    ///
    /// # Returns
    ///
    /// Runtime error if this context is not finalized
    pub fn check_finalized(&self) -> Result<()> {
        if !self.is_finalized() {
            return Err(runtime_error!("Context is not finalized"));
        }
        Ok(())
    }

    /// Returns the main graph of the context if it is already set.
    ///
    /// # Returns
    ///
    /// Main graph of the context
    pub fn get_main_graph(&self) -> Result<Graph> {
        match &self.body.borrow().main_graph {
            Some(g) => Ok(g.upgrade()),
            None => Err(runtime_error!("main graph is not set")),
        }
    }

    /// Returns the number of graphs contained in this context.
    ///
    /// # Returns
    ///
    /// Number of the graphs in this context
    pub fn get_num_graphs(&self) -> u64 {
        self.body.borrow().graphs.len() as u64
    }

    /// Returns the graph contained in this context with a given ID.
    ///
    /// A graph ID is a serial number of a graph between `0` and `n-1` where `n` is the number of graphs in this context.
    ///
    /// # Arguments
    ///
    /// `id` - ID of a graph
    ///
    /// # Returns
    ///
    /// Graph with the given ID
    pub fn get_graph_by_id(&self, id: u64) -> Result<Graph> {
        let graphs = &self.body.borrow().graphs;
        if id >= graphs.len() as u64 {
            Err(runtime_error!("Invalid id for the graph retrieval"))
        } else {
            Ok(graphs[id as usize].clone())
        }
    }

    /// Returns the node contained in this context with a given global ID.
    ///
    /// The global ID of a node is a pair of the node ID and the ID of its parent graph.
    ///
    /// # Arguments
    ///
    /// `id` - tuple (graph ID, node ID)
    ///
    /// # Returns
    ///
    /// Node with the given global ID
    pub fn get_node_by_global_id(&self, id: (u64, u64)) -> Result<Node> {
        self.get_graph_by_id(id.0)?.get_node_by_id(id.1)
    }

    fn make_serializable(&self) -> SerializableContext {
        let main_graph = match self.get_main_graph() {
            Ok(g) => Some(g.get_id()),
            Err(_) => None,
        };
        let cell = self.body.borrow();
        Arc::new(SerializableContextBody {
            finalized: self.is_finalized(),
            graphs: self
                .get_graphs()
                .iter()
                .map(|g| g.make_serializable())
                .collect(),
            main_graph,
            graphs_names: cell.graphs_names.clone().into_iter().collect(),
            nodes_names: cell.nodes_names.clone().into_iter().collect(),
            graphs_annotations: cell.graphs_annotations.clone().into_iter().collect(),
            nodes_annotations: cell.nodes_annotations.clone().into_iter().collect(),
        })
    }

    fn add_type_checker(&self) -> Result<Context> {
        {
            let mut cell = self.body.borrow_mut();
            if cell.type_checker.is_some() {
                return Err(runtime_error!(
                    "Type checker associated with the context already exists"
                ));
            }
            cell.type_checker = Some(create_type_inference_worker(self.clone()));
        }
        for graph in self.get_graphs() {
            for node in graph.get_nodes() {
                node.get_type()?;
            }
        }
        Ok(self.clone())
    }

    fn get_total_size_nodes(&self) -> u64 {
        self.body.borrow().total_size_nodes
    }

    fn set_total_size_nodes(&self, size: u64) {
        self.body.borrow_mut().total_size_nodes = size;
    }

    fn try_update_total_size(&self, node: Node) -> Result<()> {
        let node_type: Type;
        match node.get_operation() {
            Operation::Input(input_type) => {
                node_type = input_type;
            }
            Operation::Constant(t, _) => {
                node_type = t;
            }
            _ => return Ok(()),
        }
        if !node_type.is_valid() {
            return Err(runtime_error!("Node with an invalid type: {:?}", node_type));
        }
        let new_total_size = self
            .get_total_size_nodes()
            .checked_add(get_size_estimation_in_bits(node_type)?)
            .ok_or_else(|| runtime_error!("add overflow!"))?;
        if new_total_size > constants::MAX_TOTAL_SIZE_NODES {
            return Err(runtime_error!(
                "Can't add a node: total size of nodes exceeds MAX_TOTAL_SIZE_NODES"
            ));
        }
        self.set_total_size_nodes(new_total_size);
        Ok(())
    }

    fn unregister_node(&self, node: Node) -> Result<()> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!(
                "The node to be unregister from  a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't unregister a node from  a finalized context"
            ));
        }

        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();

        let mut cell = self.body.borrow_mut();
        let name_option = cell.nodes_names.remove(&(graph_id, node_id));
        cell.nodes_annotations.remove(&(graph_id, node_id));
        if cell.nodes_names_inverse.get(&graph_id).is_none() {
            return Ok(());
        }
        let graph_map_inverse = cell
            .nodes_names_inverse
            .get_mut(&graph_id)
            .expect("Should not be here!");
        if let Some(name) = name_option {
            graph_map_inverse.remove(&name);
        }
        Ok(())
    }

    fn to_versioned_data(&self) -> Result<VersionedData> {
        VersionedData::create_versioned_data(
            DATA_VERSION,
            serde_json::to_string(&self.make_serializable())?,
        )
    }
}

impl Serialize for Context {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let versioned_context = self
            .to_versioned_data()
            .expect("Error during conversion from Context into VersionedData");
        //VersionedData::from(self.clone());
        versioned_context.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Context {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Context, D::Error>
    where
        D: Deserializer<'de>,
    {
        let versioned_context = VersionedData::deserialize(deserializer)?;
        if !versioned_context.check_version(DATA_VERSION) {
            Err(runtime_error!(
                "Context version doesn't match the requirement"
            ))
            .map_err(serde::de::Error::custom)
        } else {
            let serializable_context =
                serde_json::from_str::<SerializableContext>(versioned_context.get_data_string())
                    .expect("Error during deserialization of SerializableContext");
            serializable_context
                .recover_original_context()
                .map_err(serde::de::Error::custom)
        }
    }
}

/// In general, `create_unchecked_context()` should not return errors, but
/// we still make the result type Result<Context> for uniformity.
pub(super) fn create_unchecked_context() -> Result<Context> {
    Ok(Context {
        body: Arc::new(AtomicRefCell::new(ContextBody {
            finalized: false,
            graphs: vec![],
            main_graph: None,
            graphs_names: HashMap::new(),
            graphs_names_inverse: HashMap::new(),
            nodes_names: HashMap::new(),
            nodes_names_inverse: HashMap::new(),
            graphs_annotations: HashMap::new(),
            nodes_annotations: HashMap::new(),
            type_checker: None,
            total_size_nodes: 0,
        })),
    })
}

/// Creates an empty computation context.
///
/// # Returns
///
/// New computation context
///
/// # Example
///
/// ```
/// # use ciphercore_base::graphs::create_context;
/// let c = create_context().unwrap();
/// ```
pub fn create_context() -> Result<Context> {
    let context = create_unchecked_context()?;
    context.add_type_checker()?;
    Ok(context)
}

fn graphs_deep_equal(graph1: Graph, graph2: Graph) -> bool {
    let graph1_body = graph1.body.borrow();
    let graph2_body = graph2.body.borrow();
    if graph1_body.finalized != graph2_body.finalized {
        return false;
    }
    if graph1_body.nodes.len() != graph2_body.nodes.len() {
        return false;
    }
    for j in 0..graph1_body.nodes.len() {
        let node1 = graph1_body.nodes[j].clone();
        let node2 = graph2_body.nodes[j].clone();
        let node1_body = node1.body.borrow();
        let node2_body = node2.body.borrow();
        if node1_body.operation != node2_body.operation {
            return false;
        }
        let node_dependencies1: Vec<u64> = node1_body
            .node_dependencies
            .iter()
            .map(|n| n.upgrade().get_id())
            .collect();
        let node_dependencies2: Vec<u64> = node2_body
            .node_dependencies
            .iter()
            .map(|n| n.upgrade().get_id())
            .collect();
        if node_dependencies1 != node_dependencies2 {
            return false;
        }
        let graph_dependencies1: Vec<u64> = node1_body
            .graph_dependencies
            .iter()
            .map(|g| g.upgrade().get_id())
            .collect();
        let graph_dependencies2: Vec<u64> = node2_body
            .graph_dependencies
            .iter()
            .map(|g| g.upgrade().get_id())
            .collect();
        if graph_dependencies1 != graph_dependencies2 {
            return false;
        }
    }
    if graph1_body
        .output_node
        .clone()
        .map(|n| n.upgrade().get_id())
        != graph2_body
            .output_node
            .clone()
            .map(|n| n.upgrade().get_id())
    {
        return false;
    }
    true
}

/// Check that two given contexts contain the same data, i.e. graphs, nodes, names, parameters.
///
/// Underlying structures that contain pointers (graphs, nodes) are compared by data they refer to.
///
/// # Arguments
///
/// * `context1` - first context to compare
/// * `context2` - second context to compare
///
/// # Returns
///
/// `true` if the given contexts contain the same content, otherwise `false`
pub fn contexts_deep_equal(context1: Context, context2: Context) -> bool {
    let body1 = context1.body.borrow();
    let body2 = context2.body.borrow();
    if body1.finalized != body2.finalized {
        return false;
    }
    if body1.graphs_names != body2.graphs_names {
        return false;
    }
    if body1.nodes_names != body2.nodes_names {
        return false;
    }
    if body1.nodes_annotations != body2.nodes_annotations {
        return false;
    }
    if body1.graphs_annotations != body2.graphs_annotations {
        return false;
    }
    if body1.graphs.len() != body2.graphs.len() {
        return false;
    }
    for i in 0..body1.graphs.len() {
        if !graphs_deep_equal(body1.graphs[i].clone(), body2.graphs[i].clone()) {
            return false;
        }
    }
    body1.main_graph.clone().map(|g| g.upgrade().get_id())
        == body2.main_graph.clone().map(|g| g.upgrade().get_id())
}

impl Context {
    /// Sets the name of a graph.
    ///
    /// A given name should be unique.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph
    /// * `name` - name of the graph
    ///
    /// # Returns
    ///
    /// This context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// ```
    pub fn set_graph_name(&self, graph: Graph, name: &str) -> Result<Context> {
        if graph.get_context() != *self {
            return Err(runtime_error!(
                "The graph to be named is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't set a graph name in a finalized context"
            ));
        }
        let id = graph.get_id();
        let name_owned = name.to_owned();
        let mut cell = self.body.borrow_mut();
        if cell.graphs_names.get(&id).is_some() {
            return Err(runtime_error!("Can't set the graph name twice"));
        }
        if cell.graphs_names_inverse.get(name).is_some() {
            return Err(runtime_error!("Graph names must be unique"));
        }
        cell.graphs_names.insert(id, name_owned.clone());
        cell.graphs_names_inverse.insert(name_owned, id);
        Ok(self.clone())
    }

    /// Returns the name of a graph.
    ///
    /// # Arguments
    ///
    /// `graph` - graph
    ///
    /// # Returns
    ///
    /// Name of a given graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// assert_eq!(c.get_graph_name(g).unwrap(), "relu".to_owned());
    /// ```
    pub fn get_graph_name(&self, graph: Graph) -> Result<String> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let cell = self.body.borrow();
        Ok(cell
            .graphs_names
            .get(&graph.get_id())
            .ok_or_else(|| runtime_error!("The graph does not have a name assigned"))?
            .clone())
    }

    /// Returns the graph with a given name in this context.
    ///
    /// # Arguments
    ///
    /// `name` - graph name
    ///
    /// # Returns
    ///
    /// Graph with a given name
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let n = g.input(scalar_type(BIT)).unwrap();
    /// g.set_name("input_graph").unwrap();
    /// assert!(g == c.retrieve_graph("input_graph").unwrap());
    /// ```
    pub fn retrieve_graph(&self, name: &str) -> Result<Graph> {
        let cell = self.body.borrow();
        let id = cell
            .graphs_names_inverse
            .get(name)
            .ok_or_else(|| runtime_error!("No graph with such a name exists"))?;
        let graph = cell.graphs[*id as usize].clone();
        Ok(graph)
    }

    /// Sets the name of a node.
    ///
    /// A given name should be unique.
    ///
    /// # Arguments
    ///
    /// * `node` - node
    /// * `name` - name of a node
    ///
    /// # Returns
    ///
    /// This context
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// c.set_node_name(n, "XOR").unwrap();
    /// ```
    pub fn set_node_name(&self, node: Node, name: &str) -> Result<Context> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!(
                "The node to be named is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't set a node name in a finalized context"
            ));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let mut cell = self.body.borrow_mut();
        if cell.nodes_names.get(&(graph_id, node_id)).is_some() {
            return Err(runtime_error!("Can't set the node name twice"));
        }
        if cell.nodes_names_inverse.get(&graph_id).is_none() {
            cell.nodes_names_inverse.insert(graph_id, HashMap::new());
        }
        let graph_map_inverse = cell
            .nodes_names_inverse
            .get_mut(&graph_id)
            .expect("Should not be here!");
        if graph_map_inverse.get(name).is_some() {
            return Err(runtime_error!(
                "Node names must be unique (within the graph)"
            ));
        }
        graph_map_inverse.insert(name.to_owned(), node_id);
        cell.nodes_names
            .insert((graph_id, node_id), name.to_owned());
        Ok(self.clone())
    }

    /// Returns the name of a node.
    ///
    /// # Arguments
    ///
    /// `node` - node
    ///
    /// # Returns
    ///
    /// Name of a node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// n.set_name("XOR").unwrap();
    /// assert_eq!(c.get_node_name(n).unwrap(), "XOR".to_owned());
    /// ```
    pub fn get_node_name(&self, node: Node) -> Result<String> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!("The node is in a different context"));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let cell = self.body.borrow_mut();
        Ok(cell
            .nodes_names
            .get(&(graph_id, node_id))
            .ok_or_else(|| runtime_error!("The node is not named"))?
            .clone())
    }

    /// Returns the node with a given name in a given graph.
    ///
    /// # Arguments
    ///
    /// * `graph` - graph
    /// * `name` - node name
    ///
    /// # Returns
    ///
    /// Node with a given name
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let n = g.input(scalar_type(BIT)).unwrap();
    /// n.set_name("input_node").unwrap();
    /// assert!(n == c.retrieve_node(g, "input_node").unwrap());
    /// ```
    pub fn retrieve_node(&self, graph: Graph, name: &str) -> Result<Node> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let graph_id = graph.get_id();
        let cell = self.body.borrow();
        let node_id = cell
            .nodes_names_inverse
            .get(&graph_id)
            .ok_or_else(|| runtime_error!("The graph has no named nodes"))?
            .get(name)
            .ok_or_else(|| runtime_error!("Node with a given name does not exist"))?;
        Ok(graph.body.borrow().nodes[*node_id as usize].clone())
    }

    fn prepare_input_values<T: Clone>(
        &self,
        graph: Graph,
        values: HashMap<&str, T>,
    ) -> Result<Vec<T>> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let graph_id = graph.get_id();
        let cell = self.body.borrow();
        for node_name in values.keys() {
            cell.nodes_names_inverse
                .get(&graph_id)
                .ok_or_else(|| runtime_error!("Trying to call graph without named nodes"))?
                .get(node_name as &str)
                .ok_or_else(|| runtime_error!("Input with a given name is not found"))?;
        }
        let mut result = vec![];
        for node in graph.get_nodes() {
            if let Operation::Input(_) = node.get_operation() {
                let node_id = node.get_id();
                let node_name = cell
                    .nodes_names
                    .get(&(graph_id, node_id))
                    .ok_or_else(|| runtime_error!("Unnamed input"))?;
                let node_value = values
                    .get(node_name as &str)
                    .ok_or_else(|| runtime_error!("Unspecified input"))?
                    .clone();
                result.push(node_value);
            }
        }
        Ok(result)
    }

    pub(super) fn add_node_annotation(
        &self,
        node: &Node,
        annotation: NodeAnnotation,
    ) -> Result<Context> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!(
                "The node to be annotated is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't add a node annotation in a finalized context"
            ));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let key = (graph_id, node_id);
        let mut cell = self.body.borrow_mut();
        let annotations = cell.nodes_annotations.get_mut(&key);
        if let Some(annotation_vec) = annotations {
            annotation_vec.push(annotation);
        } else {
            cell.nodes_annotations.insert(key, vec![annotation]);
        }
        Ok(self.clone())
    }

    pub(super) fn get_node_annotations(&self, node: Node) -> Result<Vec<NodeAnnotation>> {
        if node.get_graph().get_context() != *self {
            return Err(runtime_error!("The node is in a different context"));
        }
        let node_id = node.get_id();
        let graph_id = node.get_graph().get_id();
        let cell = self.body.borrow_mut();
        Ok(cell
            .nodes_annotations
            .get(&(graph_id, node_id))
            .cloned()
            .unwrap_or_else(Vec::new))
    }

    fn add_graph_annotation(&self, graph: &Graph, annotation: GraphAnnotation) -> Result<Context> {
        if graph.get_context() != *self {
            return Err(runtime_error!(
                "The graph to be annotated is in a different context"
            ));
        }
        if self.is_finalized() {
            return Err(runtime_error!(
                "Can't set a graph annotation in a finalized context"
            ));
        }
        let id = graph.get_id();
        let mut cell = self.body.borrow_mut();
        let annotations = cell.graphs_annotations.get_mut(&id);
        if let Some(annotation_vec) = annotations {
            annotation_vec.push(annotation);
        } else {
            cell.graphs_annotations.insert(id, vec![annotation]);
        }
        Ok(self.clone())
    }

    fn get_graph_annotations(&self, graph: Graph) -> Result<Vec<GraphAnnotation>> {
        if graph.get_context() != *self {
            return Err(runtime_error!("The graph is in a different context"));
        }
        let cell = self.body.borrow();
        Ok(cell
            .graphs_annotations
            .get(&graph.get_id())
            .cloned()
            .unwrap_or_else(Vec::new))
    }
}

impl Graph {
    /// Applies [Context::set_main_graph] to the parent context and `this` graph. Returns the clone of `this`.
    ///
    /// # Returns
    ///
    /// This graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n = g.input(t).unwrap();
    /// n.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// g.set_as_main().unwrap();
    /// ```
    pub fn set_as_main(&self) -> Result<Graph> {
        self.get_context().set_main_graph(self.clone())?;
        Ok(self.clone())
    }

    /// Applies [Context::set_graph_name] to the parent context and `this` graph. Returns the clone of `this`.
    ///
    /// # Arguments
    ///
    /// `name` - name of the graph
    ///
    /// # Returns
    ///
    /// This graph
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// ```
    pub fn set_name(&self, name: &str) -> Result<Graph> {
        self.get_context().set_graph_name(self.clone(), name)?;
        Ok(self.clone())
    }

    /// Applies [Context::get_graph_name] to the parent context and `this` graph.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// g.set_name("relu").unwrap();
    /// assert_eq!(g.get_name().unwrap(), "relu".to_owned());
    /// ```
    pub fn get_name(&self) -> Result<String> {
        self.get_context().get_graph_name(self.clone())
    }

    #[doc(hidden)]
    pub fn add_annotation(&self, annotation: GraphAnnotation) -> Result<Graph> {
        self.get_context().add_graph_annotation(self, annotation)?;
        Ok(self.clone())
    }

    pub(super) fn get_annotations(&self) -> Result<Vec<GraphAnnotation>> {
        self.get_context().get_graph_annotations(self.clone())
    }

    /// Applies [Context::retrieve_node] to the parent context and `this` graph.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let n = g.input(scalar_type(BIT)).unwrap();
    /// n.set_name("input_node").unwrap();
    /// assert!(n == g.retrieve_node("input_node").unwrap());
    /// ```
    pub fn retrieve_node(&self, name: &str) -> Result<Node> {
        self.get_context().retrieve_node(self.clone(), name)
    }

    /// Rearrange given input values according to the names and the order of the related input nodes.
    ///
    /// For example, given a graph with the first input node named 'A' and the second one named 'B' and input values `{'B': v, 'A': w}`, this function returns a vector `[w, v]`.
    ///
    /// # Arguments
    ///
    /// `values` - hashmap of values keyed by node names
    ///
    /// # Returns
    ///
    /// Vector of values arranged by node names
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// # use std::collections::HashMap;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// n1.set_name("input1").unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// n2.set_name("input2").unwrap();
    ///
    /// let mut input_map = HashMap::new();
    /// input_map.insert("input2", 2);
    /// input_map.insert("input1", 1);
    /// let ordered_input = g.prepare_input_values(input_map).unwrap();
    ///
    /// assert_eq!(vec![1,2], ordered_input);
    /// ```
    pub fn prepare_input_values<T: Clone>(&self, values: HashMap<&str, T>) -> Result<Vec<T>> {
        self.get_context()
            .prepare_input_values(self.clone(), values)
    }
}

impl Node {
    /// Applies [Context::set_node_name] to the parent context and `this` node. Returns the clone of `this`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// n.set_name("XOR").unwrap();
    /// ```
    pub fn set_name(&self, name: &str) -> Result<Node> {
        self.get_graph()
            .get_context()
            .set_node_name(self.clone(), name)?;
        Ok(self.clone())
    }

    /// Applies [Context::get_node_name] to the parent context and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{scalar_type, BIT};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n = g.input(t).unwrap();
    /// n.set_name("XOR").unwrap();
    /// assert_eq!(n.get_name().unwrap(), "XOR".to_owned());
    /// ```
    pub fn get_name(&self) -> Result<String> {
        self.get_graph().get_context().get_node_name(self.clone())
    }

    #[doc(hidden)]
    pub fn add_annotation(&self, annotation: NodeAnnotation) -> Result<Node> {
        self.get_graph()
            .get_context()
            .add_node_annotation(self, annotation)?;
        Ok(self.clone())
    }

    #[doc(hidden)]
    pub fn get_annotations(&self) -> Result<Vec<NodeAnnotation>> {
        self.get_graph()
            .get_context()
            .get_node_annotations(self.clone())
    }

    /// Adds a node to the parent graph that adds elementwise the array or scalar associated with the node to an array or scalar of the same scalar type associated with another node.
    ///
    /// Applies [Graph::add] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.add(n2).unwrap();
    /// ```
    pub fn add(&self, b: Node) -> Result<Node> {
        self.get_graph().add(self.clone(), b)
    }

    /// Adds a node to the parent graph that subtracts elementwise the array or scalar of the same scalar type associated with another node from an array or scalar associated with the node.
    ///
    /// Applies [Graph::subtract] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.subtract(n2).unwrap();
    /// ```
    pub fn subtract(&self, b: Node) -> Result<Node> {
        self.get_graph().subtract(self.clone(), b)
    }

    /// Adds a node to the parent graph that multiplies elementwise the array or scalar associated with the node by an array or scalar of the same scalar type associated with another node.
    ///
    /// Applies [Graph::multiply] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, scalar_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = scalar_type(BIT);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.multiply(n2).unwrap();
    /// ```
    pub fn multiply(&self, b: Node) -> Result<Node> {
        self.get_graph().multiply(self.clone(), b)
    }

    /// Adds a node to the parent graph that computes the dot product of arrays or scalars associated with the node and another node.
    ///
    /// Applies [Graph::dot] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![10], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t).unwrap();
    /// let n3 = n1.dot(n2).unwrap();
    /// ```
    pub fn dot(&self, b: Node) -> Result<Node> {
        self.get_graph().dot(self.clone(), b)
    }

    /// Adds a node to the parent graph that computes the matrix product of two arrays associated with the node and another node.
    ///
    /// Applies [Graph::matmul] to the parent graph, `this` node and the `b` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![2, 3], INT32);
    /// let t2 = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = n1.matmul(n2).unwrap();
    /// ```
    pub fn matmul(&self, b: Node) -> Result<Node> {
        self.get_graph().matmul(self.clone(), b)
    }

    /// Adds a node to the parent graph that divides a scalar or each entry of the array associated with the node by a positive constant integer `scale`.
    ///
    /// Applies [Graph::add] to the parent graph, `this` node and `scale`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.truncate(4).unwrap();
    /// ```
    pub fn truncate(&self, scale: u64) -> Result<Node> {
        self.get_graph().truncate(self.clone(), scale)
    }

    /// Adds a node to the parent graph that computes the sum of entries of the array associated with the node along given axes.
    ///
    /// Applies [Graph::sum] to the parent graph, `this` node and `axes`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.sum(axes).unwrap();
    /// ```
    pub fn sum(&self, axes: ArrayShape) -> Result<Node> {
        self.get_graph().sum(self.clone(), axes)
    }

    /// Adds a node to the parent graph that permutes the array associated with the node along given axes.
    ///
    /// Applies [Graph::permute_axes] to the parent graph, `this` node and `axes`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let axes = vec![1, 0, 2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.permute_axes(axes).unwrap();
    /// ```
    pub fn permute_axes(&self, axes: ArrayShape) -> Result<Node> {
        self.get_graph().permute_axes(self.clone(), axes)
    }

    /// Adds a node to the parent graph that extracts a sub-array with a given index from the array associated with the node.
    ///
    /// Applies [Graph::get] to the parent graph, `this` node and `index`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let index = vec![2];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.get(index).unwrap();
    /// ```
    pub fn get(&self, index: ArrayShape) -> Result<Node> {
        self.get_graph().get(self.clone(), index)
    }

    /// Adds a node that extracts a sub-array corresponding to a given slice from the array associated with the node.
    ///
    /// Applies [Graph::get_slice] to the parent graph, `this` node and `slice`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::{create_context, SliceElement};
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let slice = vec![SliceElement::Ellipsis, SliceElement::SubArray(None, None, Some(-2))];
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.get_slice(slice).unwrap();
    /// ```
    pub fn get_slice(&self, slice: Slice) -> Result<Node> {
        self.get_graph().get_slice(self.clone(), slice)
    }

    /// Adds a node to the parent graph that reshapes a value associated with the node to a given compatible type.
    ///
    /// Applies [Graph::reshape] to the parent graph, `this` node and `new_type`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let old_t = array_type(vec![3, 2, 3], INT32);
    /// let new_t = array_type(vec![3,6], INT32);
    /// let n1 = g.input(old_t).unwrap();
    /// let n2 = n1.reshape(new_t).unwrap();
    /// ```
    pub fn reshape(&self, new_type: Type) -> Result<Node> {
        self.get_graph().reshape(self.clone(), new_type)
    }

    #[doc(hidden)]
    pub fn nop(&self) -> Result<Node> {
        self.get_graph().nop(self.clone())
    }

    #[doc(hidden)]
    pub fn prf(&self, iv: u64, output_type: Type) -> Result<Node> {
        self.get_graph().prf(self.clone(), iv, output_type)
    }

    /// Adds a node to the parent graph converting an integer array or scalar associated with the node to the binary form.
    ///
    /// Applies [Graph::a2b] to the parent graph and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.a2b().unwrap();
    /// ```
    pub fn a2b(&self) -> Result<Node> {
        self.get_graph().a2b(self.clone())
    }

    /// Adds a node to the parent graph converting a binary array associated with the node to an array of a given scalar type.
    ///
    /// Applies [Graph::b2a] to the parent graph, `this` node and `scalar_type`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{BIT, INT32, array_type};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 32], BIT);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.b2a(INT32).unwrap();
    /// ```
    pub fn b2a(&self, scalar_type: ScalarType) -> Result<Node> {
        self.get_graph().b2a(self.clone(), scalar_type)
    }

    /// Adds a node that extracts an element of a tuple associated with the node.
    ///
    /// Applies [Graph::tuple_get] to the parent graph, `this` node and `index`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_tuple(vec![n1, n2]).unwrap();
    /// let n4 = n3.tuple_get(1).unwrap();
    /// ```
    pub fn tuple_get(&self, index: u64) -> Result<Node> {
        self.get_graph().tuple_get(self.clone(), index)
    }

    /// Adds a node to the parent graph that extracts an element of a named tuple associated with the node.
    ///
    /// Applies [Graph::named_tuple_get] to the parent graph, `this` node and the `key` string.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t1 = array_type(vec![3, 2, 3], INT32);
    /// let t2 = array_type(vec![2, 3], INT32);
    /// let n1 = g.input(t1).unwrap();
    /// let n2 = g.input(t2).unwrap();
    /// let n3 = g.create_named_tuple(vec![("node1".to_owned(), n1), ("node2".to_owned(), n2)]).unwrap();
    /// let n4 = n3.named_tuple_get("node2".to_owned()).unwrap();
    /// ```
    pub fn named_tuple_get(&self, key: String) -> Result<Node> {
        self.get_graph().named_tuple_get(self.clone(), key)
    }

    /// Adds a node to the parent graph that extracts an element of a vector associated with the node.
    ///
    /// Applies [Graph::vector_get] to the parent graph, `this` node and the `index` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{UINT32, INT32, array_type, scalar_type};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t.clone()).unwrap();
    /// let n2 = g.input(t.clone()).unwrap();
    /// let n3 = g.create_vector(t, vec![n1,n2]).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n4 = n3.vector_get(index).unwrap();
    /// ```
    pub fn vector_get(&self, index: Node) -> Result<Node> {
        self.get_graph().vector_get(self.clone(), index)
    }

    /// Adds a node to the parent graph converting an array associated with the node to a vector.
    ///
    /// Applies [Graph::array_to_vector] to the parent graph and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, scalar_type, INT32, UINT32};
    /// # use ciphercore_base::data_values::Value;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![4, 3, 2], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = g.array_to_vector(n1).unwrap();
    /// let index = g.constant(scalar_type(UINT32), Value::from_scalar(0, UINT32).unwrap()).unwrap();
    /// let n3 = n2.vector_get(index).unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_vector());
    /// assert_eq!(n3.get_type().unwrap().get_shape(), vec![3,2]);
    /// ```
    pub fn array_to_vector(&self) -> Result<Node> {
        self.get_graph().array_to_vector(self.clone())
    }

    /// Adds a node to the parent graph converting a vector associated with the node to an array.
    ///
    /// Applies [Graph::vector_to_array] to the parent graph and `this` node.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = n1.vector_to_array().unwrap();
    ///
    /// assert!(n2.get_type().unwrap().is_array());
    /// assert_eq!(n2.get_type().unwrap().get_shape(), vec![4, 3, 2]);
    /// ```
    pub fn vector_to_array(&self) -> Result<Node> {
        self.get_graph().vector_to_array(self.clone())
    }

    /// Adds a node that creates a vector with `n` copies of a value of this node.
    ///
    /// Applies [Graph::repeat] to the parent graph, `this` node and `n`.
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::data_types::{INT32, array_type};
    /// # use ciphercore_base::graphs::create_context;
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2, 3], INT32);
    /// let n1 = g.input(t).unwrap();
    /// let n2 = n1.repeat(10).unwrap();
    /// ```
    pub fn repeat(&self, n: u64) -> Result<Node> {
        self.get_graph().repeat(self.clone(), n)
    }

    /// Applies [Graph::set_output_node] to the parent graph and `this` node.
    ///
    /// # Returns
    ///
    /// This node
    ///
    /// # Example
    ///
    /// ```
    /// # use ciphercore_base::graphs::create_context;
    /// # use ciphercore_base::data_types::{array_type, vector_type, INT32};
    /// let c = create_context().unwrap();
    /// let g = c.create_graph().unwrap();
    /// let t = array_type(vec![3, 2], INT32);
    /// let vec_t = vector_type(4, t);
    /// let n1 = g.input(vec_t).unwrap();
    /// let n2 = g.vector_to_array(n1).unwrap();
    /// n2.set_as_output().unwrap();
    /// g.finalize().unwrap();
    /// ```
    pub fn set_as_output(&self) -> Result<Node> {
        self.get_graph().set_output_node(self.clone())?;
        Ok(self.clone())
    }
}

// Pass the node name of `in_node` to `out_node` if it is present.
pub(crate) fn copy_node_name(in_node: Node, out_node: Node) -> Result<()> {
    let node_name_result = in_node.get_name();
    if let Ok(node_name) = node_name_result {
        out_node.set_name(&node_name)?;
    }
    Ok(())
}

impl Context {
    pub(super) fn downgrade(&self) -> WeakContext {
        WeakContext {
            body: Arc::downgrade(&self.body),
        }
    }
}
type WeakContextBodyPointer = Weak<AtomicRefCell<ContextBody>>;

pub(super) struct WeakContext {
    body: WeakContextBodyPointer,
}

impl WeakContext {
    //upgrade function panics if the the Context pointer it downgraded from went out of scope
    pub(super) fn upgrade(&self) -> Context {
        Context {
            body: self.body.upgrade().unwrap(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data_types::{
        array_type, scalar_type, tuple_type, vector_type, BIT, UINT16, UINT64,
    };
    use crate::version::DATA_VERSION;
    use std::rc::Rc;

    #[test]
    fn test_wellformed_cases() {
        let context = create_unchecked_context().unwrap();
        let graph = context.create_graph().unwrap();
        let input1 = graph.input(scalar_type(BIT)).unwrap();
        let input2 = graph.input(scalar_type(BIT)).unwrap();
        graph.add(input1.clone(), input2.clone()).unwrap();
        graph.subtract(input1.clone(), input2.clone()).unwrap();
        graph.multiply(input1.clone(), input2.clone()).unwrap();
        graph.dot(input1.clone(), input2.clone()).unwrap();
        graph.matmul(input1.clone(), input2.clone()).unwrap();
        graph.truncate(input1.clone(), 123).unwrap();
        let input3 = graph.input(array_type(vec![10, 20, 30], BIT)).unwrap();
        graph.sum(input3.clone(), vec![1, 2]).unwrap();
        graph.permute_axes(input3.clone(), vec![1, 2, 0]).unwrap();
        graph.get(input3.clone(), vec![1, 2]).unwrap();
        graph
            .reshape(input3.clone(), array_type(vec![20, 300], BIT))
            .unwrap();
        graph.nop(input3.clone()).unwrap();
        let key = graph.random(array_type(vec![128], BIT)).unwrap();
        graph
            .prf(key.clone(), 0, array_type(vec![10, 10], UINT64))
            .unwrap();
        graph
            .stack(vec![input1.clone(), input2.clone()], vec![2, 1])
            .unwrap();
        let c = graph
            .constant(scalar_type(BIT), Value::from_bytes(vec![1]))
            .unwrap();
        let input4 = graph.input(array_type(vec![10, 10], UINT64)).unwrap();
        let bits = graph.a2b(input4.clone()).unwrap();
        graph.b2a(bits.clone(), UINT64).unwrap();
        let t = graph
            .create_tuple(vec![input1.clone(), input2.clone()])
            .unwrap();
        let _v = graph
            .create_vector(scalar_type(BIT), vec![input1.clone(), input2.clone()])
            .unwrap();
        let nt = graph
            .create_named_tuple(vec![
                ("Name".to_owned(), input1.clone()),
                ("Gender".to_owned(), input2.clone()),
            ])
            .unwrap();
        graph.tuple_get(t, 1).unwrap();
        graph.named_tuple_get(nt, "Gender".to_owned()).unwrap();
        let v = graph.repeat(c.clone(), 100).unwrap();
        graph.zip(vec![v.clone(), v.clone(), v.clone()]).unwrap();
        let zero = graph
            .constant(scalar_type(UINT64), Value::from_bytes(vec![0; 8]))
            .unwrap();
        graph.vector_get(v, zero).unwrap();
        graph.array_to_vector(input1.clone()).unwrap();
        graph.vector_to_array(input1.clone()).unwrap();
    }

    #[test]
    fn call_iterate_test() {
        let context = create_unchecked_context().unwrap();
        let single_bit_adder = context.create_graph().unwrap();
        {
            let carry = single_bit_adder.input(scalar_type(BIT)).unwrap();
            let inputs = single_bit_adder
                .input(tuple_type(vec![scalar_type(BIT), scalar_type(BIT)]))
                .unwrap();
            let a = single_bit_adder.tuple_get(inputs.clone(), 0).unwrap();
            let b = single_bit_adder.tuple_get(inputs.clone(), 1).unwrap();
            let ac = single_bit_adder.add(carry.clone(), a.clone()).unwrap();
            let bc = single_bit_adder.add(carry.clone(), b.clone()).unwrap();
            let result = single_bit_adder.add(ac.clone(), b.clone()).unwrap();
            let result_carry = single_bit_adder
                .add(
                    single_bit_adder.multiply(ac.clone(), bc.clone()).unwrap(),
                    carry,
                )
                .unwrap();
            let output = single_bit_adder
                .create_tuple(vec![result_carry.clone(), result.clone()])
                .unwrap();
            single_bit_adder.set_output_node(output).unwrap();
            single_bit_adder.finalize().unwrap();
        }
        let v32 = vector_type(32, scalar_type(BIT));
        let adder = context.create_graph().unwrap();
        {
            let a = adder.input(v32.clone()).unwrap();
            let b = adder.input(v32.clone()).unwrap();
            let azb = adder.zip(vec![a, b]).unwrap();
            let c = adder
                .constant(scalar_type(BIT), Value::from_bytes(vec![0]))
                .unwrap();
            let cr = adder.iterate(single_bit_adder, c, azb).unwrap();
            let r = adder.tuple_get(cr, 1).unwrap();
            adder.set_output_node(r).unwrap();
            adder.finalize().unwrap();
        }
        let three_adder = context.create_graph().unwrap();
        let a = three_adder.input(v32.clone()).unwrap();
        let b = three_adder.input(v32.clone()).unwrap();
        let c = three_adder.input(v32.clone()).unwrap();
        let result = three_adder
            .call(
                adder.clone(),
                vec![three_adder.call(adder.clone(), vec![a, b]).unwrap(), c],
            )
            .unwrap();
        three_adder.set_output_node(result).unwrap();
        three_adder.finalize().unwrap();
        context.set_main_graph(three_adder).unwrap();
        context.finalize().unwrap();
    }

    #[test]
    fn test_malformed_graphs() {
        let context = create_unchecked_context().unwrap();
        let graph = context.create_graph().unwrap();
        let graph2 = context.create_graph().unwrap();
        let input1 = graph.input(scalar_type(UINT64)).unwrap();
        let input2 = graph2.input(scalar_type(UINT64)).unwrap();
        let e1 = graph.add(input1.clone(), input2.clone());
        assert!(e1.is_err());
        let fake_node = Node {
            body: Arc::new(AtomicRefCell::new(NodeBody {
                graph: graph.downgrade(),
                node_dependencies: vec![],
                graph_dependencies: vec![],
                operation: Operation::Input(scalar_type(BIT)),
                id: 0,
            })),
        };
        let e2 = graph.add(fake_node.clone(), input1.clone());
        assert!(e2.is_err());
        let fake_node_2 = Node {
            body: Arc::new(AtomicRefCell::new(NodeBody {
                graph: graph.downgrade(),
                node_dependencies: vec![],
                graph_dependencies: vec![],
                operation: Operation::Input(scalar_type(BIT)),
                id: 31337,
            })),
        };
        let e3 = graph.add(fake_node_2.clone(), input1.clone());
        assert!(e3.is_err());
        graph.set_output_node(input1.clone()).unwrap();
        graph.finalize().unwrap();
        let e4 = graph.add(input1.clone(), input1.clone());
        assert!(e4.is_err());
        let graph3 = context.create_graph().unwrap();
        let e5 = graph3.finalize();
        assert!(e5.is_err());
        let e6 = graph3.set_output_node(input1);
        assert!(e6.is_err());
    }

    #[test]
    fn test_malformed_contexts() {
        let context = create_unchecked_context().unwrap();
        let e1 = context.finalize();
        assert!(e1.is_err());
        let graph = context.create_graph().unwrap();
        let e2 = graph.finalize();
        assert!(e2.is_err());
        graph
            .set_output_node(graph.create_tuple(vec![]).unwrap())
            .unwrap();
        let e4 = context.set_main_graph(graph.clone());
        assert!(e4.is_err());
        graph.finalize().unwrap();
        let e3 = context.finalize();
        assert!(e3.is_err());
        context.set_main_graph(graph.clone()).unwrap();
        context.finalize().unwrap();
    }

    #[test]
    fn test_malformed_call_iterate() {
        let context1 = create_unchecked_context().unwrap();
        let graph1 = context1.create_graph().unwrap();
        let output = graph1.create_tuple(vec![]).unwrap();
        graph1.set_output_node(output).unwrap();
        let graph2 = context1.create_graph().unwrap();
        let e1 = graph2.call(graph1.clone(), vec![]);
        assert!(e1.is_err());
        graph1.finalize().unwrap();
        graph2.call(graph1.clone(), vec![]).unwrap();
        let context2 = create_unchecked_context().unwrap();
        let graph3 = context2.create_graph().unwrap();
        let e2 = graph3.call(graph1.clone(), vec![]);
        assert!(e2.is_err());
        let graph4 = context1.create_graph().unwrap();
        graph4.input(tuple_type(vec![])).unwrap();
        graph4.input(tuple_type(vec![])).unwrap();
        let t = graph4.create_tuple(vec![]).unwrap();
        let tt = graph4.create_tuple(vec![t.clone(), t.clone()]).unwrap();
        graph4.set_output_node(tt).unwrap();
        let graph5 = context1.create_graph().unwrap();
        let es = graph5.create_tuple(vec![]).unwrap();
        let v = graph5
            .repeat(graph5.create_tuple(vec![]).unwrap(), 10)
            .unwrap();
        let e3 = graph5.iterate(graph4.clone(), es.clone(), v.clone());
        assert!(e3.is_err());
        graph4.finalize().unwrap();
        graph5
            .iterate(graph4.clone(), es.clone(), v.clone())
            .unwrap();
        let graph6 = context2.create_graph().unwrap();
        let es = graph6.create_tuple(vec![]).unwrap();
        let v = graph6
            .repeat(graph6.create_tuple(vec![]).unwrap(), 10)
            .unwrap();
        let e4 = graph6.iterate(graph4.clone(), es.clone(), v.clone());
        assert!(e4.is_err());
    }

    #[test]
    fn test_graph_consistency() {
        let context = create_unchecked_context().unwrap();
        let graph = context.create_graph().unwrap();
        let input1 = graph.input(scalar_type(BIT)).unwrap();
        let input2 = graph.input(scalar_type(BIT)).unwrap();
        graph.add(input1.clone(), input2.clone()).unwrap();
        graph.set_output_node(input1.clone()).unwrap();
        graph.finalize().unwrap();
        for (i, node) in graph.get_nodes().iter().enumerate() {
            assert_eq!(node.get_id(), i as u64);
            assert!(graph == node.get_graph());
            for dependency in node.get_node_dependencies() {
                assert!(dependency.get_id() < node.get_id());
            }
        }
        let operations: Vec<Operation> = graph
            .get_nodes()
            .iter()
            .map(|x| x.get_operation())
            .collect();
        assert!(operations.len() == 3);
        match operations[0] {
            Operation::Input(_) => {}
            _ => {
                panic!("Input expected");
            }
        }
        match operations[1] {
            Operation::Input(_) => {}
            _ => {
                panic!("Input expected");
            }
        }
        match operations[2] {
            Operation::Add => {}
            _ => {
                panic!("Add expected");
            }
        }
    }

    #[test]
    fn test_unfinalized_graphs() {
        let context = create_unchecked_context().unwrap();
        let e = context.finalize();
        assert!(e.is_err());
        let graph = context.create_graph().unwrap();
        let graph2 = context.create_graph().unwrap();
        let e = context.finalize();
        assert!(e.is_err());
        let i = graph2.input(scalar_type(BIT)).unwrap();
        graph2.set_output_node(i).unwrap();
        graph2.finalize().unwrap();
        context.set_main_graph(graph2).unwrap();
        let e = context.finalize();
        assert!(e.is_err());
        let ii = graph.input(scalar_type(BIT)).unwrap();
        graph.set_output_node(ii).unwrap();
        graph.finalize().unwrap();
        context.finalize().unwrap();
    }

    #[test]
    fn test_operation_serialization() {
        let o = Operation::Constant(scalar_type(BIT), Value::from_bytes(vec![1]));
        let se = serde_json::to_string(&o).unwrap();
        assert_eq!(
            se,
            format!("{{\"Constant\":[{{\"Scalar\":{{\"signed\":false,\"modulus\":2}}}},{{\"version\":{},\"data\":\"{{\\\"body\\\":{{\\\"Bytes\\\":[1]}}}}\"}}]}}", DATA_VERSION)
        );
        let de = serde_json::from_str::<Operation>(&se).unwrap();
        assert_eq!(de, o);
    }

    fn context_generators() -> Vec<Box<dyn Fn() -> Context>> {
        let context1 = || {
            let context = create_unchecked_context().unwrap();
            context
        };
        let context2 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph).unwrap();
            context.finalize().unwrap();
            context
        };
        let context3 = || {
            let context = create_unchecked_context().unwrap();
            context.create_graph().unwrap();
            context
        };
        let context4 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context
        };
        let context5 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            graph.input(scalar_type(BIT)).unwrap();
            context
        };
        let context6 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            graph
                .constant(scalar_type(BIT), Value::from_bytes(vec![1]))
                .unwrap();
            context
        };
        let context7 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i1 = graph.input(scalar_type(BIT)).unwrap();
            let i2 = graph.input(scalar_type(BIT)).unwrap();
            graph.add(i1, i2).unwrap();
            context
        };
        let context8 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i1 = graph.input(scalar_type(BIT)).unwrap();
            let i2 = graph.input(scalar_type(BIT)).unwrap();
            graph.add(i2, i1).unwrap();
            context
        };
        let context9 = || {
            let context = create_unchecked_context().unwrap();
            let graph1 = context.create_graph().unwrap();
            let i1 = graph1.input(scalar_type(BIT)).unwrap();
            graph1.set_output_node(i1).unwrap();
            graph1.finalize().unwrap();
            let graph2 = context.create_graph().unwrap();
            let i2 = graph2.input(scalar_type(BIT)).unwrap();
            graph2.set_output_node(i2).unwrap();
            graph2.finalize().unwrap();
            let graph3 = context.create_graph().unwrap();
            let i = graph3.input(scalar_type(BIT)).unwrap();
            graph3.call(graph1, vec![i]).unwrap();
            context
        };
        let context10 = || {
            let context = create_unchecked_context().unwrap();
            let graph1 = context.create_graph().unwrap();
            let i1 = graph1.input(scalar_type(BIT)).unwrap();
            graph1.set_output_node(i1).unwrap();
            graph1.finalize().unwrap();
            let graph2 = context.create_graph().unwrap();
            let i2 = graph2.input(scalar_type(BIT)).unwrap();
            graph2.set_output_node(i2).unwrap();
            graph2.finalize().unwrap();
            let graph3 = context.create_graph().unwrap();
            let i = graph3.input(scalar_type(BIT)).unwrap();
            graph3.call(graph2, vec![i]).unwrap();
            context
        };
        let context11 = || {
            let context = create_unchecked_context().unwrap();
            let graph1 = context.create_graph().unwrap();
            let i1 = graph1.input(scalar_type(BIT)).unwrap();
            graph1.set_output_node(i1).unwrap();
            graph1.finalize().unwrap();
            let graph2 = context.create_graph().unwrap();
            let i2 = graph2.input(scalar_type(BIT)).unwrap();
            graph2.set_output_node(i2).unwrap();
            graph2.finalize().unwrap();
            let graph3 = context.create_graph().unwrap();
            let i = graph3.input(scalar_type(BIT)).unwrap();
            let o = graph3.call(graph2, vec![i]).unwrap();
            graph3.set_output_node(o).unwrap();
            context
        };
        let context12 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph).unwrap();
            context
        };
        let context13 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph.clone()).unwrap();
            context.set_graph_name(graph, "main").unwrap();
            context.finalize().unwrap();
            context
        };
        let context14 = || {
            let context = create_unchecked_context().unwrap();
            let graph = context.create_graph().unwrap();
            let i = graph.input(scalar_type(BIT)).unwrap();
            graph.set_output_node(i.clone()).unwrap();
            graph.finalize().unwrap();
            context.set_main_graph(graph.clone()).unwrap();
            context.set_graph_name(graph.clone(), "main").unwrap();
            context.set_node_name(i.clone(), "input").unwrap();
            context
                .add_graph_annotation(&graph, GraphAnnotation::AssociativeOperation)
                .unwrap();
            context
                .add_node_annotation(&i, NodeAnnotation::AssociativeOperation)
                .unwrap();
            context.finalize().unwrap();
            context
        };
        let mut closures: Vec<Box<dyn Fn() -> Context>> = vec![];
        closures.push(Box::new(context1));
        closures.push(Box::new(context2));
        closures.push(Box::new(context3));
        closures.push(Box::new(context4));
        closures.push(Box::new(context5));
        closures.push(Box::new(context6));
        closures.push(Box::new(context7));
        closures.push(Box::new(context8));
        closures.push(Box::new(context9));
        closures.push(Box::new(context10));
        closures.push(Box::new(context11));
        closures.push(Box::new(context12));
        closures.push(Box::new(context13));
        closures.push(Box::new(context14));
        closures
    }

    fn test_context_deep_equal_helper_equal<F>(f: F)
    where
        F: Fn() -> Context,
    {
        let context1 = f();
        let context2 = f();
        assert!(context1 != context2);
        assert!(contexts_deep_equal(context1, context2));
    }

    fn test_context_deep_equal_helper_nonequal<F1, F2>(f1: F1, f2: F2)
    where
        F1: Fn() -> Context,
        F2: Fn() -> Context,
    {
        let context1 = f1();
        let context2 = f2();
        assert!(context1 != context2);
        assert!(!contexts_deep_equal(context1, context2));
    }

    #[test]
    fn test_context_deep_equal() {
        let generators = context_generators();
        for i in 0..generators.len() {
            test_context_deep_equal_helper_equal(&generators[i]);
            for j in 0..i {
                test_context_deep_equal_helper_nonequal(&generators[i], &generators[j]);
            }
        }
    }

    pub fn deserialize_error_lenient(serialized_string: &str, error_msg: &str) {
        use std::panic::catch_unwind;
        let result = catch_unwind(|| serde_json::from_str::<Context>(serialized_string).unwrap());
        // This is a (nasty) hack.
        // We check whether the returned error contain the expected error message.
        use ciphercore_utils::execute_main::extract_panic_message;
        if let Err(e) = result {
            match extract_panic_message(e) {
                Some(msg) => {
                    if !msg.contains(error_msg) {
                        panic!("Undesireable panic: {}", msg);
                    }
                }
                None => panic!("Panic of unknown type"),
            }
        } else {
            panic!("Expected error not occur")
        }
    }

    use std::{
        fs::File,
        io::{prelude::*, BufReader},
        path::Path,
    };

    fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> {
        let file = File::open(filename).expect("no such file");
        let buf = BufReader::new(file);
        buf.lines()
            .map(|l| l.expect("Could not parse line"))
            .collect()
    }

    #[test]
    #[cfg(not(feature = "nightly-features"))]
    fn test_context_serialize() {
        let generators = context_generators();
        let contexts: Vec<Context> = generators.iter().map(|generator| generator()).collect();
        let serialized_contexts: Vec<String> = contexts
            .iter()
            .map(|context| serde_json::to_string(context).unwrap())
            .collect();
        let deserialized_contexts: Vec<Context> = serialized_contexts
            .iter()
            .map(|serialized_context| serde_json::from_str(serialized_context).unwrap())
            .collect();
        assert_eq!(contexts.len(), deserialized_contexts.len());
        for i in 0..contexts.len() {
            assert!(contexts[i] != deserialized_contexts[i]);
            assert!(contexts_deep_equal(
                contexts[i].clone(),
                deserialized_contexts[i].clone()
            ));
        }

        //Read test cases from golden file
        let test_case = lines_from_file("./src/test_data/version_testcase.txt");
        assert_eq!(serde_json::to_string(&contexts[0]).unwrap(), test_case[0]);

        //Following test case expect an error message "Non-existent main graph" which is caused by the field "\"main_graph\":918276318"
        deserialize_error_lenient(&test_case[1], "Non-existent main graph");
        assert_eq!(serde_json::to_string(&contexts[9]).unwrap(), test_case[2]);
        //Following test case expect an error message "Non-existent node dependency" which is caused by the field "\"node_dependencies\":[918723]"
        deserialize_error_lenient(&test_case[3], "Non-existent node dependency");
        //Following test case expect an error message "Non-existent graph dependency" which is caused by the field "\"graph_dependencies\":[918723]"
        deserialize_error_lenient(&test_case[4], "Non-existent graph dependency");
        assert_eq!(serde_json::to_string(&contexts[13]).unwrap(), test_case[5]);
        //Following test case expect an error message "Non-existent output node" which is caused by the field "\"output_node\":9817273"
        deserialize_error_lenient(&test_case[6], "Non-existent output node");
        //Following test case expect an error message "graphs_names contain an invalid ID" which is caused by the field "\"graphs_names\":[[8079123,\"main\"]]"
        deserialize_error_lenient(&test_case[7], "graphs_names contain an invalid ID");
        //Following test case expect an error message "nodes_names contain an invalid graph ID" which is caused by the field "\"nodes_names\":[[[8079123,0],\"input\"]]"
        deserialize_error_lenient(&test_case[8], "nodes_names contain an invalid graph ID");
        //Following test case expect an error message "nodes_names contain an invalid graph ID" which is caused by the field "\"nodes_names\":[[[0,8079123],\"input\"]]"
        deserialize_error_lenient(&test_case[9], "nodes_names contain an invalid node ID");
        //Following test case expect an error message "Context version doesn't match the requirement" which is caused by its old version number
        deserialize_error_lenient(
            &test_case[10],
            "Context version doesn't match the requirement",
        );
        //Following test case expect an error message "Context version doesn't match the requirement" which is caused by its old version number. Although its payload is unsupported, this should not cause any error before passing the version check.
        deserialize_error_lenient(
            &test_case[11],
            "Context version doesn't match the requirement",
        );
    }

    use crate::data_types::INT32;
    use crate::data_values::Value;
    use crate::evaluators::random_evaluate;
    use std::iter::FromIterator;

    #[test]
    fn test_named_contexts() {
        let helper = || -> Result<Context> {
            let context = create_context()?;
            let graph = context.create_graph()?;
            let input_a = graph.input(scalar_type(INT32))?;
            let input_b = graph.input(scalar_type(INT32))?;
            let output = graph.add(input_a.clone(), input_b.clone())?;
            graph.set_output_node(output.clone())?;
            graph.finalize()?;
            context.set_main_graph(graph.clone())?;
            assert!(context.get_graph_name(graph.clone()).is_err());
            assert!(context.retrieve_graph("main").is_err());
            assert!(context.get_node_name(input_a.clone()).is_err());
            assert!(context.retrieve_node(graph.clone(), "a").is_err());
            context.set_graph_name(graph.clone(), "main")?;
            context.set_node_name(input_a.clone(), "a")?;
            assert!(context.retrieve_node(graph.clone(), "b").is_err());
            context.set_node_name(input_b.clone(), "b")?;
            context.finalize()?;
            assert_eq!(context.get_graph_name(graph.clone())?, "main");
            assert_eq!(context.get_node_name(input_a.clone())?, "a");
            assert_eq!(context.get_node_name(input_b.clone())?, "b");
            assert!(context.retrieve_node(graph.clone(), "a")? == input_a.clone());
            Ok(context)
        };
        let context = helper().unwrap();
        let helper2 = |context: Context| -> Result<i32> {
            let other_context = create_context()?;
            let other_graph = other_context.create_graph()?;
            let input = other_graph.input(scalar_type(BIT))?;
            let other_input = other_graph.input(scalar_type(BIT))?;
            assert!(context
                .prepare_input_values::<Value>(other_graph.clone(), HashMap::new())
                .is_err());
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph.clone(),
                    HashMap::from_iter([("a", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            other_context.set_node_name(input, "b")?;
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph.clone(),
                    HashMap::from_iter([("a", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph.clone(),
                    HashMap::from_iter([("b", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            other_context.set_node_name(other_input, "c")?;
            assert!(other_context
                .prepare_input_values::<Value>(
                    other_graph,
                    HashMap::from_iter([("b", Value::from_scalar(123, INT32)?)])
                )
                .is_err());
            let g = context.retrieve_graph("main")?;
            let result = random_evaluate(
                g.clone(),
                context.prepare_input_values(
                    g.clone(),
                    HashMap::from_iter([
                        ("a", Value::from_scalar(123, INT32)?),
                        ("b", Value::from_scalar(456, INT32)?),
                    ]),
                )?,
            )?;
            let result = result.to_i32(INT32)?;
            Ok(result)
        };
        assert_eq!(helper2(context).unwrap(), 579);
        let helper3 = |context: Context| -> Result<()> {
            let other_context = create_context()?;
            let other_graph = other_context.create_graph()?;
            let other_node = other_graph.input(scalar_type(BIT))?;
            assert!(context
                .set_graph_name(other_graph.clone(), "outside")
                .is_err());
            assert!(context.get_graph_name(other_graph.clone()).is_err());
            assert!(context
                .set_node_name(other_node.clone(), "outside")
                .is_err());
            assert!(context.get_node_name(other_node.clone()).is_err());
            assert!(context.retrieve_node(other_graph.clone(), "a").is_err());
            Ok(())
        };
        helper3(helper().unwrap()).unwrap();
        let helper4 = || -> Result<()> {
            let context = create_context()?;
            let graph = context.create_graph()?;
            let input = graph.input(scalar_type(BIT))?;
            graph.set_output_node(input.clone())?;
            graph.finalize()?;
            context.set_main_graph(graph.clone())?;
            context.finalize()?;
            assert!(context.set_graph_name(graph, "main").is_err());
            assert!(context.set_node_name(input, "input").is_err());
            Ok(())
        };
        helper4().unwrap();
        let helper5 = || -> Result<()> {
            let context = create_context()?;
            let graph = context.create_graph()?;
            let input = graph.input(scalar_type(BIT))?;
            let other_graph = context.create_graph()?;
            let other_input = graph.input(scalar_type(BIT))?;
            context.set_graph_name(graph.clone(), "main")?;
            assert!(context.set_graph_name(graph, "main3").is_err());
            assert!(context.set_graph_name(other_graph, "main").is_err());
            context.set_node_name(input.clone(), "input")?;
            assert!(context.set_node_name(input, "input3").is_err());
            assert!(context.set_node_name(other_input, "input").is_err());
            Ok(())
        };
        helper5().unwrap();
    }

    #[test]
    fn test_context_type_checking() {
        || -> Result<()> {
            let context = create_context()?;
            let g = context.create_graph()?;
            let i = g.input(tuple_type(vec![]))?;
            assert!(g.add(i.clone(), i.clone()).is_err());
            // Now checking that the node actually have not gotten added by accident
            assert_eq!(g.get_nodes().len(), 1);
            Ok(())
        }()
        .unwrap();
    }

    fn generate_pair_of_equal_contexts() -> Vec<(Context, Context)> {
        let context1 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i = g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?;
            g.set_output_node(i)?;
            g.finalize()?;
            g.set_as_main()?;
            Ok(context)
        }()
        .unwrap();
        let context2 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i = g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?;
            i.set_as_output()?;
            g.finalize()?;
            context.set_main_graph(g)?;
            Ok(context)
        }()
        .unwrap();
        let context3 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            context.set_graph_name(g, "random graph name")?;
            Ok(context)
        }()
        .unwrap();
        let context4 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            context.create_graph()?.set_name("random graph name")?;
            Ok(context)
        }()
        .unwrap();
        let context5 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i = g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?;
            context.set_node_name(i, "random node name")?;
            Ok(context)
        }()
        .unwrap();
        let context6 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            g.constant(scalar_type(BIT), Value::from_scalar(0, BIT)?)?
                .set_name("random node name")?;
            Ok(context)
        }()
        .unwrap();
        let context7 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i1 = g.input(scalar_type(BIT))?;
            let i2 = g.input(scalar_type(BIT))?;
            g.add(i1.clone(), i2.clone())?;
            g.subtract(i1.clone(), i2.clone())?;
            g.multiply(i1.clone(), i2.clone())?;
            g.dot(i1.clone(), i2.clone())?;
            g.matmul(i1.clone(), i2.clone())?;
            g.truncate(i1.clone(), 123)?;
            g.sum(i1.clone(), vec![1, 4, 7])?;
            g.permute_axes(i1.clone(), vec![1, 4, 7])?;
            g.get(i1.clone(), vec![1, 4])?;
            g.reshape(i1.clone(), array_type(vec![12, 34], BIT))?;
            g.nop(i1.clone())?;
            g.prf(i1.clone(), 123, scalar_type(BIT))?;
            g.a2b(i1.clone())?;
            g.b2a(i1.clone(), BIT)?;
            g.tuple_get(i1.clone(), 0)?;
            g.named_tuple_get(i1.clone(), "field name".to_owned())?;
            g.vector_get(i1.clone(), i2)?;
            g.array_to_vector(i1.clone())?;
            g.vector_to_array(i1.clone())?;
            g.repeat(i1.clone(), 123)?;
            Ok(context)
        }()
        .unwrap();
        let context8 = || -> Result<Context> {
            let context = create_unchecked_context()?;
            let g = context.create_graph()?;
            let i1 = g.input(scalar_type(BIT))?;
            let i2 = g.input(scalar_type(BIT))?;
            i1.add(i2.clone())?;
            i1.subtract(i2.clone())?;
            i1.multiply(i2.clone())?;
            i1.dot(i2.clone())?;
            i1.matmul(i2.clone())?;
            i1.truncate(123)?;
            i1.sum(vec![1, 4, 7])?;
            i1.permute_axes(vec![1, 4, 7])?;
            i1.get(vec![1, 4])?;
            i1.reshape(array_type(vec![12, 34], BIT))?;
            i1.nop()?;
            i1.prf(123, scalar_type(BIT))?;
            i1.a2b()?;
            i1.b2a(BIT)?;
            i1.tuple_get(0)?;
            i1.named_tuple_get("field name".to_owned())?;
            i1.vector_get(i2)?;
            i1.array_to_vector()?;
            i1.vector_to_array()?;
            i1.repeat(123)?;
            Ok(context)
        }()
        .unwrap();
        let result = vec![
            (context1, context2),
            (context3, context4),
            (context5, context6),
            (context7, context8),
        ];
        result
    }

    #[test]
    fn test_node_graph_helpers() {
        let pairs_of_contexts = generate_pair_of_equal_contexts();
        for (context1, context2) in pairs_of_contexts {
            assert!(contexts_deep_equal(context1, context2));
        }
        || -> Result<()> {
            let context = create_context()?;
            let g = context.create_graph()?.set_name("graph name")?;
            let i = g.input(scalar_type(BIT))?.set_name("node name")?;
            assert_eq!(g.get_name()?, "graph name");
            assert!(g.retrieve_node("node name")? == i);
            assert!(i.get_name()? == "node name");
            assert_eq!(
                g.prepare_input_values(hashmap!("node name" => Value::from_scalar(1, BIT)?))?,
                vec![Value::from_scalar(1, BIT)?]
            );
            Ok(())
        }()
        .unwrap();
    }

    #[test]
    fn test_operation_fmt_display() {
        let test_operation_fmt_display_helper = || -> Result<()> {
            let o0 = Rc::new(Operation::Input(scalar_type(UINT16)));
            assert_eq!(format!("{}", o0), "Input");
            let o1 = Rc::new(Operation::Add);
            assert_eq!(format!("{}", o1), "Add");
            let o2 = Rc::new(Operation::Truncate(10));
            assert_eq!(format!("{}", o2), "Truncate");
            let o3 = Rc::new(Operation::Get(vec![10, 20]));
            assert_eq!(format!("{}", o3), "Get");
            let o4 = Rc::new(Operation::NOP);
            assert_eq!(format!("{}", o4), "NOP");
            let o5 = Rc::new(Operation::CreateNamedTuple(vec![
                "Name".to_string(),
                "Address".to_string(),
            ]));
            assert_eq!(format!("{}", o5), "CreateNamedTuple");
            let o6 = Rc::new(Operation::NamedTupleGet("Name".to_string()));
            assert_eq!(format!("{}", o6), "NamedTupleGet");
            Ok(())
        };
        test_operation_fmt_display_helper().unwrap();
    }

    #[test]
    fn test_annotations() {
        let test_annotations_helper = || -> Result<()> {
            let context = create_context()?;
            let g = context.create_graph()?;
            let i = g.input(scalar_type(BIT))?;
            g.add_annotation(GraphAnnotation::AssociativeOperation)?;
            i.add_annotation(NodeAnnotation::AssociativeOperation)?;
            assert_eq!(
                g.get_annotations()?,
                vec![GraphAnnotation::AssociativeOperation]
            );
            assert_eq!(
                i.get_annotations()?,
                vec![NodeAnnotation::AssociativeOperation]
            );
            Ok(())
        };
        test_annotations_helper().unwrap();
    }
}