autonomi 0.9.0

Autonomi client API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
// Copyright 2025 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

// Standard library imports
use std::{
    path::PathBuf,
    str::FromStr,
    sync::Arc,
    time::{Duration, SystemTime},
};

// External dependencies
use ant_bootstrap::{Bootstrap, BootstrapConfig};
use ant_evm::{PaymentQuote, QuotingMetrics, RewardsAddress};
use ant_protocol::storage::DataTypes;
use bls::{PK_SIZE, PublicKey, SecretKey};
use bytes::Bytes;
use exponential_backoff::Backoff;
use libp2p::Multiaddr;
use pyo3::{
    basic::CompareOp,
    exceptions::{PyConnectionError, PyRuntimeError, PyValueError},
    prelude::*,
};
use pyo3_async_runtimes::tokio::future_into_py;
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use tokio::sync::mpsc;
use xor_name::{XOR_NAME_LEN, XorName};

// Internal imports
use crate::{
    Amount, AttoTokens, Chunk, ChunkAddress, Client, ClientConfig, ClientOperatingStrategy,
    GraphEntry, GraphEntryAddress, InitialPeersConfig, MaxFeePerGas, Network as EVMNetwork,
    Pointer, PointerAddress, Scratchpad, ScratchpadAddress, Signature, TransactionConfig, Wallet,
    client::{
        ClientEvent, UploadSummary,
        chunk::DataMapChunk,
        data::DataAddress,
        files::{archive_private::PrivateArchiveDataMap, archive_public::ArchiveAddress},
        key_derivation::{
            DerivationIndex, DerivedPubkey, DerivedSecretKey, MainPubkey, MainSecretKey,
        },
        payment::{PaymentOption, Receipt},
        pointer::PointerTarget,
        quote::{QuoteForAddress, StoreQuote},
        vault::{UserData, VaultSecretKey},
    },
    files::{Metadata, PrivateArchive, PublicArchive},
    networking::{PeerId, Quorum, RetryStrategy, Strategy},
    register::{RegisterAddress, RegisterHistory},
};

/// Helper function to convert ScratchpadError to appropriate Python exception
fn scratchpad_error_to_py_err(
    error: crate::client::data_types::scratchpad::ScratchpadError,
) -> PyErr {
    use crate::client::data_types::scratchpad::ScratchpadError;

    match error {
        ScratchpadError::Fork(conflicting_scratchpads) => {
            // Convert Rust scratchpads to Python scratchpads
            let py_scratchpads: Vec<PyScratchpad> = conflicting_scratchpads
                .iter()
                .map(|s| PyScratchpad { inner: s.clone() })
                .collect();

            // Create the fork error message
            let message = format!("{}", ScratchpadError::Fork(conflicting_scratchpads.clone()));

            // Create a runtime error with the conflicting scratchpads attached
            Python::with_gil(|py| {
                let exception = PyRuntimeError::new_err(message);
                if let Ok(exc_value) = exception
                    .value(py)
                    .downcast::<pyo3::exceptions::PyRuntimeError>()
                {
                    let _ = exc_value.setattr("conflicting_scratchpads", py_scratchpads);
                }
                exception
            })
        }
        _ => PyRuntimeError::new_err(format!("{error}")),
    }
}

#[pyclass(name = "AttoTokens")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PyAttoTokens {
    inner: AttoTokens,
}

#[pymethods]
impl PyAttoTokens {
    /// Creates a new instance with zero tokens
    #[staticmethod]
    fn zero() -> Self {
        Self {
            inner: AttoTokens::zero(),
        }
    }

    /// Returns whether this represents zero tokens
    fn is_zero(&self) -> bool {
        self.inner.is_zero()
    }

    /// Creates a new instance from atto amount
    #[staticmethod]
    fn from_atto(value: String) -> PyResult<Self> {
        let amount = Amount::from_str(&value)
            .map_err(|e| PyValueError::new_err(format!("Invalid amount: {e}")))?;
        Ok(Self {
            inner: AttoTokens::from_atto(amount),
        })
    }

    /// Creates a new instance from a u64 number of atto tokens
    #[staticmethod]
    fn from_u64(value: u64) -> Self {
        Self {
            inner: AttoTokens::from_u64(value),
        }
    }

    /// Creates a new instance from a u128 number of atto tokens
    #[staticmethod]
    fn from_u128(value: u128) -> Self {
        Self {
            inner: AttoTokens::from_u128(value),
        }
    }

    /// Gets the amount as an atto value string
    fn as_atto(&self) -> String {
        self.inner.as_atto().to_string()
    }

    /// Adds another AttoTokens value, returning None if overflow occurred
    fn checked_add(&self, rhs: &PyAttoTokens) -> Option<PyAttoTokens> {
        self.inner
            .checked_add(rhs.inner)
            .map(|inner| PyAttoTokens { inner })
    }

    /// Subtracts another AttoTokens value, returning None if overflow occurred
    fn checked_sub(&self, rhs: &PyAttoTokens) -> Option<PyAttoTokens> {
        self.inner
            .checked_sub(rhs.inner)
            .map(|inner| PyAttoTokens { inner })
    }

    /// Converts the value as/to bytes
    fn as_bytes(&self) -> Vec<u8> {
        self.inner.to_bytes()
    }

    /// Creates a new instance from a string representation
    #[staticmethod]
    fn from_str(value_str: &str) -> PyResult<Self> {
        AttoTokens::from_str(value_str)
            .map(|inner| Self { inner })
            .map_err(|e| PyValueError::new_err(format!("Failed to parse AttoTokens: {e}")))
    }

    /// Returns the string representation of the value
    fn __str__(&self) -> String {
        self.inner.to_string()
    }

    /// Returns the representation of the value for debugging
    fn __repr__(&self) -> String {
        format!("AttoTokens('{}')", self.inner)
    }
}

#[pyclass(name = "DataTypes", eq, eq_int)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PyDataTypes {
    Chunk = 0,
    GraphEntry = 1,
    Pointer = 2,
    Scratchpad = 3,
}

impl From<PyDataTypes> for DataTypes {
    fn from(py_data_type: PyDataTypes) -> Self {
        match py_data_type {
            PyDataTypes::Chunk => DataTypes::Chunk,
            PyDataTypes::GraphEntry => DataTypes::GraphEntry,
            PyDataTypes::Pointer => DataTypes::Pointer,
            PyDataTypes::Scratchpad => DataTypes::Scratchpad,
        }
    }
}

#[pyclass(name = "Client")]
pub(crate) struct PyClient {
    inner: Client,
}

#[pymethods]
impl PyClient {
    /// Initialize the client with default configuration.
    #[staticmethod]
    fn init(py: Python) -> PyResult<Bound<PyAny>> {
        future_into_py(py, async {
            let inner = Client::init()
                .await
                .map_err(|e| PyConnectionError::new_err(format!("Failed to connect: {e}")))?;
            Ok(PyClient { inner })
        })
    }

    /// Initialize a client that is configured to be local.
    #[staticmethod]
    fn init_local(py: Python) -> PyResult<Bound<PyAny>> {
        future_into_py(py, async {
            let inner = Client::init_local()
                .await
                .map_err(|e| PyConnectionError::new_err(format!("Failed to connect: {e}")))?;
            Ok(PyClient { inner })
        })
    }

    /// Initialize a client that is configured to be connected to the alpha network.
    #[staticmethod]
    fn init_alpha(py: Python) -> PyResult<Bound<PyAny>> {
        future_into_py(py, async {
            let inner = Client::init_alpha()
                .await
                .map_err(|e| PyConnectionError::new_err(format!("Failed to connect: {e}")))?;
            Ok(PyClient { inner })
        })
    }

    /// Initialize a client that bootstraps from a list of peers.
    ///
    /// If any of the provided peers is a global address, the client will not be local.
    #[staticmethod]
    fn init_with_peers(py: Python, peers: Vec<String>) -> PyResult<Bound<PyAny>> {
        let peers: Vec<Multiaddr> = peers
            .iter()
            .map(|p| Multiaddr::from_str(p))
            .collect::<Result<_, _>>()
            .map_err(|e| PyValueError::new_err(format!("Failed to parse peers: {e}")))?;

        future_into_py(py, async {
            let inner = Client::init_with_peers(peers)
                .await
                .map_err(|e| PyConnectionError::new_err(format!("Failed to connect: {e}")))?;
            Ok(PyClient { inner })
        })
    }

    /// Initialize the client with the given configuration.
    #[staticmethod]
    fn init_with_config(py: Python, config: PyClientConfig) -> PyResult<Bound<PyAny>> {
        future_into_py(py, async {
            let inner = Client::init_with_config(config.inner)
                .await
                .map_err(|e| PyConnectionError::new_err(format!("Failed to connect: {e}")))?;
            Ok(PyClient { inner })
        })
    }

    fn enable_client_events(&mut self) -> PyClientEventReceiver {
        let receiver = self.inner.enable_client_events();
        PyClientEventReceiver {
            inner: Arc::new(futures::lock::Mutex::new(receiver)),
        }
    }

    /// Returns the EVM network used by this client.
    fn evm_network(&self) -> PyEVMNetwork {
        PyEVMNetwork {
            inner: self.inner.evm_network().clone(),
        }
    }

