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
//! The shielded wallet implementation
use std::collections::{btree_map, BTreeMap, BTreeSet};
use eyre::{eyre, Context};
use masp_primitives::asset_type::AssetType;
#[cfg(feature = "mainnet")]
use masp_primitives::consensus::MainNetwork as Network;
#[cfg(not(feature = "mainnet"))]
use masp_primitives::consensus::TestNetwork as Network;
use masp_primitives::convert::AllowedConversion;
use masp_primitives::ff::PrimeField;
use masp_primitives::memo::MemoBytes;
use masp_primitives::merkle_tree::{
CommitmentTree, IncrementalWitness, MerklePath,
};
use masp_primitives::sapling::{
Diversifier, Node, Note, Nullifier, ViewingKey,
};
use masp_primitives::transaction::builder::Builder;
use masp_primitives::transaction::components::sapling::builder::BuildParams;
use masp_primitives::transaction::components::{
I128Sum, TxOut, U64Sum, ValueSum,
};
use masp_primitives::transaction::fees::fixed::FeeRule;
use masp_primitives::transaction::{builder, Transaction};
use masp_primitives::zip32::{ExtendedKey, PseudoExtendedKey};
use namada_core::address::Address;
use namada_core::arith::checked;
use namada_core::borsh::{BorshDeserialize, BorshSerialize};
use namada_core::chain::BlockHeight;
use namada_core::collections::{HashMap, HashSet};
use namada_core::control_flow;
use namada_core::masp::{
encode_asset_type, AssetData, MaspEpoch, TransferSource, TransferTarget,
};
use namada_core::task_env::TaskEnvironment;
use namada_core::time::{DateTimeUtc, DurationSecs};
use namada_core::token::{
Amount, Change, DenominatedAmount, Denomination, MaspDigitPos,
};
use namada_io::client::Client;
use namada_io::{
display_line, edisplay_line, Io, MaybeSend, MaybeSync, NamadaIo,
ProgressBar,
};
use namada_tx::IndexedTx;
use namada_wallet::{DatedKeypair, DatedSpendingKey};
use rand::prelude::StdRng;
use rand_core::{OsRng, SeedableRng};
use crate::masp::utils::MaspClient;
#[cfg(any(test, feature = "testing"))]
use crate::masp::{testing, ENV_VAR_MASP_TEST_SEED};
use crate::masp::{
ContextSyncStatus, Conversions, MaspAmount, MaspDataLogEntry, MaspFeeData,
MaspSourceTransferData, MaspTargetTransferData, MaspTransferData,
MaspTxReorderedData, NoteIndex, ShieldedSyncConfig, ShieldedTransfer,
ShieldedUtils, SpentNotesTracker, TransferErr, WalletMap, WitnessMap,
NETWORK,
};
/// Represents the current state of the shielded pool from the perspective of
/// the chosen viewing keys.
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct ShieldedWallet<U: ShieldedUtils> {
/// Location where this shielded context is saved
#[borsh(skip)]
pub utils: U,
/// The commitment tree produced by scanning all transactions up to tx_pos
pub tree: CommitmentTree<Node>,
/// Maps viewing keys to the block height to which they are synced.
/// In particular, the height given by the value *has been scanned*.
pub vk_heights: BTreeMap<ViewingKey, Option<IndexedTx>>,
/// Maps viewing keys to applicable note positions
pub pos_map: HashMap<ViewingKey, BTreeSet<usize>>,
/// Maps a nullifier to the note position to which it applies
pub nf_map: HashMap<Nullifier, usize>,
/// Maps note positions to their corresponding notes
pub note_map: HashMap<usize, Note>,
/// Maps note positions to their corresponding memos
pub memo_map: HashMap<usize, MemoBytes>,
/// Maps note positions to the diversifier of their payment address
pub div_map: HashMap<usize, Diversifier>,
/// Maps note positions to their witness (used to make merkle paths)
pub witness_map: WitnessMap,
/// The set of note positions that have been spent
pub spents: HashSet<usize>,
/// Maps asset types to their decodings
pub asset_types: HashMap<AssetType, AssetData>,
/// Maps note positions to their corresponding viewing keys
pub vk_map: HashMap<usize, ViewingKey>,
/// Maps a shielded tx to the index of its first output note.
pub note_index: NoteIndex,
/// The sync state of the context
pub sync_status: ContextSyncStatus,
}
/// Default implementation to ease construction of TxContexts. Derive cannot be
/// used here due to CommitmentTree not implementing Default.
impl<U: ShieldedUtils + Default> Default for ShieldedWallet<U> {
fn default() -> ShieldedWallet<U> {
ShieldedWallet::<U> {
utils: U::default(),
vk_heights: BTreeMap::new(),
note_index: BTreeMap::default(),
tree: CommitmentTree::empty(),
pos_map: HashMap::default(),
nf_map: HashMap::default(),
note_map: HashMap::default(),
memo_map: HashMap::default(),
div_map: HashMap::default(),
witness_map: HashMap::default(),
spents: HashSet::default(),
asset_types: HashMap::default(),
vk_map: HashMap::default(),
sync_status: ContextSyncStatus::Confirmed,
}
}
}
impl<U: ShieldedUtils + MaybeSend + MaybeSync> ShieldedWallet<U> {
/// Try to load the last saved shielded context from the given context
/// directory. If this fails, then leave the current context unchanged.
pub async fn load(&mut self) -> std::io::Result<()> {
self.utils.clone().load(self, false).await
}
/// Try to load the last saved confirmed shielded context from the given
/// context directory. If this fails, then leave the current context
/// unchanged.
pub async fn load_confirmed(&mut self) -> std::io::Result<()> {
self.utils.clone().load(self, true).await?;
Ok(())
}
/// Save this shielded context into its associated context directory. If the
/// state to be saved is confirmed than also delete the speculative one (if
/// available)
pub async fn save(&self) -> std::io::Result<()> {
self.utils.save(self).await
}
/// Update the merkle tree of witnesses the first time we
/// scan new MASP transactions.
pub(crate) fn update_witness_map(
&mut self,
indexed_tx: IndexedTx,
shielded: &Transaction,
) -> Result<(), eyre::Error> {
let mut note_pos = self.tree.size();
self.note_index.insert(indexed_tx, note_pos);
for so in shielded
.sapling_bundle()
.map_or(&vec![], |x| &x.shielded_outputs)
{
// Create merkle tree leaf node from note commitment
let node = Node::new(so.cmu.to_repr());
// Update each merkle tree in the witness map with the latest
// addition
for (_, witness) in self.witness_map.iter_mut() {
witness.append(node).map_err(|()| {
eyre!("note commitment tree is full".to_string())
})?;
}
self.tree.append(node).map_err(|()| {
eyre!("note commitment tree is full".to_string())
})?;
// Finally, make it easier to construct merkle paths to this new
// note
let witness = IncrementalWitness::<Node>::from_tree(&self.tree);
self.witness_map.insert(note_pos, witness);
note_pos = checked!(note_pos + 1).unwrap();
}
Ok(())
}
/// Sync the current state of the multi-asset shielded pool in a
/// ShieldedContext with the state on-chain.
pub async fn sync<M, T, I>(
&mut self,
env: impl TaskEnvironment,
config: ShieldedSyncConfig<M, T, I>,
last_query_height: Option<BlockHeight>,
sks: &[DatedSpendingKey],
fvks: &[DatedKeypair<ViewingKey>],
) -> Result<(), eyre::Error>
where
M: MaspClient + Send + Sync + Unpin + 'static,
T: ProgressBar,
I: control_flow::ShutdownSignal,
{
env.run(|spawner| async move {
let dispatcher = config.dispatcher(spawner, &self.utils).await;
if let Some(updated_ctx) =
dispatcher.run(None, last_query_height, sks, fvks).await?
{
*self = updated_ctx;
}
Ok(())
})
.await
}
pub(crate) fn min_height_to_sync_from(
&self,
) -> Result<BlockHeight, eyre::Error> {
let Some(maybe_least_synced_vk_height) =
self.vk_heights.values().min().cloned()
else {
return Err(eyre!(
"No viewing keys are available in the shielded context to \
decrypt notes with"
.to_string(),
));
};
Ok(maybe_least_synced_vk_height
.map_or_else(BlockHeight::first, |itx| itx.height))
}
#[allow(missing_docs)]
pub fn save_decrypted_shielded_outputs(
&mut self,
vk: &ViewingKey,
note_pos: usize,
note: Note,
pa: masp_primitives::sapling::PaymentAddress,
memo: MemoBytes,
) -> Result<(), eyre::Error> {
// Add this note to list of notes decrypted by this
// viewing key
self.pos_map.entry(*vk).or_default().insert(note_pos);
// Compute the nullifier now to quickly recognize when
// spent
let nf = note.nf(
&vk.nk,
note_pos
.try_into()
.map_err(|_| eyre!("Can not get nullifier".to_string()))?,
);
self.note_map.insert(note_pos, note);
self.memo_map.insert(note_pos, memo);
// The payment address' diversifier is required to spend
// note
self.div_map.insert(note_pos, *pa.diversifier());
self.nf_map.insert(nf, note_pos);
self.vk_map.insert(note_pos, *vk);
Ok(())
}
#[allow(missing_docs)]
pub fn save_shielded_spends(
&mut self,
transaction: &Transaction,
update_witness_map: bool,
) {
for ss in transaction
.sapling_bundle()
.map_or(&vec![], |x| &x.shielded_spends)
{
// If the shielded spend's nullifier is in our map, then target
// note is rendered unusable
if let Some(note_pos) = self.nf_map.get(&ss.nullifier) {
self.spents.insert(*note_pos);
if update_witness_map {
self.witness_map.swap_remove(note_pos);
}
}
}
}
/// Compute the total unspent notes associated with the viewing key in the
/// context. If the key is not in the context, then we do not know the
/// balance and hence we return None.
pub async fn compute_shielded_balance(
&mut self,
vk: &ViewingKey,
) -> Result<Option<I128Sum>, eyre::Error> {
// Cannot query the balance of a key that's not in the map
if !self.pos_map.contains_key(vk) {
return Ok(None);
}
let mut val_acc = I128Sum::zero();
// Retrieve the notes that can be spent by this key
if let Some(avail_notes) = self.pos_map.get(vk) {
for note_idx in avail_notes {
// Spent notes cannot contribute a new transaction's pool
if self.spents.contains(note_idx) {
continue;
}
// Get note associated with this ID
let note = self
.note_map
.get(note_idx)
.ok_or_else(|| eyre!("Unable to get note {note_idx}"))?;
// Finally add value to multi-asset accumulator
val_acc += I128Sum::from_nonnegative(
note.asset_type,
i128::from(note.value),
)
.map_err(|()| {
eyre!("found note with invalid value or asset type")
})?
}
}
Ok(Some(val_acc))
}
/// Try to convert as much of the given asset type-value pair using the
/// given allowed conversion. Usage is incremented by the amount of the
/// conversion used, the conversions are applied to the given input, and
/// the trace amount that could not be converted is moved from input to
/// output.
#[allow(clippy::too_many_arguments)]
async fn apply_conversion(
&mut self,
io: &impl Io,
conv: AllowedConversion,
asset_type: AssetType,
value: i128,
usage: &mut i128,
input: &mut I128Sum,
output: &mut I128Sum,
) -> Result<(), eyre::Error> {
// We do not need to convert negative values
if value <= 0 {
return Ok(());
}
// If conversion is possible, accumulate the exchanged amount
let conv: I128Sum = I128Sum::from_sum(conv.into());
// The amount required of current asset to qualify for conversion
let threshold = -conv[&asset_type];
if threshold == 0 {
edisplay_line!(
io,
"Asset threshold of selected conversion for asset type {} is \
0, this is a bug, please report it.",
asset_type
);
eyre::bail!("Conversion asset threshold cannot be null");
}
// We should use an amount of the AllowedConversion that almost
// cancels the original amount
let required = value / threshold;
// Forget about the trace amount left over because we cannot
// realize its value
let trace = I128Sum::from_pair(asset_type, value % threshold);
// Record how much more of the given conversion has been used
*usage += required;
// Apply the conversions to input and move the trace amount to output
*input += conv * required - trace.clone();
*output += trace;
Ok(())
}
/// Updates the internal state with the data of the newly generated
/// transaction. More specifically invalidate the spent notes, but do not
/// cache the newly produced output descriptions and therefore the merkle
/// tree (this is because we don't know the exact position in the tree where
/// the new notes will be appended)
pub async fn pre_cache_transaction(
&mut self,
masp_tx: &Transaction,
) -> Result<(), eyre::Error> {
self.save_shielded_spends(masp_tx, false);
// Save the speculative state for future usage
self.sync_status = ContextSyncStatus::Speculative;
self.save().await.map_err(|e| eyre!(e.to_string()))?;
Ok(())
}
}
/// A trait that allows downstream types specify how a shielded wallet
/// should interact / query a node.
pub trait ShieldedQueries<U: ShieldedUtils + MaybeSend + MaybeSync>:
std::ops::Deref<Target = ShieldedWallet<U>> + std::ops::DerefMut
{
/// Get the address of the native token
#[allow(async_fn_in_trait)]
async fn query_native_token<C: Client + Sync>(
client: &C,
) -> Result<Address, eyre::Error>;
/// Query the denomination of a token type
#[allow(async_fn_in_trait)]
async fn query_denom<C: Client + Sync>(
client: &C,
token: &Address,
) -> Option<Denomination>;
/// Query for converting assets across epochs
#[allow(async_fn_in_trait)]
async fn query_conversion<C: Client + Sync>(
client: &C,
asset_type: AssetType,
) -> Option<(
Address,
Denomination,
MaspDigitPos,
MaspEpoch,
I128Sum,
MerklePath<Node>,
)>;
/// Get the last block height
#[allow(async_fn_in_trait)]
async fn query_block<C: Client + Sync>(
client: &C,
) -> Result<Option<u64>, eyre::Error>;
/// Get the upper limit on the time to make a new block
#[allow(async_fn_in_trait)]
async fn query_max_block_time_estimate<C: Client + Sync>(
client: &C,
) -> Result<DurationSecs, eyre::Error>;
/// Query the MASP epoch
#[allow(async_fn_in_trait)]
async fn query_masp_epoch<C: Client + Sync>(
client: &C,
) -> Result<MaspEpoch, eyre::Error>;
}
/// The methods of the shielded wallet that depend on the [`ShieldedQueries`]
/// trait. These cannot be overridden downstream.
pub trait ShieldedApi<U: ShieldedUtils + MaybeSend + MaybeSync>:
ShieldedQueries<U>
{
/// Use the addresses already stored in the wallet to precompute as many
/// asset types as possible.
#[allow(async_fn_in_trait)]
async fn precompute_asset_types<C: Client + Sync>(
&mut self,
client: &C,
tokens: Vec<&Address>,
) -> Result<(), eyre::Error> {
// To facilitate lookups of human-readable token names
for token in tokens {
let Some(denom) = Self::query_denom(client, token).await else {
return Err(eyre!("denomination for token {token}"));
};
for position in MaspDigitPos::iter() {
let asset_type =
encode_asset_type(token.clone(), denom, position, None)
.map_err(|_| eyre!("unable to create asset type",))?;
self.asset_types.insert(
asset_type,
AssetData {
token: token.clone(),
denom,
position,
epoch: None,
},
);
}
}
Ok(())
}
/// Query the ledger for the decoding of the given asset type and cache it
/// if it is found.
#[allow(async_fn_in_trait)]
async fn decode_asset_type<C: Client + Sync>(
&mut self,
client: &C,
asset_type: AssetType,
) -> Option<AssetData> {
// Try to find the decoding in the cache
if let decoded @ Some(_) = self.asset_types.get(&asset_type) {
tracing::debug!(
"Asset type: {}, found cached data: {:#?}",
asset_type,
decoded
);
return decoded.cloned();
}
// Query for the conversion for the given asset type
let (token, denom, position, ep, _conv, _path): (
Address,
Denomination,
MaspDigitPos,
_,
I128Sum,
MerklePath<Node>,
) = Self::query_conversion(client, asset_type).await?;
let pre_asset_type = AssetData {
token,
denom,
position,
epoch: Some(ep),
};
self.asset_types.insert(asset_type, pre_asset_type.clone());
Some(pre_asset_type)
}
/// Query the ledger for the conversion that is allowed for the given asset
/// type and cache it. The target epoch must be greater than or equal to the
/// asset's epoch. If the target epoch is None, then convert to the latest
/// epoch.
#[allow(async_fn_in_trait)]
async fn query_allowed_conversion<'a, C: Client + Sync>(
&'a mut self,
client: &C,
asset_type: AssetType,
conversions: &'a mut Conversions,
) -> Result<(), eyre::Error> {
let btree_map::Entry::Vacant(conv_entry) =
conversions.entry(asset_type)
else {
return Ok(());
};
// Get the conversion for the given asset type, otherwise fail
let Some((token, denom, position, ep, conv, path)) =
Self::query_conversion(client, asset_type).await
else {
return Ok(());
};
let asset_data = AssetData {
token,
denom,
position,
epoch: Some(ep),
};
self.asset_types.insert(asset_type, asset_data.clone());
// If the conversion is 0, then we just have a pure decoding
if !conv.is_zero() {
conv_entry.insert((conv.into(), path, 0));
}
Ok(())
}
/// Convert the given amount into the latest asset types whilst making a
/// note of the conversions that were used. Note that this function does
/// not assume that allowed conversions from the ledger are expressed in
/// terms of the latest asset types.
#[allow(async_fn_in_trait)]
async fn compute_exchanged_amount(
&mut self,
client: &(impl Client + Sync),
io: &impl Io,
mut input: I128Sum,
mut conversions: Conversions,
) -> Result<(I128Sum, Conversions), eyre::Error> {
// Where we will store our exchanged value
let mut output = I128Sum::zero();
// Repeatedly exchange assets until it is no longer possible
while let Some(asset_type) = input.asset_types().next().cloned() {
self.query_allowed_conversion(client, asset_type, &mut conversions)
.await?;
// Consolidate the current amount with any dust from output.
// Whatever is not used is moved back to output anyway.
let dust = output.project(asset_type);
input += dust.clone();
output -= dust;
// Now attempt to apply conversions
if let Some((conv, _wit, usage)) = conversions.get_mut(&asset_type)
{
display_line!(
io,
"converting current asset type to latest asset type..."
);
// Not at the target asset type, not at the latest asset type.
// Apply conversion to get from current asset type to the latest
// asset type.
self.apply_conversion(
io,
conv.clone(),
asset_type,
input[&asset_type],
usage,
&mut input,
&mut output,
)
.await?;
} else {
// At the target asset type. Then move component over to output.
let comp = input.project(asset_type);
output += comp.clone();
input -= comp;
}
}
Ok((output, conversions))
}
/// Compute the total unspent notes associated with the viewing key in the
/// context and express that value in terms of the currently timestamped
/// asset types. If the key is not in the context, then we do not know the
/// balance and hence we return None.
#[allow(async_fn_in_trait)]
async fn compute_exchanged_balance(
&mut self,
client: &(impl Client + Sync),
io: &impl Io,
vk: &ViewingKey,
) -> Result<Option<I128Sum>, eyre::Error> {
// First get the unexchanged balance
if let Some(balance) = self.compute_shielded_balance(vk).await? {
let exchanged_amount = self
.compute_exchanged_amount(client, io, balance, BTreeMap::new())
.await?
.0;
// And then exchange balance into current asset types
Ok(Some(exchanged_amount))
} else {
Ok(None)
}
}
/// Determine if using the current note would actually bring us closer to
/// our target. Returns the contribution of the current note to the
/// target if so.
#[allow(async_fn_in_trait)]
async fn is_amount_required(
&mut self,
client: &(impl Client + Sync),
// NB: value accumulated thus far
src: ValueSum<(MaspDigitPos, Address), i128>,
// NB: the target amount remaining
dest: ValueSum<(MaspDigitPos, Address), i128>,
// NB: current contribution (from a note + rewards if any)
delta: I128Sum,
) -> Option<ValueSum<(MaspDigitPos, Address), i128>> {
// If the delta causes any regression, then do not use it
if delta < I128Sum::zero() {
return None;
}
let gap = dest.clone() - src;
// Decode the assets in delta; any undecodable assets
// will end up in `_rem_delta`
let (decoded_delta, _rem_delta) = self.decode_sum(client, delta).await;
// Find any component in the delta that may help
// close the gap with dest
let any_component_closes_gap =
decoded_delta.components().any(|((_, asset_data), value)| {
*value > 0
&& gap
.get(&(asset_data.position, asset_data.token.clone()))
.is_positive()
});
if any_component_closes_gap {
// Convert the delta into Namada amounts
let converted_delta = decoded_delta.components().fold(
ValueSum::zero(),
|accum, ((_, asset_data), value)| {
accum
+ ValueSum::from_pair(
(asset_data.position, asset_data.token.clone()),
*value,
)
},
);
Some(converted_delta)
} else {
None
}
}
/// We estimate the next epoch rewards accumulated by the assets included in
/// the provided raw balance, i.e. a balance based only on the available
/// notes, without accounting for any conversions. The estimation is done by
/// assuming the same rewards rate on each asset as in the latest masp
/// epoch.
#[allow(async_fn_in_trait)]
async fn estimate_next_epoch_rewards(
&mut self,
context: &impl NamadaIo,
raw_balance: &I128Sum,
) -> Result<DenominatedAmount, eyre::Error> {
let native_token = Self::query_native_token(context.client()).await?;
let native_token_denom =
Self::query_denom(context.client(), &native_token)
.await
.ok_or_else(|| {
eyre!(
"Could not retrieve the denomination of the native \
token"
)
})?;
let epoch_zero = MaspEpoch::zero();
let current_epoch = Self::query_masp_epoch(context.client()).await?;
let previous_epoch = match current_epoch.prev() {
Some(prev) => prev,
// We are currently at MaspEpoch(0) and there are no conversions yet
// at this point
None => return Ok(DenominatedAmount::native(Amount::zero())),
};
let next_epoch = current_epoch
.next()
.ok_or_else(|| eyre!("The final MASP epoch is already afoot."))?;
// Get the current amount, this serves as the reference point to
// estimate future rewards
let current_exchanged_balance = self
.compute_exchanged_amount(
context.client(),
context.io(),
raw_balance.to_owned(),
Conversions::new(),
)
.await?
.0;
let mut latest_conversions = Conversions::new();
// We need to query conversions for the latest assets in the current
// exchanged balance. For these assets there are no conversions yet so
// we need to see if there are conversions for the previous epoch
for (asset_type, _) in current_exchanged_balance.components() {
let asset = match self
.decode_asset_type(context.client(), *asset_type)
.await
{
Some(
data @ AssetData {
epoch: Some(ep), ..
},
) if ep == current_epoch => data,
_ => continue,
};
let redated_asset_type = asset.redate(previous_epoch).encode()?;
self.query_allowed_conversion(
context.client(),
redated_asset_type,
&mut latest_conversions,
)
.await?;
}
let mut estimated_next_epoch_conversions = Conversions::new();
// re-date the all the latest conversions up one epoch
for (asset_type, (conv, wit, _)) in latest_conversions {
let asset = self
.decode_asset_type(context.client(), asset_type)
.await
.ok_or_else(|| {
eyre!(
"Could not decode conversion asset type {}",
asset_type
)
})?;
let decoded_conv = self
.decode_sum(context.client(), conv.clone().into())
.await
.0;
let mut est_conv = I128Sum::zero();
for ((_, mut asset_data), val) in decoded_conv.into_components() {
// We must upconvert the components of the conversion if
// this conversion is for the native token or the component
// itself is not the native token. If instead the conversion
// component is the native token and it is for a non-native
// token, then we should avoid upconverting it
// since conversions for non-native tokens must
// always refer to a specific epoch (MaspEpoch(0)) native token
if asset.token == native_token
|| asset_data.token != native_token
{
asset_data = asset_data.redate_to_next_epoch();
}
est_conv += ValueSum::from_pair(asset_data.encode()?, val)
}
estimated_next_epoch_conversions.insert(
asset.redate_to_next_epoch().encode().unwrap(),
(AllowedConversion::from(est_conv), wit.clone(), 0),
);
}
// Get the estimated future balance based on the new conversions
let next_exchanged_balance = self
.compute_exchanged_amount(
context.client(),
context.io(),
current_exchanged_balance.clone(),
estimated_next_epoch_conversions,
)
.await?
.0;
// Extract only the native token balance for rewards. Depending on
// rewards being enabled for the native token or not, we'll find the
// balance we look for at either epoch 0 or the current epoch. If
// rewards are not enabled for the native token we might have
// balances at any epochs in between these two. These would be
// guaranteed to be the same in both the exchanged amounts we've
// computed here above. This means they are irrelevant for the
// estimation of the next epoch rewards since they would cancel out
// anyway
let mut current_native_balance = ValueSum::<AssetType, i128>::zero();
let mut next_native_balance = ValueSum::<AssetType, i128>::zero();
for epoch in [epoch_zero, current_epoch, next_epoch] {
for position in MaspDigitPos::iter() {
let native_asset_epoch0 = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position,
epoch: Some(epoch_zero),
};
let native_asset_epoch0_type = native_asset_epoch0
.encode()
.map_err(|_| eyre!("unable to create asset type"))?;
let native_asset = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position,
epoch: Some(epoch),
};
let native_asset_type = native_asset
.encode()
.map_err(|_| eyre!("unable to create asset type"))?;
// Pre-date all the assets to MaspEpoch(0) for comparison
if let Some((_, amt)) = current_exchanged_balance
.project(native_asset_type)
.into_components()
.last()
{
current_native_balance +=
ValueSum::from_pair(native_asset_epoch0_type, amt);
}
if let Some((_, amt)) = next_exchanged_balance
.project(native_asset_type)
.into_components()
.last()
{
next_native_balance +=
ValueSum::from_pair(native_asset_epoch0_type, amt);
}
}
}
let rewards = next_native_balance - current_native_balance;
let decoded_rewards =
self.decode_sum(context.client(), rewards).await.0;
decoded_rewards
.into_components()
.try_fold(
Amount::zero(),
|acc,
(
(
_,
AssetData {
token,
denom: _,
position,
epoch,
},
),
amt,
)| {
// Sanity checks, the rewards must be given in the native
// asset at masp epoch 0
if token != native_token {
return Err(eyre!(
"Found reward asset other than the native token"
));
}
match epoch {
Some(ep) if ep == epoch_zero => (),
_ => {
return Err(eyre!(
"Found reward asset with an epoch different \
than the 0th"
));
}
}
let amt = Amount::from_masp_denominated_i128(amt, position)
.ok_or_else(|| {
eyre!("Could not convert MASP reward to amount")
})?;
checked!(acc + amt)
.wrap_err("Overflow in MASP reward computation")
},
)
.map(DenominatedAmount::native)
}
/// Collect enough unspent notes in this context to exceed the given amount
/// of the specified asset type. Return the total value accumulated plus
/// notes and the corresponding diversifiers/merkle paths that were used to
/// achieve the total value. Updates the changes map.
#[allow(clippy::too_many_arguments)]
#[allow(async_fn_in_trait)]
async fn collect_unspent_notes(
&mut self,
context: &impl NamadaIo,
spent_notes: &mut SpentNotesTracker,
sk: PseudoExtendedKey,
target: ValueSum<(MaspDigitPos, Address), i128>,
) -> Result<
(
I128Sum,
Vec<(Diversifier, Note, MerklePath<Node>)>,
Conversions,
),
eyre::Error,
> {
let vk = &sk.to_viewing_key().fvk.vk;
// TODO: we should try to use the smallest notes possible to fund the
// transaction to allow people to fetch less often
// Establish connection with which to do exchange rate queries
let mut conversions = BTreeMap::new();
let mut namada_acc = ValueSum::zero();
let mut masp_acc = I128Sum::zero();
let mut notes = Vec::new();
// Retrieve the notes that can be spent by this key
if let Some(avail_notes) = self.pos_map.get(vk).cloned() {
for note_idx in &avail_notes {
// Skip spend notes already used in this transaction
if spent_notes
.get(vk)
.is_some_and(|set| set.contains(note_idx))
{
continue;
}
// No more transaction inputs are required once we have met
// the target amount
if namada_acc >= target {
break;
}
// Spent notes from the shielded context (i.e. from previous
// transactions) cannot contribute a new transaction's pool
if self.spents.contains(note_idx) {
continue;
}
// Get note, merkle path, diversifier associated with this ID
let note = *self
.note_map
.get(note_idx)
.ok_or_else(|| eyre!("Unable to get note {note_idx}"))?;
// The amount contributed by this note before conversion
let pre_contr =
I128Sum::from_pair(note.asset_type, i128::from(note.value));
let (contr, proposed_convs) = self
.compute_exchanged_amount(
context.client(),
context.io(),
pre_contr,
conversions.clone(),
)
.await?;
// Use this note only if it brings us closer to our target
if let Some(namada_contr) = self
.is_amount_required(
context.client(),
namada_acc.clone(),
target.clone(),
contr.clone(),
)
.await
{
// Be sure to record the conversions used in computing
// accumulated value
masp_acc += contr;
namada_acc += namada_contr;
// Commit the conversions that were used to exchange
conversions = proposed_convs;
let merkle_path = self
.witness_map
.get(note_idx)
.ok_or_else(|| eyre!("Unable to get note {note_idx}"))?
.path()
.ok_or_else(|| {
eyre!("Unable to get path: {}", line!())
})?;
let diversifier =
self.div_map.get(note_idx).ok_or_else(|| {
eyre!("Unable to get note {note_idx}")
})?;
// Commit this note to our transaction
notes.push((*diversifier, note, merkle_path));
// Append the note the list of used ones
spent_notes
.entry(vk.to_owned())
.and_modify(|set| {
set.insert(*note_idx);
})
.or_insert([*note_idx].into_iter().collect());
}
}
}
Ok((masp_acc, notes, conversions))
}
/// Convert an amount whose units are AssetTypes to one whose units are
/// Addresses that they decode to. All asset types not corresponding to
/// the given epoch are ignored.
#[allow(async_fn_in_trait)]
async fn decode_combine_sum_to_epoch<C: Client + Sync>(
&mut self,
client: &C,
amt: I128Sum,
target_epoch: MaspEpoch,
) -> (ValueSum<Address, Change>, I128Sum) {
let mut res = ValueSum::zero();
let mut undecoded = ValueSum::zero();
for (asset_type, val) in amt.components() {
// Decode the asset type
let decoded = self.decode_asset_type(client, *asset_type).await;
// Only assets with the target timestamp count
match decoded {
Some(pre_asset_type)
if pre_asset_type
.epoch
.map_or(true, |epoch| epoch <= target_epoch) =>
{
let decoded_change = Change::from_masp_denominated(
*val,
pre_asset_type.position,
)
.expect("expected this to fit");
res += ValueSum::from_pair(
pre_asset_type.token,
decoded_change,
);
}
None => {
undecoded += ValueSum::from_pair(*asset_type, *val);
}
_ => {}
}
}
(res, undecoded)
}
/// Convert an amount whose units are AssetTypes to one whose units are
/// Addresses that they decode to and combine the denominations.
#[allow(async_fn_in_trait)]
async fn decode_combine_sum<C: Client + Sync>(
&mut self,
client: &C,
amt: I128Sum,
) -> (MaspAmount, I128Sum) {
let mut res = MaspAmount::zero();
let mut undecoded = ValueSum::zero();
for (asset_type, val) in amt.components() {
// Decode the asset type
if let Some(decoded) =
self.decode_asset_type(client, *asset_type).await
{
let decoded_change =
Change::from_masp_denominated(*val, decoded.position)
.expect("expected this to fit");
res += MaspAmount::from_pair(
(decoded.epoch, decoded.token),
decoded_change,
);
} else {
undecoded += ValueSum::from_pair(*asset_type, *val);
}
}
(res, undecoded)
}
/// Convert an amount whose units are AssetTypes to one whose units are
/// Addresses that they decode to.
#[allow(async_fn_in_trait)]
async fn decode_sum<C: Client + Sync>(
&mut self,
client: &C,
amt: I128Sum,
) -> (ValueSum<(AssetType, AssetData), i128>, I128Sum) {
let mut res = ValueSum::zero();
let mut rem = ValueSum::zero();
for (asset_type, val) in amt.components() {
// Decode the asset type
if let Some(decoded) =
self.decode_asset_type(client, *asset_type).await
{
res += ValueSum::from_pair((*asset_type, decoded), *val);
} else {
rem += ValueSum::from_pair(*asset_type, *val);
}
}
(res, rem)
}
/// Make shielded components to embed within a Transfer object. If no
/// shielded payment address nor spending key is specified, then no
/// shielded components are produced. Otherwise, a transaction containing
/// nullifiers and/or note commitments are produced. Dummy transparent
/// UTXOs are sometimes used to make transactions balanced, but it is
/// understood that transparent account changes are effected only by the
/// amounts and signatures specified by the containing Transfer object.
#[allow(async_fn_in_trait)]
async fn gen_shielded_transfer(
&mut self,
context: &impl NamadaIo,
data: Vec<MaspTransferData>,
fee_data: Option<MaspFeeData>,
expiration: Option<DateTimeUtc>,
bparams: &mut impl BuildParams,
) -> Result<Option<ShieldedTransfer>, TransferErr> {
// Determine epoch in which to submit potential shielded transaction
let epoch = Self::query_masp_epoch(context.client())
.await
.map_err(|e| TransferErr::General(e.to_string()))?;
// Try to get a seed from env var, if any.
#[allow(unused_mut)]
let mut rng = StdRng::from_rng(OsRng).unwrap();
#[cfg(feature = "testing")]
let mut rng = if let Ok(seed) = std::env::var(ENV_VAR_MASP_TEST_SEED)
.map_err(|e| TransferErr::General(e.to_string()))
.and_then(|seed| {
let exp_str =
format!("Env var {ENV_VAR_MASP_TEST_SEED} must be a u64.");
let parsed_seed: u64 =
seed.parse().map_err(|_| TransferErr::General(exp_str))?;
Ok(parsed_seed)
}) {
tracing::warn!(
"UNSAFE: Using a seed from {ENV_VAR_MASP_TEST_SEED} env var \
to build proofs."
);
StdRng::seed_from_u64(seed)
} else {
rng
};
// TODO: if the user requested the default expiration, there might be a
// small discrepancy between the datetime we calculate here and the one
// we set for the transaction (since we compute two different
// DateTimeUtc::now()). This should be small enough to not cause
// any issue, in case refactor the build process to compute a single
// expiration at the beginning and use it both here and for the
// transaction
let expiration_height: u32 = match expiration {
Some(expiration) => {
// Try to match a DateTime expiration with a plausible
// corresponding block height
let last_block_height = Self::query_block(context.client())
.await
.map_err(|e| TransferErr::General(e.to_string()))?
.unwrap_or(1);
let max_block_time =
Self::query_max_block_time_estimate(context.client())
.await
.map_err(|e| TransferErr::General(e.to_string()))?;
#[allow(clippy::disallowed_methods)]
let current_time = DateTimeUtc::now();
let delta_time =
expiration.0.signed_duration_since(current_time.0);
let delta_blocks = u32::try_from(
delta_time.num_seconds()
/ i64::try_from(max_block_time.0).unwrap(),
)
.map_err(|e| TransferErr::General(e.to_string()))?;
u32::try_from(last_block_height)
.map_err(|e| TransferErr::General(e.to_string()))?
+ delta_blocks
}
None => {
// NOTE: The masp library doesn't support optional
// expiration so we set the max to mimic
// a never-expiring tx. We also need to
// remove 20 which is going to be added back by the builder
u32::MAX - 20
}
};
let mut builder = Builder::<Network, PseudoExtendedKey>::new(
NETWORK,
// NOTE: this is going to add 20 more blocks to the actual
// expiration but there's no other exposed function that we could
// use from the masp crate to specify the expiration better
expiration_height.into(),
);
let mut notes_tracker = SpentNotesTracker::new();
{
// Load the current shielded context given
// the spending key we possess
let _ = self.load().await;
}
let Some(MaspTxReorderedData {
source_data,
target_data,
mut denoms,
}) = Self::reorder_data_for_masp_transfer(context, data, fee_data)
.await?
else {
// No shielded components are needed when neither source nor
// destination are shielded
return Ok(None);
};
for (MaspSourceTransferData { source, token }, amount) in &source_data {
self.add_inputs(
context,
&mut builder,
source,
token,
amount,
epoch,
&mut denoms,
&mut notes_tracker,
)
.await?;
}
for (
MaspTargetTransferData {
source,
target,
token,
},
amount,
) in target_data
{
self.add_outputs(
context,
&mut builder,
source,
&target,
token,
amount,
epoch,
&mut denoms,
)
.await?;
}
// Final safety check on the value balance to verify that the
// transaction is balanced
let value_balance = builder.value_balance();
if !value_balance.is_zero() {
let mut batch: Vec<MaspDataLogEntry> = vec![];
for (asset_type, value) in value_balance.components() {
let AssetData {
token,
denom,
position,
..
} = self
.decode_asset_type(context.client(), *asset_type)
.await
.expect(
"Every asset type in the builder must have a known \
pre-image",
);
let denominated = DenominatedAmount::new(
Amount::from_masp_denominated_i128(*value, position)
.ok_or_else(|| {
TransferErr::General(
"Masp digit overflow".to_owned(),
)
})?,
denom,
);
if let Some(entry) =
batch.iter_mut().find(|entry| entry.token == token)
{
checked!(entry.shortfall += denominated)
.map_err(|e| TransferErr::General(e.to_string()))?;
} else {
batch.push(MaspDataLogEntry {
token,
shortfall: denominated,
});
}
}
return Err(TransferErr::InsufficientFunds(batch.into()));
}
let builder_clone = builder.clone().map_builder(WalletMap);
// Build and return the constructed transaction
#[cfg(not(feature = "testing"))]
let prover = self.utils.local_tx_prover();
#[cfg(feature = "testing")]
let prover = testing::MockTxProver(std::sync::Mutex::new(OsRng));
let (masp_tx, metadata) = builder
.build(
&prover,
&FeeRule::non_standard(U64Sum::zero()),
&mut rng,
bparams,
)
.map_err(|error| TransferErr::Build { error })?;
Ok(Some(ShieldedTransfer {
builder: builder_clone,
masp_tx,
metadata,
epoch,
}))
}
/// Either get the denomination from the cache or query it
#[allow(async_fn_in_trait)]
async fn get_denom(
client: &(impl Client + Sync),
denoms: &mut HashMap<Address, Denomination>,
token: &Address,
) -> Result<Denomination, TransferErr> {
if let Some(denom) = denoms.get(token) {
Ok(*denom)
} else if let Some(denom) = Self::query_denom(client, token).await {
denoms.insert(token.clone(), denom);
Ok(denom)
} else {
Err(TransferErr::General(format!(
"Could not find the denomination of token {token}"
)))
}
}
/// Group all the information for every source/token and target/token
/// couple, and extract the denominations for all the tokens involved
/// (expect the one involved in the fees if needed). This step is
/// required so that we can collect the amount required for every couple
/// and pass it to the appropriate function so that notes can be
/// collected based on the correct amount.
#[allow(async_fn_in_trait)]
async fn reorder_data_for_masp_transfer(
context: &impl NamadaIo,
data: Vec<MaspTransferData>,
fee_data: Option<MaspFeeData>,
) -> Result<Option<MaspTxReorderedData>, TransferErr> {
let mut source_data = HashMap::<MaspSourceTransferData, Amount>::new();
let mut target_data = HashMap::<MaspTargetTransferData, Amount>::new();
let mut denoms = HashMap::new();
// If present, add the fee data to the rest of the transfer data
if let Some(fee_data) = fee_data {
let denom =
Self::get_denom(context.client(), &mut denoms, &fee_data.token)
.await?;
let amount = fee_data
.amount
.increase_precision(denom)
.map_err(|e| TransferErr::General(e.to_string()))?
.amount();
if let Some(source) = fee_data.source {
source_data.insert(
MaspSourceTransferData {
source: TransferSource::ExtendedKey(source),
token: fee_data.token.clone(),
},
amount,
);
}
target_data.insert(
MaspTargetTransferData {
source: fee_data.source.map(TransferSource::ExtendedKey),
target: TransferTarget::Address(fee_data.target),
token: fee_data.token,
},
amount,
);
}
for MaspTransferData {
source,
target,
token,
amount,
} in data
{
let spending_key = source.spending_key();
let payment_address = target.payment_address();
// No shielded components are needed when neither source nor
// destination are shielded
if spending_key.is_none() && payment_address.is_none() {
return Ok(None);
}
let denom =
Self::get_denom(context.client(), &mut denoms, &token).await?;
let amount = amount
.increase_precision(denom)
.map_err(|e| TransferErr::General(e.to_string()))?
.amount();
let key = MaspSourceTransferData {
source: source.clone(),
token: token.clone(),
};
match source_data.get_mut(&key) {
Some(prev_amount) => {
*prev_amount = checked!(prev_amount.to_owned() + amount)
.map_err(|e| TransferErr::General(e.to_string()))?;
}
None => {
source_data.insert(key, amount);
}
}
let key = MaspTargetTransferData {
source: Some(source),
target,
token,
};
match target_data.get_mut(&key) {
Some(prev_amount) => {
*prev_amount = checked!(prev_amount.to_owned() + amount)
.map_err(|e| TransferErr::General(e.to_string()))?;
}
None => {
target_data.insert(key, amount);
}
}
}
Ok(Some(MaspTxReorderedData {
source_data,
target_data,
denoms,
}))
}
/// Computes added_amt - required_amt taking care of denominations and asset
/// decodings. Error out if required_amt is not less than added_amt.
#[allow(async_fn_in_trait)]
async fn compute_change(
&mut self,
client: &(impl Client + Sync),
added_amt: I128Sum,
mut required_amt: ValueSum<(MaspDigitPos, Address), i128>,
denoms: &mut HashMap<Address, Denomination>,
) -> Result<I128Sum, TransferErr> {
// Compute the amount of change due to the sender.
let (decoded_amount, mut change) =
self.decode_sum(client, added_amt.clone()).await;
for ((asset_type, asset_data), value) in decoded_amount.components() {
// Get current component of the required amount
let req = required_amt
.get(&(asset_data.position, asset_data.token.clone()));
// Compute how much this decoded component covers of the requirement
let covered = std::cmp::min(req, *value);
// Record how far in excess of the requirement we are. This is
// change.
change += ValueSum::from_pair(*asset_type, value - covered);
// Denominate the cover and decrease the required amount accordingly
required_amt -= ValueSum::from_pair(
(asset_data.position, asset_data.token.clone()),
covered,
);
}
// Error out if the required amount was not covered by the added amount
if !required_amt.is_zero() {
let mut batch: Vec<MaspDataLogEntry> = vec![];
for ((position, token), value) in required_amt.components() {
let denom = Self::get_denom(client, denoms, token).await?;
let denominated = DenominatedAmount::new(
Amount::from_masp_denominated_i128(*value, *position)
.ok_or_else(|| {
TransferErr::General(
"Masp digit overflow".to_owned(),
)
})?,
denom,
);
if let Some(entry) =
batch.iter_mut().find(|entry| entry.token == *token)
{
checked!(entry.shortfall += denominated)
.map_err(|e| TransferErr::General(e.to_string()))?;
} else {
batch.push(MaspDataLogEntry {
token: token.clone(),
shortfall: denominated,
});
}
}
return Err(TransferErr::InsufficientFunds(batch.into()));
}
Ok(change)
}
/// Add the necessary transaction inputs to the builder. The supplied epoch
/// must be the current epoch.
#[allow(async_fn_in_trait)]
#[allow(clippy::too_many_arguments)]
async fn add_inputs(
&mut self,
context: &impl NamadaIo,
builder: &mut Builder<Network, PseudoExtendedKey>,
source: &TransferSource,
token: &Address,
amount: &Amount,
epoch: MaspEpoch,
denoms: &mut HashMap<Address, Denomination>,
notes_tracker: &mut SpentNotesTracker,
) -> Result<Option<I128Sum>, TransferErr> {
// We want to fund our transaction solely from supplied spending key
let spending_key = source.spending_key();
// Now we build up the transaction within this object
// Compute transparent output asset types in case they are required and
// save them to facilitate decodings.
let denom = denoms.get(token).unwrap();
let mut transparent_asset_types = Vec::new();
for digit in MaspDigitPos::iter() {
let mut pre_asset_type = AssetData {
epoch: Some(epoch),
token: token.clone(),
denom: *denom,
position: digit,
};
let asset_type = self
.get_asset_type(context.client(), &mut pre_asset_type)
.await
.map_err(|e| TransferErr::General(e.to_string()))?;
transparent_asset_types.push((digit, asset_type));
}
let _ = self.save().await;
// If there are shielded inputs
let added_amt = if let Some(sk) = spending_key {
// Compute the target amount to spend from the
// input token address and namada amount. We
// collect all words from the namada amount
// whose values are non-zero, and pair them
// with their corresponding masp digit position.
let required_amt = amount
.iter_words()
.zip(MaspDigitPos::iter())
.filter_map(|(value, masp_digit_pos)| {
if value != 0 {
Some((masp_digit_pos, i128::from(value)))
} else {
None
}
})
.fold(
ValueSum::zero(),
|mut accum, (masp_digit_pos, value)| {
accum += ValueSum::from_pair(
(masp_digit_pos, token.clone()),
value,
);
accum
},
);
// Locate unspent notes that can help us meet the transaction
// amount
let (added_amt, unspent_notes, used_convs) = self
.collect_unspent_notes(
context,
notes_tracker,
sk,
required_amt.clone(),
)
.await
.map_err(|e| TransferErr::General(e.to_string()))?;
// Compute the change that needs to go back to the sender
let change = self
.compute_change(
context.client(),
added_amt.clone(),
required_amt,
denoms,
)
.await?;
// Commit the computed change back to the sender.
for (asset_type, value) in change.components() {
builder
.add_sapling_output(
Some(sk.to_viewing_key().fvk.ovk),
sk.to_viewing_key().default_address().1,
*asset_type,
*value as u64,
MemoBytes::empty(),
)
.map_err(|e| TransferErr::Build {
error: builder::Error::SaplingBuild(e),
})?;
}
// Commit the notes found to our transaction
for (diversifier, note, merkle_path) in unspent_notes {
builder
.add_sapling_spend(sk, diversifier, note, merkle_path)
.map_err(|e| TransferErr::Build {
error: builder::Error::SaplingBuild(e),
})?;
}
// Commit the conversion notes used during summation
for (conv, wit, value) in used_convs.values() {
if value.is_positive() {
builder
.add_sapling_convert(
conv.clone(),
*value as u64,
wit.clone(),
)
.map_err(|e| TransferErr::Build {
error: builder::Error::SaplingBuild(e),
})?;
}
}
Some(added_amt)
} else {
// We add a dummy UTXO to our transaction, but only the source
// of the parent Transfer object is used to
// validate fund availability
let script = source
.t_addr_data()
.ok_or_else(|| {
TransferErr::General(
"Source address should be transparent".into(),
)
})?
.taddress();
for (digit, asset_type) in transparent_asset_types {
let amount_part = digit.denominate(amount);
// Skip adding an input if its value is 0
if amount_part != 0 {
builder
.add_transparent_input(TxOut {
asset_type,
value: amount_part,
address: script,
})
.map_err(|e| TransferErr::Build {
error: builder::Error::TransparentBuild(e),
})?;
}
}
None
};
Ok(added_amt)
}
/// Add the necessary transaction outputs to the builder
#[allow(clippy::too_many_arguments)]
#[allow(async_fn_in_trait)]
async fn add_outputs(
&mut self,
context: &impl NamadaIo,
builder: &mut Builder<Network, PseudoExtendedKey>,
source: Option<TransferSource>,
target: &TransferTarget,
token: Address,
amount: Amount,
epoch: MaspEpoch,
denoms: &mut HashMap<Address, Denomination>,
) -> Result<(), TransferErr> {
// Anotate the asset type in the value balance with its decoding in
// order to facilitate cross-epoch computations
let (value_balance, rem_balance) = self
.decode_sum(context.client(), builder.value_balance())
.await;
assert!(
rem_balance.is_zero(),
"no undecodable asset types should remain at this point",
);
let payment_address = target.payment_address();
// This indicates how many more assets need to be sent to the
// receiver in order to satisfy the requested transfer
// amount.
let mut rem_amount = amount.raw_amount().0;
let denom = Self::get_denom(context.client(), denoms, &token).await?;
// Now handle the outputs of this transaction
// Loop through the value balance components and see which
// ones can be given to the receiver
for ((asset_type, decoded), val) in value_balance.components() {
let rem_amount = &mut rem_amount[decoded.position as usize];
// Only asset types with the correct token can contribute. But
// there must be a demonstrated need for it.
if decoded.token == token
&& decoded.denom == denom
&& decoded.epoch.map_or(true, |vbal_epoch| vbal_epoch <= epoch)
&& *rem_amount > 0
{
let val = u128::try_from(*val).expect(
"value balance in absence of output descriptors should be \
non-negative",
);
// We want to take at most the remaining quota for the
// current denomination to the receiver
let contr = std::cmp::min(u128::from(*rem_amount), val) as u64;
// If we are sending to a shielded address, we need the outgoing
// viewing key in the following computations.
let ovk_opt = source.clone().and_then(|source| {
source.spending_key().map(|x| x.to_viewing_key().fvk.ovk)
});
// Make transaction output tied to the current token,
// denomination, and epoch.
if let Some(pa) = payment_address {
// If there is a shielded output
builder
.add_sapling_output(
ovk_opt,
pa.into(),
*asset_type,
contr,
MemoBytes::empty(),
)
.map_err(|e| TransferErr::Build {
error: builder::Error::SaplingBuild(e),
})?;
} else if let Some(t_addr_data) = target.t_addr_data() {
// If there is a transparent output
builder
.add_transparent_output(
&t_addr_data.taddress(),
*asset_type,
contr,
)
.map_err(|e| TransferErr::Build {
error: builder::Error::TransparentBuild(e),
})?;
} else {
return Result::Err(TransferErr::General(
"Transaction target must be a payment address or \
Namada address or IBC address"
.to_string(),
));
}
// Lower what is required of the remaining contribution
*rem_amount -= contr;
}
}
// Nothing must remain to be included in output
if rem_amount != [0; 4] {
return Result::Err(TransferErr::InsufficientFunds(
vec![MaspDataLogEntry {
token,
shortfall: DenominatedAmount::new(
namada_core::uint::Uint(rem_amount).into(),
denom,
),
}]
.into(),
));
}
Ok(())
}
/// Get the asset type with the given epoch, token, and denomination. If it
/// does not exist in the protocol, then remove the timestamp. Make sure to
/// store the derived AssetType so that future decoding is possible.
#[allow(async_fn_in_trait)]
async fn get_asset_type<C: Client + Sync>(
&mut self,
client: &C,
decoded: &mut AssetData,
) -> Result<AssetType, eyre::Error> {
let mut asset_type = decoded
.encode()
.map_err(|_| eyre!("unable to create asset type"))?;
if self.decode_asset_type(client, asset_type).await.is_none() {
// If we fail to decode the epoched asset type, then remove the
// epoch
tracing::debug!(
"Failed to decode epoched asset type, undating it: {:#?}",
decoded
);
*decoded = decoded.clone().undate();
asset_type = decoded
.encode()
.map_err(|_| eyre!("unable to create asset type"))?;
self.asset_types.insert(asset_type, decoded.clone());
}
Ok(asset_type)
}
/// Convert Namada amount and token type to MASP equivalents
#[allow(async_fn_in_trait)]
async fn convert_namada_amount_to_masp<C: Client + Sync>(
&mut self,
client: &C,
epoch: MaspEpoch,
token: &Address,
denom: Denomination,
val: Amount,
) -> Result<([AssetType; 4], U64Sum), eyre::Error> {
let mut amount = U64Sum::zero();
let mut asset_types = Vec::new();
for position in MaspDigitPos::iter() {
let mut pre_asset_type = AssetData {
epoch: Some(epoch),
token: token.clone(),
denom,
position,
};
let asset_type =
self.get_asset_type(client, &mut pre_asset_type).await?;
// Combine the value and unit into one amount
amount +=
U64Sum::from_nonnegative(asset_type, position.denominate(&val))
.map_err(|_| eyre!("invalid value for amount"))?;
asset_types.push(asset_type);
}
Ok((
asset_types
.try_into()
.expect("there must be exactly 4 denominations"),
amount,
))
}
}
impl<U: ShieldedUtils + MaybeSend + MaybeSync, T: ShieldedQueries<U>>
ShieldedApi<U> for T
{
}
#[cfg(test)]
mod test_shielded_wallet {
use namada_core::address::InternalAddress;
use namada_core::borsh::BorshSerializeExt;
use namada_core::masp::AssetData;
use namada_core::token::MaspDigitPos;
use namada_io::NamadaIo;
use proptest::proptest;
use tempfile::tempdir;
use super::*;
use crate::masp::fs::FsShieldedUtils;
use crate::masp::test_utils::{
arbitrary_pa, arbitrary_vk, create_note, MockNamadaIo, TestingContext,
};
#[tokio::test]
async fn test_compute_shielded_balance() {
let (_client_channel, context) = MockNamadaIo::new();
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let mut asset_data = AssetData {
token: native_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: None,
};
// check that if no notes are found, None is returned
let balance = wallet
.compute_shielded_balance(&vk)
.await
.expect("Test failed");
assert!(balance.is_none());
// check that the correct balance if found for a single note
wallet.add_note(create_note(asset_data.clone(), 10, pa), vk);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.expect("Test failed")
.expect("Test failed");
let expected =
I128Sum::from_nonnegative(asset_data.encode().unwrap(), 10)
.expect("Test failed");
assert_eq!(balance, expected);
// check that multiple notes of the same asset are added together
let new_note = create_note(asset_data.clone(), 11, pa);
wallet.add_note(new_note, vk);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.expect("Test failed")
.expect("Test failed");
let expected =
I128Sum::from_nonnegative(asset_data.encode().unwrap(), 21)
.expect("Test failed");
assert_eq!(balance, expected);
// check that spending a note works correctly
wallet.spend_note(&new_note);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.expect("Test failed")
.expect("Test failed");
let expected =
I128Sum::from_nonnegative(asset_data.encode().unwrap(), 10)
.expect("Test failed");
assert_eq!(balance, expected);
// check that the balance does not add together non-fungible asset types
asset_data.epoch = Some(MaspEpoch::new(1));
wallet.add_note(create_note(asset_data.clone(), 7, pa), vk);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.expect("Test failed")
.expect("Test failed");
let expected = expected
+ I128Sum::from_nonnegative(asset_data.encode().unwrap(), 7)
.expect("Test failed");
assert_eq!(balance, expected);
assert_eq!(balance.components().count(), 2);
// check that a missing index causes an error
wallet.note_map.clear();
assert!(wallet.compute_shielded_balance(&vk).await.is_err())
}
// Test that `compute_exchanged_amount` can perform conversions correctly
#[tokio::test]
async fn test_compute_exchanged_amount() {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel
.send(MaspEpoch::new(1).serialize_to_vec())
.expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token,
)
.await
.expect("Test failed");
for epoch in 0..=5 {
wallet.add_asset_type(AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
for epoch in 0..5 {
let mut conv = I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
}
.encode()
.unwrap(),
-2i128.pow(epoch as u32),
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(5)),
}
.encode()
.unwrap(),
2i128.pow(5),
);
context.add_conversions(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
},
(
native_token.clone(),
native_token_denom,
MaspDigitPos::Zero,
MaspEpoch::new(epoch),
conv,
MerklePath::from_path(vec![], 0),
),
);
}
let vk = arbitrary_vk();
let pa = arbitrary_pa();
// Shield at epoch 1
let asset_data = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
};
wallet.add_asset_type(asset_data.clone());
wallet.add_note(create_note(asset_data.clone(), 10, pa), vk);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
// Query the balance with conversions at epoch 5
let amount = wallet
.compute_exchanged_amount(
context.client(),
context.io(),
balance,
Conversions::new(),
)
.await
.unwrap()
.0;
assert_eq!(
amount,
I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(5)),
}
.encode()
.unwrap(),
160,
)
);
}
#[tokio::test]
// Test that the estimated rewards are 0 when no conversions are available
async fn test_estimate_rewards_no_conversions() {
let (channel, context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel
.send(MaspEpoch::new(1).serialize_to_vec())
.expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let asset_data = AssetData {
token: native_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
};
wallet.add_asset_type(asset_data.clone());
wallet.add_note(create_note(asset_data.clone(), 10, pa), vk);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet
.estimate_next_epoch_rewards(&context, &balance)
.await
.expect("Test failed");
assert_eq!(rewards_est, DenominatedAmount::native(0.into()));
}
#[tokio::test]
// Test that the estimated rewards are 0 when no conversions are available
// to the current epoch
async fn test_estimate_rewards_no_conversions_last_epoch() {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel
.send(MaspEpoch::new(2).serialize_to_vec())
.expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token,
)
.await
.expect("Test failed");
// add an old conversion for the incentivized tokens
let mut conv = I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
}
.encode()
.unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
}
.encode()
.unwrap(),
1,
);
context.add_conversions(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
},
(
native_token.clone(),
native_token_denom,
MaspDigitPos::Zero,
MaspEpoch::new(0),
conv,
MerklePath::from_path(vec![], 0),
),
);
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let asset_data = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
};
wallet.add_asset_type(asset_data.clone());
wallet.add_note(create_note(asset_data.clone(), 10, pa), vk);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet
.estimate_next_epoch_rewards(&context, &balance)
.await
.expect("Test failed");
assert_eq!(rewards_est, DenominatedAmount::native(0.into()));
}
proptest! {
/// In this test, we have a single incentivized token
/// shielded at MaspEpoch(2), owned by the shielded wallet.
/// The amount of owned token is the parameter `principal`.
///
/// We add a conversion from MaspEpoch(1) to MaspEpoch(2)
/// which issues `reward_rate` nam tokens for the first of our
/// incentivized token.
///
/// Optionally, the test also shields the same `principal` amount at
/// MaspEpoch(1).
///
/// We test that estimating the rewards for MaspEpoch(3)
/// applies the same conversions as the last epoch.
/// The asset shielded at epoch 2 does not have conversions produced yet
/// but we still expect the reward estimation logic to use the conversion at
/// the previous epoch and output a correct value.
///
/// Furthermore, we own `rewardless` amount of a token that
/// is not incentivized and thus should not contribute to
/// rewards.
#[test]
fn test_estimate_rewards_with_conversions(
// fairly arbitrary upper bounds, but they are large
// and guaranteed that 2 * reward_rate * principal
// does not exceed 64 bits
principal in 1u64 .. 100_000,
reward_rate in 1i128 .. 1_000,
rewardless in 1u64 .. 100_000,
shield_at_previous_epoch in proptest::bool::ANY
) {
// #[tokio::test] doesn't work with the proptest! macro
tokio::runtime::Runtime::new().unwrap().block_on(async {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel.send(MaspEpoch::new(2).serialize_to_vec()).expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token
)
.await
.expect("Test failed");
// we use a random addresses as our token
let incentivized_token = Address::Internal(InternalAddress::Pgf);
let unincentivized = Address::Internal(InternalAddress::ReplayProtection);
// add asset type decodings
wallet.add_asset_type(AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
});
wallet.add_asset_type(AssetData {
token: unincentivized.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: None,
});
for epoch in 0..4 {
wallet.add_asset_type(AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
// add conversions for the incentivized tokens
let mut conv = I128Sum::from_pair(
AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
}.encode().unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
}.encode().unwrap(),
1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
}.encode().unwrap(),
reward_rate,
);
context.add_conversions(
AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
},
(
incentivized_token.clone(),
0.into(),
MaspDigitPos::Zero,
MaspEpoch::new(1),
conv,
MerklePath::from_path(vec![], 0),
)
);
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let asset_data = AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
};
wallet.add_note(
create_note(asset_data, principal, pa),
vk,
);
// If this flag is set we also shield at the previous MaspEpoch(1),
// otherwise we test that the estimation logic can
// handle rewards for assets coming only from the current epoch,
// i.e. assets for which there are no conversions yet.
if shield_at_previous_epoch {
let asset_data = AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
};
wallet.add_note(
create_note(asset_data, principal, pa),
vk,
);
}
// add an unincentivized token which should not contribute
// to the rewards
let asset_data = AssetData {
token: unincentivized.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: None,
};
wallet.add_note(
create_note(asset_data, rewardless, pa),
vk,
);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet.estimate_next_epoch_rewards(&context, &balance)
.await.expect("Test failed");
assert_eq!(
rewards_est,
DenominatedAmount::native(
Amount::from_masp_denominated_i128(
// The expected rewards are just principal * reward_rate
// but if we also shielded at the previous epoch then we
// expect double the rewards
(1 + i128::from(shield_at_previous_epoch)) * reward_rate * i128::from(principal),
MaspDigitPos::Zero
).unwrap()
));
});
}
/// In this test, we have a single incentivized token
/// shielded at MaspEpoch(2), owned by the shielded wallet.
/// The amount of owned token is the parameter `principal`.
///
/// The test sets a current MaspEpoch that comes after MaspEpoch(2).
///
/// We add a conversion from MaspEpoch(1) to MaspEpoch(2)
/// which issues `reward_rate` nam tokens for the our incentivized token.
///
/// Optionally, the test also add conversions for all the masp epochs up
/// until the current one.
///
/// We test that estimating the rewards for the current masp epoch
/// applies the same conversions as the last epoch even if the asset has
/// been shielded far in the past. If conversions have been produced until
/// the current epoch than we expect the rewards to be the reward rate
/// times the amount shielded. If we only have a conversion to MaspEpoch(2)
/// instead, we expect rewards to be 0.
#[test]
fn test_estimate_rewards_with_conversions_far_past(
principal in 1u64 .. 100_000,
reward_rate in 1i128 .. 1_000,
current_masp_epoch in 3u64..20,
mint_future_rewards in proptest::bool::ANY
) {
// #[tokio::test] doesn't work with the proptest! macro
tokio::runtime::Runtime::new().unwrap().block_on(async {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel.send(MaspEpoch::new(current_masp_epoch).serialize_to_vec()).expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token
)
.await
.expect("Test failed");
// we use a random addresses as our token
let incentivized_token = Address::Internal(InternalAddress::Pgf);
// add asset type decodings
wallet.add_asset_type(AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
});
for epoch in 0..=(current_masp_epoch + 1) {
wallet.add_asset_type(AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
// if future rewards are requested add them to the context
if mint_future_rewards {
for epoch in 2..current_masp_epoch {
let mut conv = I128Sum::from_pair(
AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
}.encode().unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch + 1)),
}.encode().unwrap(),
1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
}.encode().unwrap(),
reward_rate,
);
context.add_conversions(
AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
},
(
incentivized_token.clone(),
0.into(),
MaspDigitPos::Zero,
MaspEpoch::new(epoch),
conv,
MerklePath::from_path(vec![], 0),
)
);
}
}
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let asset_data = AssetData {
token: incentivized_token.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
};
wallet.add_note(
create_note(asset_data, principal, pa),
vk,
);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet.estimate_next_epoch_rewards(&context, &balance)
.await.expect("Test failed");
assert_eq!(
rewards_est,
DenominatedAmount::native(
Amount::from_masp_denominated_i128(
// If we produced all the conversions we expect the estimated rewards to be
// the shielded amount times the reward rate, otherwise
// we expect it to be 0
reward_rate * i128::from(principal) * i128::from(mint_future_rewards),
MaspDigitPos::Zero
).unwrap()
));
});
}
/// In this test, we have a single incentivized token, the native one,
/// shielded at MaspEpoch(2), owned by the shielded wallet.
/// The amount of owned token is the parameter `principal`.
///
/// We add a conversion from MaspEpoch(1) to MaspEpoch(2)
/// which issues `reward_rate` nam tokens for our incentivized token.
///
/// Optionally, the test also shields the same `principal` amount at
/// MaspEpoch(1).
///
/// We test that estimating the rewards for MaspEpoch(3)
/// applies the same conversions as the last epoch. The asset
/// shielded at epoch 2 does not have conversions produced yet but we
/// still expect the reward estimation logic to use the conversion at
/// the previous epoch and output a correct value.
///
/// Furthermore, we own `principal` amount of the native token that
/// have no conversions (MaspEpoch(0)) and thus should not contribute to rewards.
#[test]
fn test_estimate_rewards_native_token_with_conversions(
// fairly arbitrary upper bounds, but they are large
// and guaranteed that 2 * reward_rate * principal
// does not exceed 64 bits
principal in 1u64 .. 100_000,
reward_rate in 1i128 .. 1_000,
shield_at_previous_epoch in proptest::bool::ANY
) {
// #[tokio::test] doesn't work with the proptest! macro
tokio::runtime::Runtime::new().unwrap().block_on(async {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel.send(MaspEpoch::new(2).serialize_to_vec()).expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token
)
.await
.expect("Test failed");
// add asset type decodings
for epoch in 0..4 {
wallet.add_asset_type(AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
// add conversions for the native token
let mut conv = I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
}.encode().unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
}.encode().unwrap(),
1 + reward_rate,
);
context.add_conversions(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
},
(
native_token.clone(),
native_token_denom,
MaspDigitPos::Zero,
MaspEpoch::new(1),
conv,
MerklePath::from_path(vec![], 0),
)
);
let vk = arbitrary_vk();
let pa = arbitrary_pa();
for epoch in [0, 2] {
let asset_data = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
};
wallet.add_note(
create_note(asset_data, principal, pa),
vk,
);
}
// If this flag is set we also shield at the previous MaspEpoch(1),
// otherwise we test that the estimation logic can
// handle rewards for assets coming only from the current epoch,
// i.e. assets for which there are no conversions yet.
if shield_at_previous_epoch {
let asset_data = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
};
wallet.add_note(
create_note(asset_data, principal, pa),
vk,
);
}
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet.estimate_next_epoch_rewards(&context, &balance).await.expect("Test failed");
if shield_at_previous_epoch {
assert_eq!(
rewards_est,
DenominatedAmount::native(
Amount::from_masp_denominated_i128(
// The expected rewards are just principal * reward_rate
// but if we also shielded at the previous epoch then we
// expect double the rewards and, on top of that, we
// need to account for the compounding of rewards
// given to the native token, hence the (2 + reward_rate)
(2 + reward_rate) * reward_rate * i128::from(principal),
MaspDigitPos::Zero
).unwrap()
)
);
} else {
assert_eq!(
rewards_est,
DenominatedAmount::native(
Amount::from_masp_denominated_i128(
i128::from(principal) * reward_rate,
MaspDigitPos::Zero
).unwrap()
)
);
}
});
}
/// In this test, we have a single incentivized token, the native one,
/// shielded at MaspEpoch(2), owned by the shielded wallet.
/// The amount of owned token is 1.
///
/// The test sets a current MaspEpoch that comes after MaspEpoch(2).
///
/// If requested, we add a conversion from MaspEpoch(2) to the current MaspEpoch
/// which issue `reward_rate` nam tokens for our incentivized token.
///
/// We test that estimating the rewards for the current masp epoch
/// applies the same conversions as the last epoch even if the asset has
/// been shielded far in the past. If conversions have been produced until
/// the current epoch than we expect the rewards to be the reward rate
/// times the amount shielded. If we only have a conversion to MaspEpoch(2)
/// instead, we expect rewards to be 0.
#[test]
fn test_estimate_rewards_native_token_with_conversions_far_past(
reward_rate in 1i128 .. 1_000,
current_masp_epoch in 3u64..10,
mint_future_rewards in proptest::bool::ANY
) {
// #[tokio::test] doesn't work with the proptest! macro
tokio::runtime::Runtime::new().unwrap().block_on(async {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel.send(MaspEpoch::new(current_masp_epoch).serialize_to_vec()).expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token
)
.await
.expect("Test failed");
// add asset type decodings
for epoch in 0..=(current_masp_epoch + 1){
wallet.add_asset_type(AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
// if future rewards are requested add them to the context
if mint_future_rewards {
for epoch in 2..current_masp_epoch {
let mut conv = I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
}.encode().unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch + 1)),
}.encode().unwrap(),
1 + reward_rate,
);
context.add_conversions(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
},
(
native_token.clone(),
native_token_denom,
MaspDigitPos::Zero,
MaspEpoch::new(epoch),
conv,
MerklePath::from_path(vec![], 0),
)
);
}
}
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let asset_data = AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
};
wallet.add_note(
create_note(asset_data, 1, pa),
vk,
);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet.estimate_next_epoch_rewards(&context, &balance).await.expect("Test failed");
let balance_at_epoch_3 = 1 + reward_rate;
let balance_at_current_epoch = i128::pow(balance_at_epoch_3, (current_masp_epoch - 2) as u32);
let estimated_balance_at_next_epoch = i128::pow(balance_at_epoch_3, (current_masp_epoch - 1) as u32);
assert_eq!(
rewards_est,
DenominatedAmount::native(
Amount::from_masp_denominated_i128(
i128::from(mint_future_rewards) * (estimated_balance_at_next_epoch - balance_at_current_epoch),
MaspDigitPos::Zero
).unwrap()
)
);
});
}
/// A more complicated test that checks asset estimations when multiple
/// different incentivized assets are present and multiple conversions need
/// to be applied to the same note.
#[test]
fn test_ests_with_mult_incentivized_assets(
principal1 in 1u64..10_000,
principal2 in 1u64..10_000,
tok1_reward_rate in 1i128..1000,
tok2_reward_rate in 1i128..1000,
) {
// #[tokio::test] doesn't work with the proptest! macro
tokio::runtime::Runtime::new().unwrap().block_on(async {
let (channel, mut context) = MockNamadaIo::new();
// the response to the current masp epoch query
channel
.send(MaspEpoch::new(3).serialize_to_vec())
.expect("Test failed");
let temp_dir = tempdir().unwrap();
let mut wallet = TestingContext::new(FsShieldedUtils::new(
temp_dir.path().to_path_buf(),
));
let native_token =
TestingContext::<FsShieldedUtils>::query_native_token(
context.client(),
)
.await
.expect("Test failed");
let native_token_denom =
TestingContext::<FsShieldedUtils>::query_denom(
context.client(),
&native_token
)
.await
.expect("Test failed");
// we use a random addresses as our tokens
let tok1 = Address::Internal(InternalAddress::Pgf);
let tok2 = Address::Internal(InternalAddress::ReplayProtection);
// add asset type decodings
for epoch in 0..5 {
wallet.add_asset_type(AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
for tok in [&tok1, &tok2] {
for epoch in 0..5 {
wallet.add_asset_type(AssetData {
token: tok.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
});
}
}
// add empty conversions for the native token
for epoch in 0..2 {
let mut conv = I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
}.encode().unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch + 1)),
}.encode().unwrap(),
1,
);
context.add_conversions(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(epoch)),
},
(
native_token.clone(),
native_token_denom,
MaspDigitPos::Zero,
MaspEpoch::new(epoch),
conv,
MerklePath::from_path(vec![], 0),
)
);
}
// add native conversion from epoch 2 -> 3
let mut conv = I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
}.encode().unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(3)),
}.encode().unwrap(),
2,
);
context.add_conversions(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
},
(
native_token.clone(),
native_token_denom,
MaspDigitPos::Zero,
MaspEpoch::new(2),
conv,
MerklePath::from_path(vec![], 0),
)
);
// add conversions from epoch 1 -> 2 for tok1
let mut conv = I128Sum::from_pair(
AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
}
.encode()
.unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
}
.encode()
.unwrap(),
1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
}
.encode()
.unwrap(),
tok1_reward_rate,
);
context.add_conversions(
AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
},
(
tok1.clone(),
0.into(),
MaspDigitPos::Zero,
MaspEpoch::new(1),
conv,
MerklePath::from_path(vec![], 0),
),
);
// add conversions from epoch 2 -> 3 for tok1
let mut conv = I128Sum::from_pair(
AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
}
.encode()
.unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(3)),
}
.encode()
.unwrap(),
1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
}
.encode()
.unwrap(),
1,
);
context.add_conversions(
AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
},
(
tok1.clone(),
0.into(),
MaspDigitPos::Zero,
MaspEpoch::new(2),
conv,
MerklePath::from_path(vec![], 0),
),
);
// add conversions from epoch 2 -> 3 for tok2
let mut conv = I128Sum::from_pair(
AssetData {
token: tok2.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
}
.encode()
.unwrap(),
-1,
);
conv += I128Sum::from_pair(
AssetData {
token: tok2.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(3)),
}
.encode()
.unwrap(),
1,
);
conv += I128Sum::from_pair(
AssetData {
token: native_token.clone(),
denom: native_token_denom,
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(0)),
}
.encode()
.unwrap(),
tok2_reward_rate,
);
context.add_conversions(
AssetData {
token: tok2.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
},
(
tok2.clone(),
0.into(),
MaspDigitPos::Zero,
MaspEpoch::new(2),
conv,
MerklePath::from_path(vec![], 0),
),
);
// create note with tok1
let vk = arbitrary_vk();
let pa = arbitrary_pa();
let asset_data = AssetData {
token: tok1.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(1)),
};
wallet.add_note(
create_note(asset_data.clone(), principal1, pa),
vk,
);
// create note with tok2
let asset_data = AssetData {
token: tok2.clone(),
denom: 0.into(),
position: MaspDigitPos::Zero,
epoch: Some(MaspEpoch::new(2)),
};
wallet.add_note(
create_note(asset_data.clone(), principal2, pa),
vk,
);
let balance = wallet
.compute_shielded_balance(&vk)
.await
.unwrap()
.unwrap_or_else(ValueSum::zero);
let rewards_est = wallet
.estimate_next_epoch_rewards(&context, &balance)
.await
.expect("Test failed");
// The native token balances at epoch 3 and 4 are given by the shielded amounts times the rewards times the conversion for the native asset
let native_balance_at_3 = (i128::from(principal1) * (tok1_reward_rate + 1) + i128::from(principal2) * tok2_reward_rate) * 2;
let estimated_native_balance_at_4= (i128::from(principal1) * (tok1_reward_rate + 2) + 2 * i128::from(principal2) * tok2_reward_rate) * 4;
assert_eq!(
rewards_est,
// The estimated rewards are just the difference between the two native token balances
DenominatedAmount::native(
Amount::from_masp_denominated_i128(
estimated_native_balance_at_4 - native_balance_at_3,
MaspDigitPos::Zero
).unwrap()
)
);
});
}
}
}