    /// Set the payment mode for uploads.
    fn with_payment_mode(
        mut slf: PyRefMut<'_, Self>,
        payment_mode: PyPaymentMode,
    ) -> PyRefMut<'_, Self> {
        let mode = match payment_mode {
            PyPaymentMode::Standard => crate::client::quote::PaymentMode::Standard,
            PyPaymentMode::SingleNode => crate::client::quote::PaymentMode::SingleNode,
        };
        slf.inner = slf.inner.clone().with_payment_mode(mode);
        slf
    }

    /// Get the cost of storing a chunk on the network
    fn chunk_cost<'a>(&self, py: Python<'a>, addr: PyChunkAddress) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .chunk_cost(&addr.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get chunk cost: {e}")))?;
            Ok(cost.to_string())
        })
    }

    /// Get a chunk from the network.
    fn chunk_get<'a>(&self, py: Python<'a>, addr: &PyChunkAddress) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let addr = addr.inner;

        future_into_py(py, async move {
            let chunk = client
                .chunk_get(&addr)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get chunk: {e}")))?;
            Ok(chunk.value.to_vec())
        })
    }

    /// Manually upload a chunk to the network. It is recommended to use the `data_put` method instead to upload data.
    fn chunk_put<'a>(
        &self,
        py: Python<'a>,
        data: Vec<u8>,
        payment: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment.inner.clone();
        let chunk = Chunk::new(Bytes::from(data));

        future_into_py(py, async move {
            let (cost, addr) = client
                .chunk_put(&chunk, payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to put chunk: {e}")))?;
            Ok((cost.to_string(), PyChunkAddress { inner: addr }))
        })
    }

    /// Fetches a GraphEntry from the network.
    fn graph_entry_get<'a>(
        &self,
        py: Python<'a>,
        addr: PyGraphEntryAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let entry = client
                .graph_entry_get(&addr.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get graph entry: {e}")))?;
            Ok(PyGraphEntry { inner: entry })
        })
    }

    /// Check if a graph_entry exists on the network
    fn graph_entry_check_existance<'a>(
        &self,
        py: Python<'a>,
        addr: PyGraphEntryAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let exists = client
                .graph_entry_check_existence(&addr.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get graph entry: {e}")))?;
            Ok(exists)
        })
    }

    /// Manually puts a GraphEntry to the network.
    fn graph_entry_put<'a>(
        &self,
        py: Python<'a>,
        entry: PyGraphEntry,
        payment_option: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment_option.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .graph_entry_put(entry.inner, payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get graph entry: {e}")))?;

            Ok((cost.to_string(), PyGraphEntryAddress { inner: addr }))
        })
    }

    /// Get the cost to create a GraphEntry
    fn graph_entry_cost<'a>(&self, py: Python<'a>, key: PyPublicKey) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client.graph_entry_cost(&key.inner).await.map_err(|e| {
                PyRuntimeError::new_err(format!("Failed to get graph entry cost: {e}"))
            })?;

            Ok(cost.to_string())
        })
    }

    /// Get Scratchpad from the Network.
    /// A Scratchpad is stored at the owner's public key so we can derive the address from it.
    fn scratchpad_get_from_public_key<'a>(
        &self,
        py: Python<'a>,
        public_key: PyPublicKey,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let scratchpad = client
                .scratchpad_get_from_public_key(&public_key.inner)
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok(PyScratchpad { inner: scratchpad })
        })
    }

    /// Get Scratchpad from the Network using the scratpad address.
    fn scratchpad_get<'a>(
        &self,
        py: Python<'a>,
        addr: PyScratchpadAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let scratchpad = client
                .scratchpad_get(&addr.inner)
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok(PyScratchpad { inner: scratchpad })
        })
    }

    /// Check if a scratchpad exists on the network
    fn scratchpad_check_existance<'a>(
        &self,
        py: Python<'a>,
        addr: PyScratchpadAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let exists = client
                .scratchpad_check_existence(&addr.inner)
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok(exists)
        })
    }

    /// Manually store a scratchpad on the network
    fn scratchpad_put<'a>(
        &self,
        py: Python<'a>,
        scratchpad: PyScratchpad,
        payment_option: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment_option.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .scratchpad_put(scratchpad.inner, payment)
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok((cost.to_string(), PyScratchpadAddress { inner: addr }))
        })
    }

    /// Update an existing scratchpad from a specific scratchpad
    ///
    /// This will increment the counter of the scratchpad and update the content
    /// This function is used internally by `Client.scratchpad_update` after the scratchpad has been retrieved from the network.
    /// To skip the retrieval step if you already have the scratchpad, use this function directly
    /// This function will return the new scratchpad after it has been updated
    fn scratchpad_put_update<'a>(
        &self,
        py: Python<'a>,
        scratchpad: PyScratchpad,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            client
                .scratchpad_put_update(scratchpad.inner)
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok(())
        })
    }

    /// Create a new scratchpad to the network.
    ///
    /// Make sure that the owner key is not already used for another scratchpad as each key is associated with one scratchpad.
    /// The data will be encrypted with the owner key before being stored on the network.
    /// The content type is used to identify the type of data stored in the scratchpad, the choice is up to the caller.
    ///
    /// Returns the cost and the address of the scratchpad.
    fn scratchpad_create<'a>(
        &self,
        py: Python<'a>,
        owner: PySecretKey,
        content_type: u64,
        initial_data: Vec<u8>,
        payment_option: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment_option.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .scratchpad_create(
                    &owner.inner,
                    content_type,
                    &Bytes::from(initial_data),
                    payment,
                )
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok((cost.to_string(), PyScratchpadAddress { inner: addr }))
        })
    }

    /// Update an existing scratchpad to the network.
    /// The scratchpad needs to be created first with `scratchpad_create`.
    /// This operation is free as the scratchpad was already paid for at creation.
    /// Only the latest version of the scratchpad is kept on the Network, previous versions will be overwritten and unrecoverable.
    fn scratchpad_update<'a>(
        &self,
        py: Python<'a>,
        owner: PySecretKey,
        content_type: u64,
        data: Vec<u8>,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            client
                .scratchpad_update(&owner.inner, content_type, &Bytes::from(data))
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok(())
        })
    }

    /// Update an existing scratchpad from a specific scratchpad to the network.
    ///
    /// This will increment the counter of the scratchpad and update the content.
    /// This function is used internally by `scratchpad_update` after the scratchpad has been retrieved from the network.
    /// To skip the retrieval step if you already have the scratchpad, use this function directly.
    /// This function will return the new scratchpad after it has been updated.
    fn scratchpad_update_from<'a>(
        &self,
        py: Python<'a>,
        current: PyScratchpad,
        owner: PySecretKey,
        content_type: u64,
        data: Vec<u8>,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let new_scratchpad = client
                .scratchpad_update_from(
                    &current.inner,
                    &owner.inner,
                    content_type,
                    &Bytes::from(data),
                )
                .await
                .map_err(scratchpad_error_to_py_err)?;

            Ok(PyScratchpad {
                inner: new_scratchpad,
            })
        })
    }

    /// Get the cost of creating a new Scratchpad
    fn scratchpad_cost<'a>(
        &self,
        py: Python<'a>,
        public_key: PyPublicKey,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .scratchpad_cost(&public_key.inner)
                .await
                .map_err(|e| {
                    PyRuntimeError::new_err(format!("Failed to get scratchpad cost: {e}"))
                })?;

            Ok(cost.to_string())
        })
    }

    /// Verify a scratchpad
    #[staticmethod]
    fn scratchpad_verify(scratchpad: &PyScratchpad) -> PyResult<()> {
        Client::scratchpad_verify(&scratchpad.inner).map_err(scratchpad_error_to_py_err)
    }

    /// Get the cost of storing an archive on the network
    fn archive_cost<'a>(
        &self,
        py: Python<'a>,
        archive: PyPublicArchive,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .archive_cost(&archive.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get archive cost: {e}")))?;
            Ok(cost.to_string())
        })
    }

    /// Fetch a private archive from the network using its datamap
    fn archive_get<'a>(
        &self,
        py: Python<'a>,
        data_map: &PyDataMapChunk,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let data_map = data_map.inner.clone();

        future_into_py(py, async move {
            let archive = client
                .archive_get(&data_map)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get archive: {e}")))?;

            Ok(PyPrivateArchive { inner: archive })
        })
    }

    /// Upload a private archive to the network
    fn archive_put<'a>(
        &self,
        py: Python<'a>,
        archive: PyPrivateArchive,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, data_map) = client
                .archive_put(&archive.inner, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to put archive: {e}")))?;

            Ok((cost.to_string(), PyDataMapChunk { inner: data_map }))
        })
    }

    /// Upload a public archive to the network
    fn archive_put_public<'a>(
        &self,
        py: Python<'a>,
        archive: PyPublicArchive,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .archive_put_public(&archive.inner, payment.inner)
                .await
                .map_err(|e| {
                    PyRuntimeError::new_err(format!("Failed to put public archive: {e}"))
                })?;

            Ok((cost.to_string(), PyArchiveAddress { inner: addr }))
        })
    }

    /// Get the cost to upload a file/dir to the network.
    fn file_cost<'a>(&self, py: Python<'a>, path: PathBuf) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .file_cost(&path)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get file cost: {e}")))?;

            Ok(cost.to_string())
        })
    }

    /// Download a private file from network to local file system.
    fn file_download<'a>(
        &self,
        py: Python<'a>,
        data_map: PyDataMapChunk,
        path: PathBuf,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            client
                .file_download(&data_map.inner, path)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to download file: {e}")))?;

            Ok(())
        })
    }

    /// Download a private directory from network to local file system
    fn dir_download<'a>(
        &self,
        py: Python<'a>,
        data_map: PyPrivateArchiveDataMap,
        dir_path: PathBuf,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            client
                .dir_download(&data_map.inner, dir_path)
                .await
                .map_err(|e| {
                    PyRuntimeError::new_err(format!("Failed to download directory: {e}"))
                })?;
            Ok(())
        })
    }

    /// Upload a directory to the network. The directory is recursively walked and each file is uploaded to the network.
    /// The datamaps of these (private) files are not uploaded but returned within the PrivateArchive return type.
    fn dir_content_upload<'a>(
        &self,
        py: Python<'a>,
        dir_path: PathBuf,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, archive) = client
                .dir_content_upload(dir_path, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to upload directory: {e}")))?;
            Ok((cost.to_string(), PyPrivateArchive { inner: archive }))
        })
    }

    /// Download file from network to local file system.
    fn file_download_public<'a>(
        &self,
        py: Python<'a>,
        addr: &PyDataAddress,
        path: PathBuf,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        let addr = addr.inner;
        future_into_py(py, async move {
            client
                .file_download_public(&addr, path)
                .await
                .map_err(|e| {
                    PyRuntimeError::new_err(format!("Failed to download public file: {e}"))
                })?;

            Ok(())
        })
    }

    /// Same as `dir_upload` but also uploads the archive (privately) to the network.
    ///
    /// Returns the datamap allowing the private archive to be downloaded from the network.
    fn dir_upload<'a>(
        &self,
        py: Python<'a>,
        dir_path: PathBuf,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, data_map) = client
                .dir_upload(dir_path, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to upload directory: {e}")))?;
            Ok((
                cost.to_string(),
                PyPrivateArchiveDataMap { inner: data_map },
            ))
        })
    }

    /// Upload the content of a private file to the network.
    /// Reads file, splits into chunks, uploads chunks, returns [`DataMapChunk`]
    fn file_content_upload<'a>(
        &self,
        py: Python<'a>,
        path: PathBuf,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, data_map) = client
                .file_content_upload(path, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to upload file: {e}")))?;
            Ok((cost.to_string(), PyDataMapChunk { inner: data_map }))
        })
    }

    /// Upload the content of a public file to the network.
    /// Reads file, splits into chunks, uploads chunks, uploads datamap, returns DataAddr (pointing to the datamap)
    fn file_content_upload_public<'a>(
        &self,
        py: Python<'a>,
        path: PathBuf,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, data_addr) = client
                .file_content_upload_public(path, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to upload file: {e}")))?;
            Ok((cost.to_string(), PyDataAddress { inner: data_addr }))
        })
    }

    /// Upload a piece of private data to the network. This data will be self-encrypted.
    /// The [`DataMapChunk`] is not uploaded to the network, keeping the data private.
    ///
    /// Returns the [`DataMapChunk`] containing the map to the encrypted chunks.
    fn data_put<'a>(
        &self,
        py: Python<'a>,
        data: Vec<u8>,
        payment: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment.inner.clone();

        future_into_py(py, async move {
            let (cost, data_map) = client
                .data_put(Bytes::from(data), payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to put data: {e}")))?;
            Ok((cost.to_string(), PyDataMapChunk { inner: data_map }))
        })
    }

    /// Fetch a blob of (private) data from the network
    fn data_get<'a>(&self, py: Python<'a>, access: &PyDataMapChunk) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let access = access.inner.clone();

        future_into_py(py, async move {
            let data = client
                .data_get(&access)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get data: {e}")))?;
            Ok(data.to_vec())
        })
    }

    /// Stream a blob of (private) data from the network. Returns a Python iterator.
    /// Use this for large blobs of data to avoid loading everything into memory.
    fn data_stream<'a>(
        &self,
        py: Python<'a>,
        access: &PyDataMapChunk,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let access = access.inner.clone();

        future_into_py(py, async move {
            let stream = client
                .data_stream(&access)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to create stream: {e}")))?;
            Ok(PyDataStream::new(stream))
        })
    }

    /// Get the estimated cost of storing a piece of data.
    fn data_cost<'a>(&self, py: Python<'a>, data: Vec<u8>) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .data_cost(Bytes::from(data))
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get data cost: {e}")))?;
            Ok(cost.to_string())
        })
    }

    /// Upload a piece of data to the network. This data is publicly accessible.
    ///
    /// Returns the Data Address at which the data was stored.
    fn data_put_public<'a>(
        &self,
        py: Python<'a>,
        data: Vec<u8>,
        payment: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .data_put_public(bytes::Bytes::from(data), payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to put data: {e}")))?;

            Ok((cost.to_string(), PyDataAddress { inner: addr }))
        })
    }

    /// Fetch a blob of data from the network
    fn data_get_public<'a>(
        &self,
        py: Python<'a>,
        addr: &PyDataAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        let addr = addr.inner;
        future_into_py(py, async move {
            let data = client
                .data_get_public(&addr)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get data: {e}")))?;
            Ok(data.to_vec())
        })
    }

    /// Stream a blob of public data from the network. Returns a Python iterator.
    /// Use this for large blobs of data to avoid loading everything into memory.
    fn data_stream_public<'a>(
        &self,
        py: Python<'a>,
        addr: &PyDataAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let addr = addr.inner;

        future_into_py(py, async move {
            let stream = client
                .data_stream_public(&addr)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to create stream: {e}")))?;
            Ok(PyDataStream::new(stream))
        })
    }

    /// Upload a directory as a public archive to the network.
    /// Returns the network address where the archive is stored.
    fn dir_upload_public<'a>(
        &self,
        py: Python<'a>,
        dir_path: PathBuf,
        payment: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .dir_upload_public(dir_path, payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to upload directory: {e}")))?;
            Ok((cost.to_string(), PyArchiveAddress { inner: addr }))
        })
    }

    /// Download a public archive from the network to a local directory.
    fn dir_download_public<'a>(
        &self,
        py: Python<'a>,
        addr: &PyArchiveAddress,
        dir_path: PathBuf,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        let addr = addr.inner;
        future_into_py(py, async move {
            client
                .dir_download_public(&addr, dir_path)
                .await
                .map_err(|e| {
                    PyRuntimeError::new_err(format!("Failed to download directory: {e}"))
                })?;
            Ok(())
        })
    }

    /// Upload a directory to the network. The directory is recursively walked and each file is uploaded to the network.
    ///
    /// The datamaps of these files are uploaded on the network, making the individual files publicly available.
    ///
    /// This returns, but does not upload (!),the `PublicArchive` containing the datamaps of the uploaded files.
    fn dir_content_upload_public<'a>(
        &self,
        py: Python<'a>,
        dir_path: PathBuf,
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, archive) = client
                .dir_content_upload_public(dir_path, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to upload directory: {e}")))?;
            Ok((cost.to_string(), PyPublicArchive { inner: archive }))
        })
    }

    /// Get a public archive from the network.
    fn archive_get_public<'a>(
        &self,
        py: Python<'a>,
        addr: &PyArchiveAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        let addr = addr.inner;
        future_into_py(py, async move {
            let archive = client
                .archive_get_public(&addr)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get archive: {e}")))?;

            Ok(PyPublicArchive { inner: archive })
        })
    }

    /// Get the cost of creating a new vault.
    fn vault_cost<'a>(
        &self,
        py: Python<'a>,
        key: &PyVaultSecretKey,
        max_expected_size: u64,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let key = key.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .vault_cost(&key, max_expected_size)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get vault cost: {e}")))?;
            Ok(cost.to_string())
        })
    }

    /// Put data into the client's VaultPacket
    ///
    /// Dynamically expand the vault capacity by paying for more space (Scratchpad) when needed.
    ///
    /// It is recommended to use the hash of the app name or unique identifier as the content type.
    fn vault_put<'a>(
        &self,
        py: Python<'a>,
        data: Vec<u8>,
        payment: &PyPaymentOption,
        key: &PyVaultSecretKey,
        content_type: u64,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment.inner.clone();
        let key = key.inner.clone();

        future_into_py(py, async move {
            match client
                .vault_put(bytes::Bytes::from(data), payment, &key, content_type)
                .await
            {
                Ok(cost) => Ok(cost.to_string()),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to write to vault: {e}"
                ))),
            }
        })
    }

    /// Get the register history, starting from the root to the latest entry.
    ///
    /// This returns a [`RegisterHistory`] that can be use to get the register values from the history.
    ///
    /// [`RegisterHistory::next`] can be used to get the values one by one, from the first to the latest entry.
    /// [`RegisterHistory::collect`] can be used to get all the register values from the history from the first to the latest entry.
    fn register_history(&self, addr: String) -> PyResult<PyRegisterHistory> {
        let client = self.inner.clone();
        let addr = RegisterAddress::from_hex(&addr)
            .map_err(|e| PyValueError::new_err(format!("Failed to parse address: {e}")))?;

        let history = client.register_history(&addr);
        Ok(PyRegisterHistory::new(history))
    }

    /// Create a new register key from a SecretKey and a name.
    ///
    /// This derives a new `SecretKey` from the owner's `SecretKey` using the name.
    /// Note that you will need to keep track of the names you used to create the register key.
    #[staticmethod]
    fn register_key_from_name(owner: PySecretKey, name: &str) -> PyResult<PySecretKey> {
        let key = Client::register_key_from_name(&owner.inner, name);
        Ok(PySecretKey { inner: key })
    }

    /// Create a new RegisterValue from bytes, make sure the bytes are not longer than `REGISTER_VALUE_SIZE`
    #[staticmethod]
    fn register_value_from_bytes(bytes: &[u8]) -> PyResult<[u8; 32]> {
        let value = Client::register_value_from_bytes(bytes)
            .map_err(|e| PyValueError::new_err(format!("`bytes` has invalid length: {e}")))?;
        Ok(value)
    }

    /// Create a new register with an initial value.
    ///
    /// Note that two payments are required, one for the underlying `GraphEntry` and one for the `Pointer`.
    fn register_create<'a>(
        &self,
        py: Python<'a>,
        owner: PySecretKey,
        value: [u8; 32],
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .register_create(&owner.inner, value, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to create register: {e}")))?;

            Ok((cost.to_string(), addr.to_hex()))
        })
    }

    /// Update the value of a register.
    ///
    /// The register needs to be created first with `register_create`.
    fn register_update<'a>(
        &self,
        py: Python<'a>,
        owner: PySecretKey,
        value: [u8; 32],
        payment: PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client
                .register_update(&owner.inner, value, payment.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to update register: {e}")))?;

            Ok(cost.to_string())
        })
    }

    /// Get the current value of the register
    fn register_get<'a>(&self, py: Python<'a>, addr: String) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let addr = RegisterAddress::from_hex(&addr)
            .map_err(|e| PyValueError::new_err(format!("Failed to parse address: {e}")))?;

        future_into_py(py, async move {
            let data = client
                .register_get(&addr)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get register: {e}")))?;

            Ok(data)
        })
    }

    /// Get the current value of the register
    fn register_cost<'a>(&self, py: Python<'a>, owner: PyPublicKey) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let cost = client.register_cost(&owner.inner).await.map_err(|e| {
                PyRuntimeError::new_err(format!("Failed to get register cost: {e}"))
            })?;

            Ok(cost.to_string())
        })
    }

    /// Retrieves and returns a decrypted vault if one exists.
    ///
    /// Returns the content type of the bytes in the vault.
    fn fetch_and_decrypt_vault<'a>(
        &self,
        py: Python<'a>,
        key: &PyVaultSecretKey,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let key = key.inner.clone();

        future_into_py(py, async move {
            match client.vault_get(&key).await {
                Ok((data, content_type)) => Ok((data.to_vec(), content_type)),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to fetch vault: {e}"
                ))),
            }
        })
    }

    /// Get the user data from the vault
    fn vault_get_user_data<'a>(
        &self,
        py: Python<'a>,
        key: &PyVaultSecretKey,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let key = key.inner.clone();

        future_into_py(py, async move {
            match client.vault_get_user_data(&key).await {
                Ok(user_data) => Ok(PyUserData { inner: user_data }),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to get user data from vault: {e}"
                ))),
            }
        })
    }

    /// Put the user data to the vault.
    ///
    /// Returns the total cost of the put operation.
    fn vault_put_user_data<'a>(
        &self,
        py: Python<'a>,
        key: &PyVaultSecretKey,
        payment: &PyPaymentOption,
        user_data: &PyUserData,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let key = key.inner.clone();
        let payment = payment.inner.clone();
        let user_data = user_data.inner.clone();

        future_into_py(py, async move {
            match client.vault_put_user_data(&key, payment, user_data).await {
                Ok(cost) => Ok(cost.to_string()),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to put user data: {e}"
                ))),
            }
        })
    }

    /// @deprecated Use `vault_put` instead. This function will be removed in a future version.
    fn write_bytes_to_vault<'a>(
        &self,
        py: Python<'a>,
        data: Vec<u8>,
        payment: &PyPaymentOption,
        key: &PyVaultSecretKey,
        content_type: u64,
    ) -> PyResult<Bound<'a, PyAny>> {
        self.vault_put(py, data, payment, key, content_type)
    }

    /// @deprecated Use `vault_get_user_data` instead. This function will be removed in a future version.
    fn get_user_data_from_vault<'a>(
        &self,
        py: Python<'a>,
        key: &PyVaultSecretKey,
    ) -> PyResult<Bound<'a, PyAny>> {
        self.vault_get_user_data(py, key)
    }

    /// @deprecated Use `vault_put_user_data` instead. This function will be removed in a future version.
    fn put_user_data_to_vault<'a>(
        &self,
        py: Python<'a>,
        key: &PyVaultSecretKey,
        payment: &PyPaymentOption,
        user_data: &PyUserData,
    ) -> PyResult<Bound<'a, PyAny>> {
        self.vault_put_user_data(py, key, payment, user_data)
    }

    /// Get a pointer from the network
    fn pointer_get<'a>(
        &self,
        py: Python<'a>,
        addr: PyPointerAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            match client.pointer_get(&addr.inner).await {
                Ok(pointer) => Ok(PyPointer { inner: pointer }),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to get pointer: {e}"
                ))),
            }
        })
    }

    /// Check if a pointer exists on the network
    fn pointer_check_existance<'a>(
        &self,
        py: Python<'a>,
        addr: PyPointerAddress,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let exists = client
                .pointer_check_existence(&addr.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to get pointer: {e}")))?;

            Ok(exists)
        })
    }

    /// Manually store a pointer on the network
    fn pointer_put<'a>(
        &self,
        py: Python<'a>,
        pointer: &PyPointer,
        payment_option: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let pointer = pointer.inner.clone();
        let payment = payment_option.inner.clone();

        future_into_py(py, async move {
            let (_cost, addr) = client
                .pointer_put(pointer, payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to put pointer: {e}")))?;

            Ok(PyPointerAddress { inner: addr })
        })
    }

    /// Create a new pointer on the network.
    ///
    /// Make sure that the owner key is not already used for another pointer as each key is associated with one pointer
    fn pointer_create<'a>(
        &self,
        py: Python<'a>,
        owner: PySecretKey,
        target: PyPointerTarget,
        payment_option: &PyPaymentOption,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let payment = payment_option.inner.clone();

        future_into_py(py, async move {
            let (cost, addr) = client
                .pointer_create(&owner.inner, target.inner, payment)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to create pointer: {e}")))?;

            Ok((cost.to_string(), PyPointerAddress { inner: addr }))
        })
    }

    /// Update an existing pointer to point to a new target on the network.
    ///
    /// The pointer needs to be created first with `pointer_put`.
    /// This operation is free as the pointer was already paid for at creation.
    /// Only the latest version of the pointer is kept on the Network, previous versions will be overwritten and unrecoverable.
    fn pointer_update<'a>(
        &self,
        py: Python<'a>,
        owner: PySecretKey,
        target: PyPointerTarget,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            client
                .pointer_update(&owner.inner, target.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to update pointer: {e}")))?;

            Ok(())
        })
    }

    /// Update an existing pointer from a specific pointer to point to a new target on the network.
    ///
    /// This will increment the counter of the pointer and update the target.
    /// This function is used internally by `pointer_update` after the pointer has been retrieved from the network.
    /// To skip the retrieval step if you already have the pointer, use this function directly.
    /// This function will return the new pointer after it has been updated.
    fn pointer_update_from<'a>(
        &self,
        py: Python<'a>,
        current: PyPointer,
        owner: PySecretKey,
        target: PyPointerTarget,
    ) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();

        future_into_py(py, async move {
            let new_pointer = client
                .pointer_update_from(&current.inner, &owner.inner, target.inner)
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("Failed to update pointer: {e}")))?;

            Ok(PyPointer { inner: new_pointer })
        })
    }

    /// Calculate the cost of storing a pointer
    fn pointer_cost<'a>(&self, py: Python<'a>, key: &PyPublicKey) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        let key = key.inner;

        future_into_py(py, async move {
            match client.pointer_cost(&key).await {
                Ok(cost) => Ok(cost.to_string()),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to get pointer cost: {e}"
                ))),
            }
        })
    }

    /// Verify a pointer
    #[staticmethod]
    fn pointer_verify(pointer: &PyPointer) -> PyResult<()> {
        Client::pointer_verify(&pointer.inner)
            .map_err(|e| PyRuntimeError::new_err(format!("Failed to verify pointer: {e}")))
    }

    fn get_raw_quotes<'a>(
        &self,
        py: Python<'a>,
        data_type: PyDataTypes,
        content_addrs: Vec<(PyXorName, usize)>,
    ) -> PyResult<Bound<'a, PyAny>> {
        let data_type: DataTypes = data_type.into();
        let client = self.inner.clone();
        let content_addrs_iter = content_addrs
            .into_iter()
            .map(|(xor_name, size)| (xor_name.inner, size));

        future_into_py(py, async move {
            let results = client.get_raw_quotes(data_type, content_addrs_iter).await;

            let py_results: Vec<_> = results
                .into_iter()
                .map(|result| match result {
                    Ok((xor_name, quotes)) => {
                        let py_xor_name = PyXorName { inner: xor_name };

                        let py_quotes: Vec<_> = quotes
                            .into_iter()
                            .map(|(peer_id, addresses, quote)| {
                                let peer_id_str = peer_id.to_string();

                                let addresses_str = addresses
                                    .0
                                    .iter()
                                    .map(|addr| addr.to_string())
                                    .collect::<Vec<_>>()
                                    .join(",");

                                let py_payment_quote = PyPaymentQuote { inner: quote };
                                (peer_id_str, addresses_str, py_payment_quote)
                            })
                            .collect();

                        (py_xor_name, py_quotes)
                    }
                    Err(err) => {
                        error!("Error in get_raw_quotes: {}", err);

                        let empty_xor = PyXorName {
                            inner: XorName::default(),
                        };
                        let empty_quotes: Vec<(String, String, PyPaymentQuote)> = Vec::new();

                        (empty_xor, empty_quotes)
                    }
                })
                .collect();

            Ok(py_results)
        })
    }

    fn get_store_quotes<'a>(
        &self,
        py: Python<'a>,
        data_type: PyDataTypes,
        content_addrs: Vec<(PyXorName, usize)>,
    ) -> PyResult<Bound<'a, PyAny>> {
        let data_type: DataTypes = data_type.into();

        let client = self.inner.clone();

        let content_addrs_iter = content_addrs
            .into_iter()
            .map(|(xor_name, size)| (xor_name.inner, size));

        future_into_py(py, async move {
            match client.get_store_quotes(data_type, content_addrs_iter).await {
                Ok(quotes) => {
                    let py_store_quote = PyStoreQuote { inner: quotes };
                    Ok(py_store_quote)
                }
                Err(err) => Err(PyErr::new::<PyValueError, _>(format!("{err:?}"))),
            }
        })
    }
}

#[pyclass(name = "ClientEvent")]
#[derive(Debug, Clone)]
pub struct PyClientEvent {
    inner: ClientEvent,
}

#[pymethods]
impl PyClientEvent {
    #[getter]
    fn event_type(&self) -> &'static str {
        match self.inner {
            ClientEvent::UploadComplete(_) => "UploadComplete",
        }
    }

    #[getter]
    fn upload_summary(&self) -> Option<PyUploadSummary> {
        match &self.inner {
            ClientEvent::UploadComplete(summary) => Some(PyUploadSummary {
                inner: summary.clone(),
            }),
        }
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(format!("{:?}", self.inner))
    }
}

#[pyclass(name = "ClientEventReceiver")]
pub struct PyClientEventReceiver {
    inner: Arc<futures::lock::Mutex<mpsc::Receiver<ClientEvent>>>,
}

#[pymethods]
impl PyClientEventReceiver {
    /// Receive the next client event, returning None if the channel is closed
    fn recv<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        let inner = Arc::clone(&self.inner);

        future_into_py(py, async move {
            let mut receiver = inner.lock().await;

            let result = receiver
                .recv()
                .await
                .map(|event| PyClientEvent { inner: event });

            Ok(result)
        })
    }
}

#[pyclass(name = "ClientOperatingStrategy")]
#[derive(Debug, Clone)]
pub struct PyClientOperatingStrategy {
    inner: ClientOperatingStrategy,
}

#[pymethods]
impl PyClientOperatingStrategy {
    /// Create a new ClientOperatingStrategy with default values
    #[new]
    fn new() -> Self {
        Self {
            inner: ClientOperatingStrategy::new(),
        }
    }

    /// Get the strategy for chunk operations
    #[getter]
    fn get_chunks(&self) -> PyStrategy {
        PyStrategy {
            inner: self.inner.chunks.clone(),
        }
    }

    /// Get the strategy for graph entry operations
    #[getter]
    fn get_graph_entry(&self) -> PyStrategy {
        PyStrategy {
            inner: self.inner.graph_entry.clone(),
        }
    }

    /// Get the strategy for pointer operations
    #[getter]
    fn get_pointer(&self) -> PyStrategy {
        PyStrategy {
            inner: self.inner.pointer.clone(),
        }
    }

    /// Get the strategy for scratchpad operations
    #[getter]
    fn get_scratchpad(&self) -> PyStrategy {
        PyStrategy {
            inner: self.inner.scratchpad.clone(),
        }
    }

    /// Return a string representation of the strategy
    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    /// Get a representation for debugging
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

/// Address of a Pointer, is derived from the owner's unique public key.
#[pyclass(name = "PointerAddress", eq, ord)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyPointerAddress {
    inner: PointerAddress,
}

#[pymethods]
impl PyPointerAddress {
    /// Construct a new PointerAddress given an owner.
    #[new]
    fn new(public_key: PyPublicKey) -> PyResult<Self> {
        Ok(Self {
            inner: PointerAddress::new(public_key.inner),
        })
    }

    /// Return the owner public key.
    pub fn owner(&self) -> PyPublicKey {
        PyPublicKey {
            inner: *self.inner.owner(),
        }
    }

    /// Returns the hex string representation of the pointer address.
    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a Pointer address from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: PointerAddress::from_hex(hex)
                .map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("PointerAddress('{}')", self.hex()))
    }
}

/// Pointer, a mutable address pointing to other data on the Network.
/// It is stored at the owner's public key and can only be updated by the owner.
#[pyclass(name = "Pointer")]
#[derive(Debug, Clone)]
pub struct PyPointer {
    inner: Pointer,
}

#[pymethods]
impl PyPointer {
    /// Create a new pointer, signing it with the provided secret key.
    /// This pointer would be stored on the network at the provided key's public key.
    /// There can only be one pointer at a time at the same address (one per key).
    #[new]
    pub fn new(key: &PySecretKey, counter: u64, target: &PyPointerTarget) -> PyResult<Self> {
        Ok(Self {
            inner: Pointer::new(&key.inner, counter, target.inner.clone()),
        })
    }

    /// Returns the network address where this pointer is stored.
    pub fn address(&self) -> PyPointerAddress {
        PyPointerAddress {
            inner: self.inner.address(),
        }
    }

    /// Returns the target that this pointer points to.
    #[getter]
    fn target(&self) -> PyPointerTarget {
        PyPointerTarget {
            inner: self.inner.target().clone(),
        }
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(format!("Pointer('{}')", self.inner.address().to_hex()))
    }
}

/// The target that a pointer points to on the network.
#[pyclass(name = "PointerTarget")]
#[derive(Debug, Clone)]
pub struct PyPointerTarget {
    inner: PointerTarget,
}

#[pymethods]
impl PyPointerTarget {
    /// Initialize a pointer targeting a chunk.
    #[staticmethod]
    fn new_chunk(addr: PyChunkAddress) -> PyResult<Self> {
        Ok(Self {
            inner: PointerTarget::ChunkAddress(addr.inner),
        })
    }

    /// Initialize a pointer targeting a graph entry.
    #[staticmethod]
    fn new_graph_entry(addr: PyGraphEntryAddress) -> PyResult<Self> {
        Ok(Self {
            inner: PointerTarget::GraphEntryAddress(addr.inner),
        })
    }

    /// Initialize a pointer targeting another pointer.
    #[staticmethod]
    fn new_pointer(addr: PyPointerAddress) -> PyResult<Self> {
        Ok(Self {
            inner: PointerTarget::PointerAddress(addr.inner),
        })
    }

    /// Initialize a pointer targeting a scratchpad.
    #[staticmethod]
    fn new_scratchpad(addr: PyScratchpadAddress) -> PyResult<Self> {
        Ok(Self {
            inner: PointerTarget::ScratchpadAddress(addr.inner),
        })
    }

    #[getter]
    fn target(&self) -> PyPointerTarget {
        PyPointerTarget {
            inner: PointerTarget::ChunkAddress(ChunkAddress::new(self.inner.xorname())),
        }
    }

    /// Returns the hex string representation of the target
    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(format!("PointerTarget('{}')", self.hex()))
    }
}

#[pyclass(name = "Chunk", eq, ord)]
#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Debug)]
pub struct PyChunk {
    inner: Chunk,
}

#[pymethods]
impl PyChunk {
    /// Creates a new instance of `Chunk`.
    #[new]
    fn new(value: Vec<u8>) -> Self {
        Self {
            inner: Chunk::new(Bytes::from(value)),
        }
    }

    /// Returns the value of the chunk.
    #[getter]
    fn value(&self) -> Vec<u8> {
        self.inner.value().to_vec()
    }

    /// Returns the address of the chunk.
    #[getter]
    fn address(&self) -> PyChunkAddress {
        PyChunkAddress {
            inner: *self.inner.address(),
        }
    }

    /// Returns the network address.
    fn network_address(&self) -> String {
        self.inner.network_address().to_string()
    }

    /// Returns the name of the chunk.
    fn name(&self) -> PyXorName {
        PyXorName {
            inner: *self.inner.name(),
        }
    }

    /// Returns size of this chunk after serialisation.
    fn size(&self) -> usize {
        self.inner.size()
    }

    /// Returns true if the chunk is too big
    fn is_too_big(&self) -> bool {
        self.inner.is_too_big()
    }

    /// The maximum size of an unencrypted/raw chunk (4MB).
    #[classattr]
    fn max_raw_size() -> usize {
        Chunk::MAX_RAW_SIZE
    }

    /// The maximum size of an encrypted chunk (4MB + 32 bytes).
    #[classattr]
    fn max_size() -> usize {
        Chunk::MAX_SIZE
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(format!("Chunk(size={})", self.inner.size()))
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!(
            "Chunk(address='{}', size={})",
            self.inner.address().to_hex(),
            self.inner.size()
        ))
    }
}

/// An address of a chunk of data on the network. Used to locate and retrieve data chunks.
#[pyclass(name = "ChunkAddress", eq, ord)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyChunkAddress {
    inner: ChunkAddress,
}

#[pymethods]
impl PyChunkAddress {
    /// Creates a new chunk address from a hex string.
    #[new]
    fn new(addr: PyXorName) -> PyResult<Self> {
        Ok(Self {
            inner: ChunkAddress::new(addr.inner),
        })
    }

    /// Returns the XorName
    pub fn xorname(&self) -> PyXorName {
        PyXorName {
            inner: *self.inner.xorname(),
        }
    }

    /// Generate a chunk address for the given content (for content-addressable-storage).
    #[staticmethod]
    fn from_content(data: Vec<u8>) -> PyResult<Self> {
        Ok(Self {
            inner: ChunkAddress::new(XorName::from_content(&data[..])),
        })
    }

    /// Generate a random chunk address.
    #[staticmethod]
    fn random() -> PyResult<Self> {
        Ok(Self {
            inner: ChunkAddress::new(XorName::random(&mut rand::thread_rng())),
        })
    }

    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a ChunkAddress from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: ChunkAddress::from_hex(hex).map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("ChunkAddress('{}')", self.hex()))
    }
}

/// Address of a GraphEntry, is derived from the owner's unique public key.
#[pyclass(name = "GraphEntryAddress", eq, ord)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyGraphEntryAddress {
    inner: GraphEntryAddress,
}

#[pymethods]
impl PyGraphEntryAddress {
    /// Create graph entry address
    #[staticmethod]
    fn new(public_key: PyPublicKey) -> PyResult<Self> {
        Ok(Self {
            inner: GraphEntryAddress::new(public_key.inner),
        })
    }

    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a graph entry address from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: GraphEntryAddress::from_hex(hex)
                .map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("GraphEntryAddress('{}')", self.hex()))
    }
}

/// Configuration for the bootstrap cache
#[pyclass(name = "BootstrapCacheConfig")]
#[derive(Debug, Clone, Default)]
pub struct PyBootstrapCacheConfig {
    pub(crate) inner: BootstrapConfig,
}

#[pymethods]
impl PyBootstrapCacheConfig {
    /// Creates a new BootstrapCacheConfig with default settings.
    #[new]
    fn new(local: bool) -> Self {
        Self {
            inner: BootstrapConfig::new(local),
        }
    }

    /// Update the config with a custom cache directory.
    fn with_cache_dir(&self, path: PathBuf) -> Self {
        Self {
            inner: self.inner.clone().with_cache_dir(path),
        }
    }

    /// Sets the maximum number of cached peers.
    fn with_max_cached_peers(&self, max_peers: usize) -> Self {
        Self {
            inner: self.inner.clone().with_max_cached_peers(max_peers),
        }
    }

    /// Sets the maximum number of addresses for a single peer.
    fn with_max_addrs_per_cached_peer(&self, max_addrs: usize) -> Self {
        Self {
            inner: self.inner.clone().with_max_addrs_per_cached_peer(max_addrs),
        }
    }

    /// Sets the flag to disable writing to the cache file.
    fn with_disable_cache_writing(&self, disable: bool) -> Self {
        Self {
            inner: self.inner.clone().with_disable_cache_writing(disable),
        }
    }

    /// Sets the flag to disable reading from the cache file.
    fn with_disable_cache_reading(&self, disable: bool) -> Self {
        Self {
            inner: self.inner.clone().with_disable_cache_reading(disable),
        }
    }

    /// Sets whether backwards-compatible cache writes are enabled.
    fn with_backwards_compatible_writes(&self, enable: bool) -> Self {
        Self {
            inner: self.inner.clone().with_backwards_compatible_writes(enable),
        }
    }

    /// Sets the minimum cache save duration in seconds.
    fn with_min_cache_save_duration(&self, seconds: u64) -> Self {
        Self {
            inner: self
                .inner
                .clone()
                .with_min_cache_save_duration(Duration::from_secs(seconds)),
        }
    }

    /// Sets the maximum cache save duration in seconds.
    fn with_max_cache_save_duration(&self, seconds: u64) -> Self {
        Self {
            inner: self
                .inner
                .clone()
                .with_max_cache_save_duration(Duration::from_secs(seconds)),
        }
    }

    /// Sets the cache save scaling factor.
    fn with_cache_save_scaling_factor(&self, factor: u32) -> Self {
        Self {
            inner: self.inner.clone().with_cache_save_scaling_factor(factor),
        }
    }

    /// Sets the list of network contact URLs.
    fn with_network_contacts_url(&self, urls: Vec<String>) -> Self {
        Self {
            inner: self.inner.clone().with_network_contacts_url(urls),
        }
    }

    /// Sets whether this config represents the first node in the network.
    fn with_first(&self, first: bool) -> Self {
        Self {
            inner: self.inner.clone().with_first(first),
        }
    }

    /// Sets the initial peers that should be used for bootstrapping.
    fn with_initial_peers(&self, peers: Vec<String>) -> PyResult<Self> {
        let parsed = peers
            .into_iter()
            .map(|addr| addr.parse::<Multiaddr>())
            .collect::<Result<Vec<_>, _>>()
            .map_err(|err| PyValueError::new_err(format!("Invalid multiaddr: {err}")))?;
        Ok(Self {
            inner: self.inner.clone().with_initial_peers(parsed),
        })
    }

    /// Get the maximum number of cached peers.
    #[getter]
    fn max_cached_peers(&self) -> usize {
        self.inner.max_cached_peers
    }

    /// Get the maximum number of addresses per cached peer.
    #[getter]
    fn max_addrs_per_cached_peer(&self) -> usize {
        self.inner.max_addrs_per_cached_peer
    }

    /// Get the cache directory.
    #[getter]
    fn cache_dir(&self) -> PathBuf {
        self.inner.cache_dir.clone()
    }

    /// Get whether cache writing is disabled.
    #[getter]
    fn disable_cache_writing(&self) -> bool {
        self.inner.disable_cache_writing
    }

    /// Get whether cache reading is disabled.
    #[getter]
    fn disable_cache_reading(&self) -> bool {
        self.inner.disable_cache_reading
    }

    /// Get whether backwards-compatible cache writes are enabled.
    #[getter]
    fn backwards_compatible_writes(&self) -> bool {
        self.inner.backwards_compatible_writes
    }

    /// Get the minimum cache save duration in seconds.
    #[getter]
    fn min_cache_save_duration(&self) -> u64 {
        self.inner.min_cache_save_duration.as_secs()
    }

    /// Get the maximum cache save duration in seconds.
    #[getter]
    fn max_cache_save_duration(&self) -> u64 {
        self.inner.max_cache_save_duration.as_secs()
    }

    /// Get the cache save scaling factor.
    #[getter]
    fn cache_save_scaling_factor(&self) -> u32 {
        self.inner.cache_save_scaling_factor
    }

    /// Get the configured network contact URLs.
    #[getter]
    fn network_contacts_url(&self) -> Vec<String> {
        self.inner.network_contacts_url.clone()
    }

    /// Get whether this config is marked as local.
    #[getter]
    fn local(&self) -> bool {
        self.inner.local
    }

    /// Return a string representation.
    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    /// Return a debug representation.
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

#[pyclass(name = "InitialPeersConfig")]
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PyInitialPeersConfig {
    inner: InitialPeersConfig,
}

#[pymethods]
impl PyInitialPeersConfig {
    /// Create a new InitialPeersConfig with default values
    #[new]
    fn new() -> Self {
        Self {
            inner: InitialPeersConfig::default(),
        }
    }

    #[getter]
    fn get_first(&self) -> bool {
        self.inner.first
    }

    #[setter]
    fn set_first(&mut self, value: bool) {
        self.inner.first = value;
    }

    /// Addresses to use for bootstrap, in multiaddr format
    #[getter]
    fn get_addrs(&self) -> Vec<String> {
        self.inner
            .addrs
            .iter()
            .map(|addr| addr.to_string())
            .collect()
    }

    #[setter]
    fn set_addrs(&mut self, addrs: Vec<String>) -> PyResult<()> {
        self.inner.addrs = addrs
            .iter()
            .filter_map(|addr| Multiaddr::from_str(addr).ok())
            .collect();
        Ok(())
    }

    /// URLs to fetch network contacts from
    #[getter]
    fn get_network_contacts_url(&self) -> Vec<String> {
        self.inner.network_contacts_url.clone()
    }

    #[setter]
    fn set_network_contacts_url(&mut self, urls: Vec<String>) {
        self.inner.network_contacts_url = urls;
    }

    /// Whether this is a local network
    #[getter]
    fn get_local(&self) -> bool {
        self.inner.local
    }

    #[setter]
    fn set_local(&mut self, value: bool) {
        self.inner.local = value;
    }

    /// Whether to ignore the bootstrap cache
    #[getter]
    fn get_ignore_cache(&self) -> bool {
        self.inner.ignore_cache
    }

    #[setter]
    fn set_ignore_cache(&mut self, value: bool) {
        self.inner.ignore_cache = value;
    }

    /// Directory for bootstrap cache files
    #[getter]
    fn get_bootstrap_cache_dir(&self) -> Option<PathBuf> {
        self.inner.bootstrap_cache_dir.clone()
    }

    #[setter]
    fn set_bootstrap_cache_dir(&mut self, dir: Option<PathBuf>) {
        self.inner.bootstrap_cache_dir = dir;
    }

    /// Read bootstrap addresses from the ANT_PEERS environment variable
    #[staticmethod]
    fn read_bootstrap_addr_from_env() -> Vec<String> {
        Bootstrap::fetch_from_env()
            .into_iter()
            .map(|addr| addr.to_string())
            .collect()
    }

    /// Return a string representation
    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    /// Return a representation for debugging
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

#[pyclass(name = "MainPubkey")]
#[derive(Copy, PartialEq, Eq, Ord, PartialOrd, Clone, Serialize, Deserialize, Hash)]
pub struct PyMainPubkey {
    inner: MainPubkey,
}

#[pymethods]
impl PyMainPubkey {
    /// Create a new MainPubkey from a PublicKey
    #[new]
    fn new(public_key: PyPublicKey) -> Self {
        Self {
            inner: MainPubkey::new(public_key.inner),
        }
    }

    /// Verify that the signature is valid for the message
    fn verify(&self, sig: &PySignature, msg: &[u8]) -> bool {
        self.inner.verify(&sig.inner, msg)
    }

    /// Generate a new DerivedPubkey from provided DerivationIndex
    fn derive_key(&self, index: &PyDerivationIndex) -> PyDerivedPubkey {
        PyDerivedPubkey {
            inner: self.inner.derive_key(&index.inner),
        }
    }

    /// Return the inner pubkey's bytes representation
    fn as_bytes(&self) -> [u8; PK_SIZE] {
        self.inner.to_bytes()
    }

    /// Return a hex representation of the MainPubkey
    fn as_hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a new MainPubkey from a hex string
    #[staticmethod]
    fn from_hex(hex_str: &str) -> PyResult<Self> {
        MainPubkey::from_hex(hex_str)
            .map(|inner| Self { inner })
            .map_err(|e| PyValueError::new_err(format!("Failed to parse hex: {e}")))
    }

    /// Return string representation (hex format)
    fn __str__(&self) -> String {
        self.inner.to_hex()
    }

    /// Return representation for debugging
    fn __repr__(&self) -> String {
        format!("MainPubkey('{}')", self.inner.to_hex())
    }
}

#[pyclass(name = "MainSecretKey")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyMainSecretKey {
    inner: MainSecretKey,
}

#[pymethods]
impl PyMainSecretKey {
    /// Create a new MainSecretKey from a SecretKey
    #[new]
    fn new(secret_key: PySecretKey) -> Self {
        Self {
            inner: MainSecretKey::new(secret_key.inner),
        }
    }

    /// Return the matching MainPubkey
    fn public_key(&self) -> PyMainPubkey {
        PyMainPubkey {
            inner: self.inner.public_key(),
        }
    }

    /// Signs the given message
    fn sign(&self, msg: &[u8]) -> PySignature {
        PySignature {
            inner: self.inner.sign(msg),
        }
    }

    /// Derive a DerivedSecretKey from a DerivationIndex
    fn derive_key(&self, index: &PyDerivationIndex) -> PyDerivedSecretKey {
        PyDerivedSecretKey {
            inner: self.inner.derive_key(&index.inner),
        }
    }

    /// Return the inner secret key's bytes representation
    fn to_bytes(&self) -> Vec<u8> {
        self.inner.to_bytes()
    }

    /// Generate a new random MainSecretKey
    #[staticmethod]
    fn random() -> Self {
        Self {
            inner: MainSecretKey::random(),
        }
    }

    /// Generate a new random DerivedSecretKey from the MainSecretKey
    fn random_derived_key(&self) -> PyDerivedSecretKey {
        PyDerivedSecretKey {
            inner: self.inner.random_derived_key(&mut rand::thread_rng()),
        }
    }

    /// Return string representation for debugging
    fn __repr__(&self) -> String {
        format!("MainSecretKey(public_key={})", self.public_key().as_hex())
    }
}
/// Address of a Scratchpad, is derived from the owner's unique public key.
#[pyclass(name = "ScratchpadAddress", eq, ord)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyScratchpadAddress {
    inner: ScratchpadAddress,
}

#[pymethods]
impl PyScratchpadAddress {
    /// Construct a new ScratchpadAddress given an owner.
    #[new]
    fn new(public_key: PyPublicKey) -> PyResult<Self> {
        Ok(Self {
            inner: ScratchpadAddress::new(public_key.inner),
        })
    }

    /// Return the owner public key.
    pub fn owner(&self) -> PyPublicKey {
        PyPublicKey {
            inner: *self.inner.owner(),
        }
    }

    /// Returns the hex string representation of the scratchpad address.
    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a scratchpad address from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: ScratchpadAddress::from_hex(hex)
                .map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("ScratchpadAddress('{}')", self.hex()))
    }
}

/// Address of Data on the Network.
#[pyclass(name = "DataAddress", eq, ord)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyDataAddress {
    inner: DataAddress,
}

#[pymethods]
impl PyDataAddress {
    /// Construct a new DataAddress
    #[new]
    fn new(xorname: PyXorName) -> PyResult<Self> {
        Ok(Self {
            inner: DataAddress::new(xorname.inner),
        })
    }

    /// Returns the hex string representation of the data address.
    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a Data address from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: DataAddress::from_hex(hex).map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("DataAddress('{}')", self.hex()))
    }
}

/// Address of Data on the Network.
#[pyclass(name = "ArchiveAddress", eq, ord)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyArchiveAddress {
    inner: ArchiveAddress,
}

#[pymethods]
impl PyArchiveAddress {
    /// Construct a new ArchiveAddress, the address of a public archive on the network.
    #[new]
    fn new(xorname: PyXorName) -> PyResult<Self> {
        Ok(Self {
            inner: ArchiveAddress::new(xorname.inner),
        })
    }

    /// Returns the hex string representation of this archive address.
    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create an ArchiveAddress from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: ArchiveAddress::from_hex(hex)
                .map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("ArchiveAddress('{}')", self.hex()))
    }
}

/// Address of Data on the Network.
#[pyclass(name = "PrivateArchiveDataMap", eq, ord)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct PyPrivateArchiveDataMap {
    inner: PrivateArchiveDataMap,
}

#[pymethods]
impl PyPrivateArchiveDataMap {
    /// Returns the hex string representation of this private archive datamap.
    #[getter]
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a PrivateArchiveDataMap from a hex string.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        Ok(Self {
            inner: PrivateArchiveDataMap::from_hex(hex)
                .map_err(|e| PyValueError::new_err(e.to_string()))?,
        })
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(self.hex())
    }

    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("PrivateArchiveDataMap('{}')", self.hex()))
    }
}

/// A wallet for interacting with the network's payment system.
/// Handles token transfers, balance checks, and payments for network operations.
#[pyclass(name = "Wallet")]
#[derive(Clone)]
pub struct PyWallet {
    pub(crate) inner: Wallet,
}

#[pymethods]
impl PyWallet {
    /// Creates a new wallet from a private key string.
    /// The wallet will be configured to use the ArbitrumOne network.
    #[new]
    fn new(private_key: String) -> PyResult<Self> {
        let wallet = Wallet::new_from_private_key(
            EVMNetwork::ArbitrumOne, // TODO: Make this configurable
            &private_key,
        )
        .map_err(|e| PyValueError::new_err(format!("`private_key` invalid: {e}")))?;

        Ok(Self { inner: wallet })
    }

    /// Convenience function that creates a new Wallet with a random EthereumWallet.
    #[staticmethod]
    fn new_with_random_wallet(network: PyEVMNetwork) -> Self {
        Self {
            inner: Wallet::new_with_random_wallet(network.inner),
        }
    }

    /// Creates a new wallet from a private key string with a specified network.
    #[staticmethod]
    fn new_from_private_key(network: PyEVMNetwork, private_key: &str) -> PyResult<Self> {
        let inner = Wallet::new_from_private_key(network.inner, private_key)
            .map_err(|e| PyValueError::new_err(format!("`private_key` invalid: {e}")))?;

        Ok(Self { inner })
    }

    /// Returns a string representation of the wallet's address.
    fn address(&self) -> String {
        self.inner.address().to_string()
    }

    /// Returns the `Network` of this wallet.
    fn network(&self) -> PyEVMNetwork {
        PyEVMNetwork {
            inner: self.inner.network().clone(),
        }
    }

    /// Returns the raw balance of payment tokens in the wallet.
    fn balance<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        future_into_py(py, async move {
            match client.balance_of_tokens().await {
                Ok(balance) => Ok(balance.to_string()),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to get balance: {e}"
                ))),
            }
        })
    }

    /// Returns the current balance of gas tokens in the wallet.
    fn balance_of_gas<'a>(&self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        let client = self.inner.clone();
        future_into_py(py, async move {
            match client.balance_of_gas_tokens().await {
                Ok(balance) => Ok(balance.to_string()),
                Err(e) => Err(PyRuntimeError::new_err(format!(
                    "Failed to get balance: {e}"
                ))),
            }
        })
    }

    /// Returns a random private key string.
    #[staticmethod]
    pub fn random_private_key() -> String {
        Wallet::random_private_key()
    }

    /// Sets the transaction configuration for the wallet.
    fn set_transaction_config(&mut self, config: PyTransactionConfig) -> PyResult<()> {
        self.inner.set_transaction_config(config.into());
        Ok(())
    }
}

#[pyclass(name = "TransactionConfig")]
#[derive(Clone, Debug)]
pub struct PyTransactionConfig {
    pub max_fee_per_gas: PyMaxFeePerGas,
}

#[pymethods]
impl PyTransactionConfig {
    /// Create a TransactionConfig with a specific MaxFeePerGas setting
    #[new]
    fn new(max_fee_per_gas: PyMaxFeePerGas) -> Self {
        Self { max_fee_per_gas }
    }

    /// Get the current MaxFeePerGas setting
    #[getter]
    fn max_fee_per_gas(&self) -> PyMaxFeePerGas {
        self.max_fee_per_gas.clone()
    }

    fn __str__(&self) -> String {
        format!(
            "{:?}",
            std::convert::Into::<TransactionConfig>::into(self.clone())
        )
    }
}

#[allow(clippy::from_over_into)]
impl Into<TransactionConfig> for PyTransactionConfig {
    fn into(self) -> TransactionConfig {
        let max_fee_per_gas = match self.max_fee_per_gas {
            PyMaxFeePerGas::Auto() => MaxFeePerGas::Auto,
            PyMaxFeePerGas::LimitedAuto(limit) => MaxFeePerGas::LimitedAuto(limit),
            PyMaxFeePerGas::Unlimited() => MaxFeePerGas::Unlimited,
            PyMaxFeePerGas::Custom(limit) => MaxFeePerGas::Custom(limit),
        };

        TransactionConfig { max_fee_per_gas }
    }
}

#[pyclass(name = "MaxFeePerGas")]
#[derive(Clone, Debug)]
pub enum PyMaxFeePerGas {
    Auto(),
    LimitedAuto(u128),
    Unlimited(),
    Custom(u128),
}

#[pymethods]
impl PyMaxFeePerGas {
    /// Use the current market price for fee per gas. WARNING: This can result in unexpected high gas fees!
    #[staticmethod]
    pub fn auto() -> Self {
        Self::Auto()
    }

    /// Use the current market price for fee per gas, but with an upper limit.
    #[staticmethod]
    pub fn limited_auto(value: u128) -> Self {
        Self::LimitedAuto(value)
    }

    /// Use no max fee per gas. WARNING: This can result in unexpected high gas fees!
    #[staticmethod]
    pub fn unlimited() -> Self {
        Self::Unlimited()
    }

    /// Use a custom max fee per gas in WEI.
    #[staticmethod]
    pub fn custom(value: u128) -> Self {
        Self::Custom(value)
    }

    pub fn __str__(&self) -> String {
        match self {
            Self::Auto() => "Auto".to_string(),
            Self::LimitedAuto(val) => format!("LimitedAuto({val})"),
            Self::Unlimited() => "Unlimited".to_string(),
            Self::Custom(val) => format!("Custom({val})"),
        }
    }
}

/// Payment strategy for uploads
#[pyclass(name = "PaymentMode", eq, eq_int)]
#[derive(Clone, Copy, PartialEq)]
pub enum PyPaymentMode {
    /// Default mode: Pay 3 nodes
    Standard = 0,
    /// Alternative mode: Pay only the median priced node with 3x the quoted amount
    SingleNode = 1,
}

/// Options for making payments on the network.
#[pyclass(name = "PaymentOption")]
#[derive(Clone)]
pub struct PyPaymentOption {
    pub(crate) inner: PaymentOption,
}

#[pymethods]
impl PyPaymentOption {
    /// Creates a payment option using the provided wallet.
    #[staticmethod]
    fn wallet(wallet: &PyWallet) -> Self {
        Self {
            inner: PaymentOption::Wallet(wallet.inner.clone()),
        }
    }
}

/// A cryptographic secret key used for signing operations.
/// Can be used to derive a public key and perform cryptographic operations.
#[pyclass(name = "SecretKey")]
#[derive(Debug, Clone)]
pub struct PySecretKey {
    inner: SecretKey,
}

#[pymethods]
impl PySecretKey {
    /// Creates a new random secret key.
    #[new]
    fn new() -> PyResult<Self> {
        Ok(Self {
            inner: SecretKey::random(),
        })
    }

    /// Creates a secret key from a hex string representation.
    #[staticmethod]
    fn from_hex(hex_str: &str) -> PyResult<Self> {
        SecretKey::from_hex(hex_str)
            .map(|key| Self { inner: key })
            .map_err(|e| PyValueError::new_err(format!("Invalid hex key: {e}")))
    }

    /// Derives and returns the corresponding public key.
    fn public_key(&self) -> PyPublicKey {
        PyPublicKey {
            inner: self.inner.public_key(),
        }
    }

    /// Returns the hex string representation of the key.
    fn hex(&self) -> String {
        self.inner.to_hex()
    }
}

#[pyclass(name = "Signature")]
#[derive(Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct PySignature {
    pub(crate) inner: Signature,
}

#[pymethods]
impl PySignature {
    /// Returns `true` if the signature contains an odd number of ones.
    fn parity(&self) -> bool {
        self.inner.parity()
    }

    /// Returns the signature with the given representation, if valid.
    #[staticmethod]
    fn from_bytes(bytes: [u8; bls::SIG_SIZE]) -> PyResult<Self> {
        Signature::from_bytes(bytes)
            .map(|inner| Self { inner })
            .map_err(|e| PyValueError::new_err(format!("Invalid signature: {e}")))
    }

    /// Returns a byte array representation of the signature.
    fn to_bytes(&self) -> [u8; bls::SIG_SIZE] {
        self.inner.to_bytes()
    }

    /// String representation
    fn __str__(&self) -> String {
        hex::encode(self.inner.to_bytes())
    }

    /// Debug representation
    fn __repr__(&self) -> String {
        format!("Signature('{}')", hex::encode(self.inner.to_bytes()))
    }
}

#[pyclass(name = "StoreQuote")]
pub struct PyStoreQuote {
    inner: StoreQuote,
}

#[pymethods]
impl PyStoreQuote {
    /// Returns the total price of all quotes
    pub fn price(&self) -> String {
        self.inner.price().to_string()
    }

    /// Returns the number of quotes
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns true if there are no quotes
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Returns a list of payment details (hash, rewards_address, price)
    pub fn payments(&self) -> Vec<(String, String, String)> {
        self.inner
            .payments()
            .into_iter()
            .map(|(hash, rewards_address, price)| {
                (
                    format!("0x{}", hex::encode(hash.0)),
                    format!("0x{}", hex::encode(rewards_address.0)),
                    price.to_string(),
                )
            })
            .collect()
    }
}

#[pyclass(name = "Backoff")]
#[derive(Debug, Clone)]
pub struct PyBackoff {
    inner: Backoff,
}

#[pymethods]
impl PyBackoff {
    /// String representation
    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    /// Representation for debugging
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

// Wrapper approach for RetryStrategy
#[pyclass(name = "RetryStrategy")]
#[derive(Clone, Debug, Copy, Default)]
pub struct PyRetryStrategy {
    inner: RetryStrategy,
}

#[pymethods]
impl PyRetryStrategy {
    /// Create a new RetryStrategy with 'None' setting (1 attempt, no retries)
    #[staticmethod]
    fn none() -> Self {
        Self {
            inner: RetryStrategy::None,
        }
    }

    /// Create a new RetryStrategy with 'Quick' setting (4 attempts)
    #[staticmethod]
    fn quick() -> Self {
        Self {
            inner: RetryStrategy::Quick,
        }
    }

    /// Create a new RetryStrategy with 'Balanced' setting (6 attempts)
    #[staticmethod]
    fn balanced() -> Self {
        Self {
            inner: RetryStrategy::Balanced,
        }
    }

    /// Create a new RetryStrategy with 'Persistent' setting (10 attempts)
    #[staticmethod]
    fn persistent() -> Self {
        Self {
            inner: RetryStrategy::Persistent,
        }
    }

    /// Get the default RetryStrategy (Balanced)
    #[staticmethod]
    fn default() -> Self {
        Self {
            inner: RetryStrategy::default(),
        }
    }

    /// Get the number of retry attempts
    fn attempts(&self) -> usize {
        self.inner.attempts()
    }

    /// Get a Backoff object configured for this retry strategy
    fn backoff(&self) -> PyBackoff {
        PyBackoff {
            inner: self.inner.backoff(),
        }
    }

    /// Get a string representation of the retry strategy
    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    /// Get a representation for debugging
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

#[pyclass(name = "Quorum")]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct PyQuorum {
    inner: Quorum,
}

#[pymethods]
impl PyQuorum {
    /// Get a string representation of the quorum
    fn __str__(&self) -> String {
        match self.inner {
            Quorum::One => "Quorum::One".to_string(),
            Quorum::Majority => "Quorum::Majority".to_string(),
            Quorum::All => "Quorum::All".to_string(),
            Quorum::N(n) => format!("Quorum::N({n})"),
        }
    }

    /// Get a representation for debugging
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

#[pyclass(name = "Strategy")]
#[derive(Debug, Clone)]
pub struct PyStrategy {
    inner: Strategy,
}

#[pymethods]
impl PyStrategy {
    /// Get the quorum for put operations
    #[getter]
    fn get_put_quorum(&self) -> PyQuorum {
        PyQuorum {
            inner: self.inner.put_quorum,
        }
    }

    /// Get the retry strategy for put operations
    #[getter]
    fn get_put_retry(&self) -> PyRetryStrategy {
        PyRetryStrategy {
            inner: self.inner.put_retry,
        }
    }

    /// Get the quorum for verification operations
    #[getter]
    fn get_verification_quorum(&self) -> PyQuorum {
        PyQuorum {
            inner: self.inner.verification_quorum,
        }
    }

    /// Get the quorum for get operations
    #[getter]
    fn get_get_quorum(&self) -> PyQuorum {
        PyQuorum {
            inner: self.inner.get_quorum,
        }
    }

    /// Get the retry strategy for get operations
    #[getter]
    fn get_get_retry(&self) -> PyRetryStrategy {
        PyRetryStrategy {
            inner: self.inner.get_retry,
        }
    }

    /// Return a string representation of the strategy
    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    /// Get a representation for debugging
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

#[pyclass(name = "UploadSummary")]
#[derive(Debug, Clone)]
pub struct PyUploadSummary {
    inner: UploadSummary,
}

#[pymethods]
impl PyUploadSummary {
    #[getter]
    fn records_paid(&self) -> usize {
        self.inner.records_paid
    }

    #[getter]
    fn records_already_paid(&self) -> usize {
        self.inner.records_already_paid
    }

    #[getter]
    fn tokens_spent(&self) -> String {
        self.inner.tokens_spent.to_string()
    }

    fn __str__(&self) -> PyResult<String> {
        Ok(format!(
            "UploadSummary {{ records_paid: {}, records_already_paid: {}, tokens_spent: {} }}",
            self.inner.records_paid, self.inner.records_already_paid, self.inner.tokens_spent
        ))
    }
}

/// A cryptographic public key derived from a secret key.
#[pyclass(name = "PublicKey")]
#[derive(Debug, Clone)]
pub struct PyPublicKey {
    inner: PublicKey,
}

#[pymethods]
impl PyPublicKey {
    /// Creates a random public key by generating a random secret key.
    #[staticmethod]
    fn random() -> PyResult<Self> {
        let secret = SecretKey::random();
        Ok(Self {
            inner: secret.public_key(),
        })
    }

    /// Creates a public key from a hex string representation.
    #[staticmethod]
    fn from_hex(hex_str: &str) -> PyResult<Self> {
        PublicKey::from_hex(hex_str)
            .map(|key| Self { inner: key })
            .map_err(|e| PyValueError::new_err(format!("Invalid hex key: {e}")))
    }

    /// Returns the hex string representation of the public key.
    fn hex(&self) -> String {
        self.inner.to_hex()
    }
}

#[pyclass(name = "QuoteForAddress")]
pub struct PyQuoteForAddress {
    inner: QuoteForAddress,
}

#[pymethods]
impl PyQuoteForAddress {
    pub fn price(&self) -> String {
        self.inner.price().to_string()
    }
}

#[pyclass(name = "QuotingMetrics")]
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PyQuotingMetrics {
    inner: QuotingMetrics,
}

#[pymethods]
impl PyQuotingMetrics {
    #[new]
    #[allow(clippy::too_many_arguments)]
    #[pyo3(signature = (data_type, data_size, close_records_stored, records_per_type, max_records, received_payment_count, live_time, network_density=None, network_size=None))]
    fn new(
        data_type: u32,
        data_size: usize,
        close_records_stored: usize,
        records_per_type: Vec<(u32, u32)>,
        max_records: usize,
        received_payment_count: usize,
        live_time: u64,
        network_density: Option<Vec<u8>>,
        network_size: Option<u64>,
    ) -> PyResult<Self> {
        // Convert network_density from Option<Vec<u8>> to Option<[u8; 32]>
        let network_density = if let Some(density) = network_density {
            if density.len() != 32 {
                return Err(PyValueError::new_err(
                    "network_density must be 32 bytes if provided",
                ));
            }
            let mut array = [0u8; 32];
            array.copy_from_slice(&density);
            Some(array)
        } else {
            None
        };

        Ok(Self {
            inner: QuotingMetrics {
                data_type,
                data_size,
                close_records_stored,
                records_per_type,
                max_records,
                received_payment_count,
                live_time,
                network_density,
                network_size,
            },
        })
    }

    // Getters
    #[getter]
    fn data_type(&self) -> u32 {
        self.inner.data_type
    }

    #[setter]
    fn set_data_type(&mut self, value: u32) {
        self.inner.data_type = value;
    }

    #[getter]
    fn data_size(&self) -> usize {
        self.inner.data_size
    }

    #[setter]
    fn set_data_size(&mut self, value: usize) {
        self.inner.data_size = value;
    }

    #[getter]
    fn close_records_stored(&self) -> usize {
        self.inner.close_records_stored
    }

    #[setter]
    fn set_close_records_stored(&mut self, value: usize) {
        self.inner.close_records_stored = value;
    }

    #[getter]
    fn records_per_type(&self) -> Vec<(u32, u32)> {
        self.inner.records_per_type.clone()
    }

    #[setter]
    fn set_records_per_type(&mut self, value: Vec<(u32, u32)>) {
        self.inner.records_per_type = value;
    }

    #[getter]
    fn max_records(&self) -> usize {
        self.inner.max_records
    }

    #[setter]
    fn set_max_records(&mut self, value: usize) {
        self.inner.max_records = value;
    }

    #[getter]
    fn received_payment_count(&self) -> usize {
        self.inner.received_payment_count
    }

    #[setter]
    fn set_received_payment_count(&mut self, value: usize) {
        self.inner.received_payment_count = value;
    }

    #[getter]
    fn live_time(&self) -> u64 {
        self.inner.live_time
    }

    #[setter]
    fn set_live_time(&mut self, value: u64) {
        self.inner.live_time = value;
    }

    #[getter]
    fn network_density(&self) -> Option<Vec<u8>> {
        self.inner.network_density.map(|array| array.to_vec())
    }

    #[setter]
    fn set_network_density(&mut self, value: Option<Vec<u8>>) -> PyResult<()> {
        self.inner.network_density = if let Some(density) = value {
            if density.len() != 32 {
                return Err(PyValueError::new_err(
                    "network_density must be 32 bytes if provided",
                ));
            }
            let mut array = [0u8; 32];
            array.copy_from_slice(&density);
            Some(array)
        } else {
            None
        };
        Ok(())
    }

    #[getter]
    fn network_size(&self) -> Option<u64> {
        self.inner.network_size
    }

    #[setter]
    fn set_network_size(&mut self, value: Option<u64>) {
        self.inner.network_size = value;
    }

    fn __str__(&self) -> String {
        format!("{:?}", self.inner)
    }

    fn __repr__(&self) -> String {
        self.__str__()
    }
}

#[pyclass(name = "PaymentQuote")]
#[derive(Clone)]
pub struct PyPaymentQuote {
    inner: PaymentQuote,
}

#[pymethods]
impl PyPaymentQuote {
    /// Creates a new PaymentQuote with the provided values
    #[new]
    #[pyo3(signature = (content, timestamp, quoting_metrics, rewards_address, pub_key, signature))]
    fn new(
        content: PyXorName,
        timestamp: u64, // seconds since UNIX_EPOCH
        quoting_metrics: PyQuotingMetrics,
        rewards_address: String, // hex string with optional 0x prefix
        pub_key: Vec<u8>,
        signature: Vec<u8>,
    ) -> PyResult<Self> {
        // Convert timestamp from u64 to SystemTime
        let timestamp = SystemTime::UNIX_EPOCH + Duration::from_secs(timestamp);

        // Convert rewards address from hex string to RewardsAddress
        let rewards_address = RewardsAddress::from_slice(
            &hex::decode(rewards_address.trim_start_matches("0x"))
                .map_err(|e| PyValueError::new_err(format!("Invalid rewards address: {e}")))?,
        );

        Ok(Self {
            inner: PaymentQuote {
                content: content.inner,
                timestamp,
                quoting_metrics: quoting_metrics.inner,
                rewards_address,
                pub_key,
                signature,
            },
        })
    }

    /// Returns the hash of the quote
    fn hash(&self) -> String {
        format!("0x{}", hex::encode(self.inner.hash().0))
    }

    /// Returns the bytes that would be signed for the given parameters
    #[staticmethod]
    fn bytes_for_signing(
        xorname: PyXorName,
        timestamp: u64,
        quoting_metrics: PyQuotingMetrics,
        rewards_address: String,
    ) -> PyResult<Vec<u8>> {
        // Convert timestamp from u64 to SystemTime
        let timestamp = SystemTime::UNIX_EPOCH + Duration::from_secs(timestamp);

        // Convert rewards address from hex string to RewardsAddress
        let rewards_address = RewardsAddress::from_slice(
            &hex::decode(rewards_address.trim_start_matches("0x"))
                .map_err(|e| PyValueError::new_err(format!("Invalid rewards address: {e}")))?,
        );

        Ok(PaymentQuote::bytes_for_signing(
            xorname.inner,
            timestamp,
            &quoting_metrics.inner,
            &rewards_address,
        ))
    }

    /// Returns the bytes to be signed from self
    fn bytes_for_sig(&self) -> Vec<u8> {
        self.inner.bytes_for_sig()
    }

    /// Returns the peer id of the node that created the quote
    fn peer_id(&self) -> PyResult<String> {
        match self.inner.peer_id() {
            Ok(peer_id) => Ok(peer_id.to_string()),
            Err(e) => Err(PyRuntimeError::new_err(format!(
                "Failed to get peer id: {e}"
            ))),
        }
    }

    /// Check if self is signed by the claimed peer
    fn check_is_signed_by_claimed_peer(&self, claimed_peer: String) -> PyResult<bool> {
        let peer_id = match PeerId::from_str(&claimed_peer) {
            Ok(id) => id,
            Err(e) => return Err(PyValueError::new_err(format!("Invalid peer ID: {e}"))),
        };

        Ok(self.inner.check_is_signed_by_claimed_peer(peer_id))
    }

    /// Check whether self is newer than the target quote
    fn is_newer_than(&self, other: &PyPaymentQuote) -> bool {
        self.inner.is_newer_than(&other.inner)
    }

    /// Check against a new quote, verify whether it is a valid one from self perspective
    fn historical_verify(&self, other: &PyPaymentQuote) -> bool {
        self.inner.historical_verify(&other.inner)
    }

    /// Returns the content of the quote
    #[getter]
    fn content(&self) -> PyXorName {
        PyXorName {
            inner: self.inner.content,
        }
    }

    /// Returns the timestamp of the quote as seconds since UNIX epoch
    #[getter]
    fn timestamp(&self) -> PyResult<u64> {
        self.inner
            .timestamp
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .map_err(|e| PyRuntimeError::new_err(format!("Failed to get timestamp: {e}")))
    }

    /// Returns the quoting metrics
    #[getter]
    fn quoting_metrics(&self) -> PyQuotingMetrics {
        PyQuotingMetrics {
            inner: self.inner.quoting_metrics.clone(),
        }
    }

    /// Returns the rewards address as a hex string
    #[getter]
    fn rewards_address(&self) -> String {
        format!("0x{}", hex::encode(self.inner.rewards_address.as_slice()))
    }

    /// Returns the public key as bytes
    #[getter]
    fn pub_key(&self) -> Vec<u8> {
        self.inner.pub_key.clone()
    }

    /// Returns the signature as bytes
    #[getter]
    fn signature(&self) -> Vec<u8> {
        self.inner.signature.clone()
    }

    /// Returns the string representation
    fn __str__(&self) -> String {
        format!(
            "PaymentQuote(content={}, timestamp={})",
            self.inner.content,
            self.inner
                .timestamp
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
        )
    }

    /// Returns the debug representation
    fn __repr__(&self) -> String {
        self.__str__()
    }
}

/// Contains the proof of payments for each XorName and the amount paid
#[pyclass(name = "Receipt")]
#[derive(Clone)]
pub struct PyReceipt {
    pub(crate) inner: Receipt,
}

#[pymethods]
impl PyReceipt {
    /// Creates a new empty receipt
    #[new]
    fn new() -> Self {
        Self {
            inner: Receipt::new(),
        }
    }

    /// Returns the number of entries in the receipt
    fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns true if the receipt has no entries
    fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

#[pyclass(name = "RegisterAddress")]
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
pub struct PyRegisterAddress {
    inner: RegisterAddress,
}

#[pymethods]
impl PyRegisterAddress {
    /// Create a new register address from a PublicKey
    #[new]
    fn new(owner: PyPublicKey) -> Self {
        Self {
            inner: RegisterAddress::new(owner.inner),
        }
    }

    /// Get the owner of the register
    fn owner(&self) -> PyPublicKey {
        PyPublicKey {
            inner: self.inner.owner(),
        }
    }

    /// Convert to underlying graph representation
    fn as_underlying_graph_root(&self) -> PyGraphEntryAddress {
        PyGraphEntryAddress {
            inner: self.inner.to_underlying_graph_root(),
        }
    }

    /// Convert to underlying head pointer
    fn as_underlying_head_pointer(&self) -> PyPointerAddress {
        PyPointerAddress {
            inner: self.inner.to_underlying_head_pointer(),
        }
    }

    /// Convert a register address to a hex string
    fn as_hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Convert a hex string to a register address
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        RegisterAddress::from_hex(hex)
            .map(|addr| Self { inner: addr })
            .map_err(|e| PyValueError::new_err(format!("Failed to parse hex: {e}")))
    }

    /// String representation (returns hex format)
    fn __str__(&self) -> String {
        self.inner.to_string()
    }

    /// Representation for debugging
    fn __repr__(&self) -> String {
        format!("RegisterAddress('{}')", self.inner.to_hex())
    }
}

/// A secret key used to encrypt and decrypt vault data.
#[pyclass(name = "VaultSecretKey")]
#[derive(Debug, Clone)]
pub struct PyVaultSecretKey {
    inner: VaultSecretKey,
}

#[pymethods]
impl PyVaultSecretKey {
    /// Creates a new random vault secret key.
    #[new]
    fn new() -> PyResult<Self> {
        Ok(Self {
            inner: VaultSecretKey::random(),
        })
    }

    #[staticmethod]
    fn from_hex(hex_str: &str) -> PyResult<Self> {
        VaultSecretKey::from_hex(hex_str)
            .map(|key| Self { inner: key })
            .map_err(|e| PyValueError::new_err(format!("Invalid hex key: {e}")))
    }

    /// Returns the hex string representation of the vault secret key.
    fn hex(&self) -> String {
        self.inner.to_hex()
    }
}

/// UserData is stored in Vaults and contains most of a user's private data:
/// It allows users to keep track of only the key to their User Data Vault
/// while having the rest kept on the Network encrypted in a Vault for them
/// Using User Data Vault is optional, one can decide to keep all their data locally instead.
#[pyclass(name = "UserData")]
#[derive(Debug, Clone)]
pub struct PyUserData {
    inner: UserData,
}

#[pymethods]
impl PyUserData {
    /// Creates a new empty UserData instance.
    #[new]
    fn new() -> Self {
        Self {
            inner: UserData::new(),
        }
    }

    /// Returns a list of public file archives as (address, name) pairs.
    fn file_archives(&self) -> Vec<(String, String)> {
        self.inner
            .file_archives
            .iter()
            .map(|(addr, name)| (addr.to_hex(), name.clone()))
            .collect()
    }

    /// Returns a list of private file archives as (data_map, name) pairs.
    fn private_file_archives(&self) -> Vec<(String, String)> {
        self.inner
            .private_file_archives
            .iter()
            .map(|(addr, name)| (addr.to_hex(), name.clone()))
            .collect()
    }
}

/// A map with encrypted data pieces on the network. Used to locate and reconstruct private data.
#[pyclass(name = "DataMapChunk")]
#[derive(Debug, Clone)]
pub struct PyDataMapChunk {
    inner: DataMapChunk,
}

#[pymethods]
impl PyDataMapChunk {
    /// Creates a DataMapChunk from a hex string representation.
    #[staticmethod]
    fn from_hex(hex: &str) -> PyResult<Self> {
        DataMapChunk::from_hex(hex)
            .map(|access| Self { inner: access })
            .map_err(|e| PyValueError::new_err(format!("Invalid hex: {e}")))
    }

    /// Returns the hex string representation of this DataMapChunk.
    fn hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Returns the private address of this DataMapChunk.
    ///
    /// Note that this is not a network address, it is only used for refering to private data client side.
    fn address(&self) -> String {
        self.inner.address().to_string()
    }
}

/// Python iterator wrapper for data streaming
#[pyclass(name = "DataStream")]
pub struct PyDataStream {
    inner: Mutex<crate::client::data::DataStream>,
}

impl PyDataStream {
    fn new(stream: crate::client::data::DataStream) -> Self {
        Self {
            inner: Mutex::new(stream),
        }
    }
}

#[pymethods]
impl PyDataStream {
    /// Make this object iterable
    fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
        slf
    }

    /// Get the next chunk from the stream
    fn __next__(&mut self) -> PyResult<Option<Vec<u8>>> {
        let mut stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        match stream.next() {
            Some(Ok(chunk)) => Ok(Some(chunk.to_vec())),
            Some(Err(e)) => Err(PyRuntimeError::new_err(format!("Stream error: {e}"))),
            None => Ok(None),
        }
    }

    /// Returns the original data size
    fn data_size(&self) -> PyResult<usize> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        Ok(stream.data_size())
    }

    /// Decrypts and returns a specific byte range from the encrypted data.
    ///
    /// Args:
    ///     start: The starting byte position (inclusive)
    ///     len: The number of bytes to read
    ///
    /// Returns:
    ///     List of bytes containing the decrypted range data
    fn get_range(&self, start: usize, len: usize) -> PyResult<Vec<u8>> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        let bytes = stream
            .get_range(start, len)
            .map_err(|e| PyRuntimeError::new_err(format!("Range access error: {e}")))?;
        Ok(bytes.to_vec())
    }

    /// Convenience method to get a range using start and end positions.
    ///
    /// Args:
    ///     start: The starting byte position (inclusive)
    ///     end: The ending byte position (exclusive)
    ///
    /// Returns:
    ///     List of bytes containing the decrypted range data
    fn range(&self, start: usize, end: usize) -> PyResult<Vec<u8>> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        let bytes = stream
            .range(start..end)
            .map_err(|e| PyRuntimeError::new_err(format!("Range access error: {e}")))?;
        Ok(bytes.to_vec())
    }

    /// Convenience method to get a range from a starting position to the end of the file.
    ///
    /// Args:
    ///     start: The starting byte position (inclusive)
    ///
    /// Returns:
    ///     List of bytes from start position to end of file
    fn range_from(&self, start: usize) -> PyResult<Vec<u8>> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        let bytes = stream
            .range_from(start)
            .map_err(|e| PyRuntimeError::new_err(format!("Range access error: {e}")))?;
        Ok(bytes.to_vec())
    }

    /// Convenience method to get a range from the beginning of the file to an end position.
    ///
    /// Args:
    ///     end: The ending byte position (exclusive)
    ///
    /// Returns:
    ///     List of bytes from beginning of file to end position
    fn range_to(&self, end: usize) -> PyResult<Vec<u8>> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        let bytes = stream
            .range_to(end)
            .map_err(|e| PyRuntimeError::new_err(format!("Range access error: {e}")))?;
        Ok(bytes.to_vec())
    }

    /// Convenience method to get the entire file content.
    ///
    /// Returns:
    ///     List of bytes containing the entire file content
    fn range_all(&self) -> PyResult<Vec<u8>> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        let bytes = stream
            .range_full()
            .map_err(|e| PyRuntimeError::new_err(format!("Range access error: {e}")))?;
        Ok(bytes.to_vec())
    }

    /// Convenience method to get an inclusive range.
    ///
    /// Args:
    ///     start: The starting byte position (inclusive)
    ///     end: The ending byte position (inclusive)
    ///
    /// Returns:
    ///     List of bytes containing the decrypted inclusive range data
    fn range_inclusive(&self, start: usize, end: usize) -> PyResult<Vec<u8>> {
        let stream = self
            .inner
            .lock()
            .map_err(|e| PyRuntimeError::new_err(format!("Lock error: {e}")))?;
        let bytes = stream
            .range_inclusive(start, end)
            .map_err(|e| PyRuntimeError::new_err(format!("Range access error: {e}")))?;
        Ok(bytes.to_vec())
    }
}

#[pyfunction]
fn encrypt(data: Vec<u8>) -> PyResult<(Vec<u8>, Vec<Vec<u8>>)> {
    let (data_map, chunks) = self_encryption::encrypt(Bytes::from(data))
        .map_err(|e| PyRuntimeError::new_err(format!("Encryption failed: {e}")))?;

    let data_map_bytes = rmp_serde::to_vec(&data_map)
        .map_err(|e| PyRuntimeError::new_err(format!("Failed to serialize datamap: {e}")))?;

    let chunks_bytes: Vec<Vec<u8>> = chunks
        .into_iter()
        .map(|chunk| chunk.content.to_vec())
        .collect();

    Ok((data_map_bytes, chunks_bytes))
}

#[pyclass(name = "DerivationIndex")]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Hash)]
pub struct PyDerivationIndex {
    inner: DerivationIndex,
}

#[pymethods]
impl PyDerivationIndex {
    /// Generates a random derivation index
    #[staticmethod]
    fn random() -> Self {
        let mut rng = rand::thread_rng();
        Self {
            inner: DerivationIndex::random(&mut rng),
        }
    }

    /// Returns the inner bytes representation
    fn as_bytes(&self) -> [u8; 32] {
        *self.inner.as_bytes()
    }

    /// Returns the inner bytes
    fn bytes_owned(&self) -> [u8; 32] {
        self.inner.into_bytes()
    }

    /// Creates a new DerivationIndex from a bytes array
    #[staticmethod]
    fn from_bytes(bytes: [u8; 32]) -> Self {
        Self {
            inner: DerivationIndex::from_bytes(bytes),
        }
    }

    /// Returns a string representation of the derivation index
    fn __str__(&self) -> String {
        format!(
            "{:02x}{:02x}{:02x}..",
            self.inner.as_bytes()[0],
            self.inner.as_bytes()[1],
            self.inner.as_bytes()[2]
        )
    }

    /// Returns a debug representation of the derivation index
    fn __repr__(&self) -> String {
        format!(
            "DerivationIndex({:02x}{:02x}{:02x}..)",
            self.inner.as_bytes()[0],
            self.inner.as_bytes()[1],
            self.inner.as_bytes()[2]
        )
    }
}

#[pyclass(name = "DerivedPubkey")]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PyDerivedPubkey {
    inner: DerivedPubkey,
}

#[pymethods]
impl PyDerivedPubkey {
    /// Create a new DerivedPubkey from a PublicKey
    #[new]
    fn new(public_key: PyPublicKey) -> Self {
        Self {
            inner: DerivedPubkey::new(public_key.inner),
        }
    }

    /// Convert to bytes representation
    fn as_bytes(&self) -> [u8; bls::PK_SIZE] {
        self.inner.to_bytes()
    }

    /// Verify a signature against a message
    fn verify(&self, sig: &PySignature, msg: &[u8]) -> bool {
        self.inner.verify(&sig.inner, msg)
    }

    /// Convert to hex string representation
    fn as_hex(&self) -> String {
        self.inner.to_hex()
    }

    /// Create a DerivedPubkey from a hex string
    #[staticmethod]
    fn from_hex(hex_str: &str) -> PyResult<Self> {
        DerivedPubkey::from_hex(hex_str)
            .map(|inner| Self { inner })
            .map_err(|e| PyValueError::new_err(format!("Failed to parse hex: {e}")))
    }

    /// Return string representation (hex format)
    fn __str__(&self) -> String {
        self.inner.to_hex()
    }

    /// Return representation for debugging
    fn __repr__(&self) -> String {
        format!("DerivedPubkey('{}')", self.inner.to_hex())
    }
}

#[pyclass(name = "DerivedSecretKey")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PyDerivedSecretKey {
    inner: DerivedSecretKey,
}

#[pymethods]
impl PyDerivedSecretKey {
    /// Create a new DerivedSecretKey from a SecretKey
    #[new]
    fn new(secret_key: PySecretKey) -> Self {
        Self {
            inner: DerivedSecretKey::new(secret_key.inner),
        }
    }

    /// Get the corresponding DerivedPubkey
    fn public_key(&self) -> PyDerivedPubkey {
        PyDerivedPubkey {
            inner: self.inner.public_key(),
        }
    }

    /// Sign a message with the secret key
    fn sign(&self, msg: &[u8]) -> PySignature {
        PySignature {
            inner: self.inner.sign(msg),
        }
    }

    /// Return string representation for debugging
    fn __repr__(&self) -> String {
        format!(
            "DerivedSecretKey(public_key={})",
            self.public_key().as_hex()
        )
    }
}

#[pyclass(name = "EVMNetwork", eq)]
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PyEVMNetwork {
    inner: EVMNetwork,
}

#[pymethods]
impl PyEVMNetwork {
    /// Creates a new network configuration.
    ///
    /// If `local` is true, configures for local network connections.
    #[new]
    fn new(local: bool) -> PyResult<Self> {
        let inner =
            EVMNetwork::new(local).map_err(|e| PyRuntimeError::new_err(format!("{e:?}")))?;
        Ok(Self { inner })
    }

    #[staticmethod]
    fn new_custom(rpc_url: &str, payment_token_addr: &str, data_payments_addr: &str) -> Self {
        Self {
            inner: EVMNetwork::new_custom(rpc_url, payment_token_addr, data_payments_addr, None),
        }
    }

    fn identifier(&self) -> &str {
        self.inner.identifier()
    }

    fn rpc_url(&self) -> String {
        self.inner.rpc_url().as_str().to_string()
    }

    fn payment_token_address(&self) -> String {
        self.inner.payment_token_address().to_string()
    }

    fn data_payments_address(&self) -> String {
        self.inner.data_payments_address().to_string()
    }
}

/// Metadata for files in an archive, containing creation time, modification time, and size.
#[pyclass(name = "Metadata")]
#[derive(Debug, Clone)]
pub struct PyMetadata {
    inner: Metadata,
}

#[pymethods]
impl PyMetadata {
    /// Create new metadata with the given file size
    #[new]
    fn new(size: u64) -> Self {
        Self {
            inner: Metadata::new_with_size(size),
        }
    }

    /// Get the creation time as Unix timestamp in seconds
    #[getter]
    fn get_created(&self) -> u64 {
        self.inner.created
    }

    /// Set the creation time as Unix timestamp in seconds
    #[setter]
    fn set_created(&mut self, value: u64) {
        self.inner.created = value;
    }

    /// Get the modification time as Unix timestamp in seconds
    #[getter]
    fn get_modified(&self) -> u64 {
        self.inner.modified
    }

    /// Set the modification time as Unix timestamp in seconds
    #[setter]
    fn set_modified(&mut self, value: u64) {
        self.inner.modified = value;
    }

    /// Get the file size in bytes
    #[getter]
    fn get_size(&self) -> u64 {
        self.inner.size
    }

    /// Set the file size in bytes
    #[setter]
    fn set_size(&mut self, value: u64) {
        self.inner.size = value;
    }
}

/// A public archive containing files that can be accessed by anyone on the network.
#[pyclass(name = "PublicArchive")]
#[derive(Debug, Clone)]
pub struct PyPublicArchive {
    inner: PublicArchive,
}

#[pymethods]
impl PyPublicArchive {
    /// Create a new empty archive
    #[new]
    fn new() -> Self {
        Self {
            inner: PublicArchive::new(),
        }
    }

    /// Rename a file in the archive.
    ///
    /// Returns None on success, or error message on failure
    fn rename_file(&mut self, old_path: PathBuf, new_path: PathBuf) -> PyResult<()> {
        self.inner
            .rename_file(&old_path, &new_path)
            .map_err(|e| PyRuntimeError::new_err(format!("Failed to rename file: {e}")))
    }

    /// Add a file to the archive
    fn add_file(&mut self, path: PathBuf, addr: &PyDataAddress, metadata: &PyMetadata) {
        self.inner
            .add_file(path, addr.inner, metadata.inner.clone());
    }

    /// List all files in the archive.
    ///
    /// Returns a list of (path, metadata) tuples
    fn files(&self) -> Vec<(PathBuf, PyMetadata)> {
        self.inner
            .files()
            .into_iter()
            .map(|(path, meta)| (path, PyMetadata { inner: meta }))
            .collect()
    }

    /// List all data addresses of files in the archive
    fn addresses(&self) -> Vec<String> {
        self.inner
            .addresses()
            .into_iter()
            .map(|a| a.to_hex())
            .collect()
    }
}

/// A public archive containing files that can be accessed by anyone on the network.
#[pyclass(name = "PrivateArchive")]
#[derive(Debug, Clone)]
pub struct PyPrivateArchive {
    inner: PrivateArchive,
}

#[pymethods]
impl PyPrivateArchive {
    /// Create a new empty archive
    #[new]
    fn new() -> Self {
        Self {
            inner: PrivateArchive::new(),
        }
    }

    /// Rename a file in the archive.
    ///
    /// Returns None on success, or error message on failure
    fn rename_file(&mut self, old_path: PathBuf, new_path: PathBuf) -> PyResult<()> {
        self.inner
            .rename_file(&old_path, &new_path)
            .map_err(|e| PyRuntimeError::new_err(format!("Failed to rename file: {e}")))
    }

    /// Add a file to a local archive. Note that this does not upload the archive to the network.
    fn add_file(&mut self, path: PathBuf, data_map: &PyDataMapChunk, metadata: &PyMetadata) {
        self.inner
            .add_file(path, data_map.inner.clone(), metadata.inner.clone());
    }

    /// List all files in the archive.
    fn files(&self) -> Vec<(PathBuf, PyMetadata)> {
        self.inner
            .files()
            .into_iter()
            .map(|(path, meta)| (path, PyMetadata { inner: meta }))
            .collect()
    }

    /// List all datamaps of files in the archive
    fn data_maps(&self) -> Vec<PyDataMapChunk> {
        self.inner
            .data_maps()
            .into_iter()
            .map(|data_map| PyDataMapChunk { inner: data_map })
            .collect()
    }
}

/// A generic GraphEntry on the Network.
///
/// Graph entries are stored at the owner's public key. Note that there can only be one graph entry per owner.
/// Graph entries can be linked to other graph entries as parents or descendants.
/// Applications are free to define the meaning of these links, those are not enforced by the protocol.
/// The protocol only ensures that the graph entry is immutable once uploaded and that the signature is valid and matches the owner.
///
/// For convenience it is advised to make use of BLS key derivation to create multiple graph entries from a single key.
#[pyclass(name = "GraphEntry", eq, ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct PyGraphEntry {
    inner: GraphEntry,
}

#[pymethods]
impl PyGraphEntry {
    /// Create a new graph entry, signing it with the provided secret key.
    #[new]
    fn new(
        owner: PySecretKey,
        parents: Vec<PyPublicKey>,
        content: [u8; 32],
        descendants: Vec<(PyPublicKey, [u8; 32])>,
    ) -> PyResult<Self> {
        Ok(Self {
            inner: GraphEntry::new(
                &owner.inner,
                parents.into_iter().map(|p| p.inner).collect(),
                content,
                descendants.into_iter().map(|p| (p.0.inner, p.1)).collect(),
            ),
        })
    }

    /// Returns the network address where this entry is stored.
    pub fn address(&self) -> PyGraphEntryAddress {
        PyGraphEntryAddress {
            inner: self.inner.address(),
        }
    }

    /// Returns the content of the graph entry.
    pub fn content(&self) -> [u8; 32] {
        self.inner.content
    }

    /// Returns the parents' public keys.
    pub fn parents(&self) -> Vec<PyPublicKey> {
        self.inner
            .parents
            .iter()
            .map(|&p| PyPublicKey { inner: p })
            .collect()
    }

    /// Returns the descendants as (public_key, content) pairs.
    pub fn descendants(&self) -> Vec<(PyPublicKey, [u8; 32])> {
        self.inner
            .descendants
            .iter()
            .map(|&(pk, c)| (PyPublicKey { inner: pk }, c))
            .collect()
    }
}

/// Scratchpad, a mutable space for encrypted data on the Network
#[pyclass(name = "Scratchpad", eq, ord)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct PyScratchpad {
    inner: Scratchpad,
}

#[pymethods]
impl PyScratchpad {
    /// Creates a new instance of Scratchpad. Encrypts the data, and signs all the elements.
    #[new]
    fn new(
        owner: PySecretKey,
        data_encoding: u64,
        unencrypted_data: Vec<u8>,
        counter: u64,
    ) -> PyResult<Self> {
        Ok(Self {
            inner: Scratchpad::new(
                &owner.inner,
                data_encoding,
                &Bytes::from(unencrypted_data),
                counter,
            ),
        })
    }

    /// Returns the address of the scratchpad.
    pub fn address(&self) -> PyScratchpadAddress {
        PyScratchpadAddress {
            inner: *self.inner.address(),
        }
    }

    /// Return the current data encoding.
    pub fn data_encoding(&self) -> u64 {
        self.inner.data_encoding()
    }

    /// Get the counter of the Scratchpad, the higher the counter, the more recent the Scratchpad is.
    ///
    /// Similarly to counter CRDTs only the latest version (highest counter) of the Scratchpad is kept on the network
    pub fn counter(&self) -> u64 {
        self.inner.counter()
    }

    /// Returns the encrypted_data, decrypted via the passed SecretKey
    pub fn decrypt_data(&self, sk: PySecretKey) -> PyResult<Vec<u8>> {
        let data = self
            .inner
            .decrypt_data(&sk.inner)
            .map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
        Ok(data.to_vec())
    }

    /// Returns the owner public key
    pub fn owner(&self) -> PyPublicKey {
        PyPublicKey {
            inner: *self.inner.owner(),
        }
    }

    /// Returns the signature
    pub fn signature(&self) -> PySignature {
        PySignature {
            inner: self.inner.signature().clone(),
        }
    }

    /// Returns the scratchpad hash as hex string
    pub fn scratchpad_hash(&self) -> String {
        hex::encode(self.inner.scratchpad_hash().0)
    }

    /// Returns the encrypted data hash as hex string
    pub fn encrypted_data_hash(&self) -> String {
        hex::encode(self.inner.encrypted_data_hash())
    }

    /// Returns the encrypted data
    pub fn encrypted_data(&self) -> Vec<u8> {
        self.inner.encrypted_data().to_vec()
    }
}

/// A handle to the register history
#[pyclass(name = "RegisterHistory")]
#[derive(Clone)]
pub struct PyRegisterHistory {
    inner: Arc<futures::lock::Mutex<RegisterHistory>>,
}

impl PyRegisterHistory {
    fn new(history: RegisterHistory) -> Self {
        Self {
            inner: Arc::new(futures::lock::Mutex::new(history)),
        }
    }
}

#[pymethods]
impl PyRegisterHistory {
    fn next<'a>(&'a mut self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        let arc = Arc::clone(&self.inner);

        future_into_py(py, async move {
            let mut register_history = arc.lock().await;
            let value = register_history
                .next()
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("history `next` failed: {e}")))?;

            Ok(value)
        })
    }

    fn collect<'a>(&'a mut self, py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
        let arc = Arc::clone(&self.inner);

        future_into_py(py, async move {
            let mut register_history = arc.lock().await;
            let values = register_history
                .collect()
                .await
                .map_err(|e| PyRuntimeError::new_err(format!("history `collect` failed: {e}")))?;

            Ok(values)
        })
    }
}

/// Configuration for the `Client` which can be provided through: `init_with_config`.
#[pyclass(name = "ClientConfig")]
#[derive(Debug, Clone)]
pub struct PyClientConfig {
    inner: ClientConfig,
}

#[pymethods]
impl PyClientConfig {
    #[new]
    fn new() -> Self {
        Self {
            inner: ClientConfig::default(),
        }
    }

    /// Whether we're expected to connect to a local network.
    #[getter]
    fn get_local(&self) -> bool {
        self.inner.bootstrap_config.local
    }

    /// Whether we're expected to connect to a local network.
    #[setter]
    fn set_local(&mut self, value: bool) {
        self.inner.bootstrap_config.local = value;
    }

    /// List of peers to connect to.
    ///
    /// If not provided, the client will use the default bootstrap peers.
    #[getter]
    fn get_peers(&self) -> Vec<String> {
        self.inner
            .bootstrap_config
            .initial_peers
            .iter()
            .map(|p| p.to_string())
            .collect()
    }

    /// List of peers to connect to. If given empty list, the client will use the default bootstrap peers.
    #[setter]
    fn set_peers(&mut self, peers: Vec<String>) -> PyResult<()> {
        if peers.is_empty() {
            return Ok(());
        }

        let peers: Vec<Multiaddr> = peers
            .iter()
            .map(|p| Multiaddr::from_str(p))
            .collect::<Result<_, _>>()
            .map_err(|e| PyValueError::new_err(format!("Failed to parse peers: {e}")))?;

        self.inner.bootstrap_config.initial_peers = peers;
        Ok(())
    }

    /// EVM network to use for quotations and payments.
    #[getter]
    fn get_network(&self) -> PyEVMNetwork {
        PyEVMNetwork {
            inner: self.inner.evm_network.clone(),
        }
    }

    /// EVM network to use for quotations and payments.
    #[setter]
    fn set_network(&mut self, network: PyEVMNetwork) {
        self.inner.evm_network = network.inner;
    }
}

/// A handle to a XorName.
#[pyclass(name = "XorName")]
#[derive(Eq, Copy, Clone, Default, Hash, Ord, PartialEq, PartialOrd)]
pub struct PyXorName {
    pub(crate) inner: XorName,
}

#[pymethods]
impl PyXorName {
    /// Generate a XorName for the given content
    #[staticmethod]
    fn from_content(content: &[u8]) -> Self {
        Self {
            inner: XorName::from_content(content),
        }
    }

    /// Generate a XorName from multiple content parts
    #[staticmethod]
    fn from_content_parts(content_parts: Vec<Vec<u8>>) -> Self {
        let refs: Vec<&[u8]> = content_parts.iter().map(|v| v.as_slice()).collect();
        Self {
            inner: XorName::from_content_parts(&refs),
        }
    }

    /// Generate a random XorName
    #[staticmethod]
    fn random() -> Self {
        Self {
            inner: XorName::random(&mut rand::thread_rng()),
        }
    }

    /// Returns `true` if the `i`-th bit is `1`
    fn bit(&self, i: u8) -> bool {
        self.inner.bit(i)
    }

    /// Compares the distance of the arguments to `self`
    /// Returns -1 if `lhs` is closer, 1 if `rhs` is closer, and 0 if equal
    fn cmp_distance(&self, lhs: &PyXorName, rhs: &PyXorName) -> i32 {
        match self.inner.cmp_distance(&lhs.inner, &rhs.inner) {
            std::cmp::Ordering::Less => -1,
            std::cmp::Ordering::Equal => 0,
            std::cmp::Ordering::Greater => 1,
        }
    }

    /// Returns a copy of `self`, with the `i`-th bit set to `bit`
    fn with_bit(&self, i: u8, bit: bool) -> Self {
        Self {
            inner: self.inner.with_bit(i, bit),
        }
    }

    /// Convert the XorName to a hex string
    fn as_hex(&self) -> String {
        hex::encode(self.inner.0)
    }

    /// Create a XorName from a hex string
    #[staticmethod]
    fn from_hex(hex_str: &str) -> PyResult<Self> {
        if hex_str.len() != XOR_NAME_LEN * 2 {
            return Err(PyValueError::new_err(format!(
                "Hex string must be exactly {} characters",
                XOR_NAME_LEN * 2
            )));
        }

        let bytes = hex::decode(hex_str)
            .map_err(|e| PyValueError::new_err(format!("Invalid hex string: {e}")))?;

        let mut array = [0u8; XOR_NAME_LEN];
        array.copy_from_slice(&bytes);

        Ok(Self {
            inner: XorName(array),
        })
    }

    /// Return string representation (short form with first bytes)
    fn __str__(&self) -> String {
        format!("{}", self.inner)
    }

    /// Return debug representation
    fn __repr__(&self) -> String {
        format!("XorName({})", hex::encode(&self.inner.0[..3]))
    }

    fn __richcmp__(&self, other: &PyXorName, op: CompareOp) -> bool {
        match op {
            CompareOp::Lt => self.inner < other.inner,
            CompareOp::Le => self.inner <= other.inner,
            CompareOp::Eq => self.inner == other.inner,
            CompareOp::Ne => self.inner != other.inner,
            CompareOp::Gt => self.inner > other.inner,
            CompareOp::Ge => self.inner >= other.inner,
        }
    }

    fn __hash__(&self) -> isize {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::hash::Hash::hash(&self.inner, &mut hasher);
        std::hash::Hasher::finish(&hasher) as isize
    }
}

/// Generate a random XorName.
#[pyfunction]
fn random_xor() -> PyXorName {
    PyXorName {
        inner: XorName::random(&mut rand::thread_rng()),
    }
}

#[pymodule]
#[pyo3(name = "autonomi_client")]
fn autonomi_client_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // m.add_class::<PyANTNetwork>()?;
    m.add_class::<PyArchiveAddress>()?;
    m.add_class::<PyAttoTokens>()?;
    m.add_class::<PyBackoff>()?;
    m.add_class::<PyBootstrapCacheConfig>()?;
    m.add_class::<PyChunk>()?;
    m.add_class::<PyChunkAddress>()?;
    m.add_class::<PyClient>()?;
    m.add_class::<PyClientConfig>()?;
    m.add_class::<PyClientEvent>()?;
    m.add_class::<PyClientEventReceiver>()?;
    m.add_class::<PyClientOperatingStrategy>()?;
    m.add_class::<PyDataAddress>()?;
    m.add_class::<PyDataMapChunk>()?;
    m.add_class::<PyDataStream>()?;
    m.add_class::<PyDataTypes>()?;
    m.add_class::<PyDerivationIndex>()?;
    m.add_class::<PyDerivedPubkey>()?;
    m.add_class::<PyDerivedSecretKey>()?;
    m.add_class::<PyEVMNetwork>()?;
    m.add_class::<PyGraphEntry>()?;
    m.add_class::<PyGraphEntryAddress>()?;
    m.add_class::<PyInitialPeersConfig>()?;
    m.add_class::<PyMainPubkey>()?;
    m.add_class::<PyMainSecretKey>()?;
    m.add_class::<PyMaxFeePerGas>()?;
    m.add_class::<PyMetadata>()?;
    m.add_class::<PyPaymentMode>()?;
    m.add_class::<PyPaymentOption>()?;
    m.add_class::<PyPaymentQuote>()?;
    m.add_class::<PyPointer>()?;
    m.add_class::<PyPointerAddress>()?;
    m.add_class::<PyPointerTarget>()?;
    m.add_class::<PyPrivateArchive>()?;
    m.add_class::<PyPrivateArchiveDataMap>()?;
    m.add_class::<PyPublicArchive>()?;
    m.add_class::<PyPublicKey>()?;
    m.add_class::<PyQuorum>()?;
    m.add_class::<PyQuoteForAddress>()?;
    m.add_class::<PyQuotingMetrics>()?;
    m.add_class::<PyReceipt>()?;
    m.add_class::<PyRegisterAddress>()?;
    m.add_class::<PyRegisterHistory>()?;
    m.add_class::<PyRetryStrategy>()?;
    m.add_class::<PyScratchpad>()?;
    m.add_class::<PyScratchpadAddress>()?;
    m.add_class::<PySecretKey>()?;
    m.add_class::<PySignature>()?;
    m.add_class::<PyStoreQuote>()?;
    m.add_class::<PyStrategy>()?;
    m.add_class::<PyTransactionConfig>()?;
    m.add_class::<PyUploadSummary>()?;
    m.add_class::<PyUserData>()?;
    m.add_class::<PyVaultSecretKey>()?;
    m.add_class::<PyWallet>()?;
    m.add_class::<PyXorName>()?;
    m.add_function(wrap_pyfunction!(encrypt, m)?)?;
    m.add_function(wrap_pyfunction!(random_xor, m)?)?;
    Ok(())
}