1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
//! Definition of transactions and other transaction-like messages, together
//! with their serialization, signing, and similar auxiliary methods.

use crate::{
    base::{
        AccountThreshold, AggregateSigPairing, AmountFraction, BakerAggregationVerifyKey,
        BakerElectionVerifyKey, BakerKeyPairs, BakerSignatureVerifyKey, ContractAddress,
        CredentialRegistrationID, DelegationTarget, Energy, Nonce, OpenStatus, UrlText,
    },
    common::{
        self,
        types::{Amount, KeyIndex, KeyPair, Timestamp, TransactionSignature, TransactionTime, *},
        Buffer, Deserial, Get, ParseResult, Put, ReadBytesExt, SerdeDeserialize, SerdeSerialize,
        Serial, Serialize,
    },
    constants::*,
    encrypted_transfers::types::{EncryptedAmountTransferData, SecToPubAmountTransferData},
    hashes,
    id::types::{
        AccountAddress, AccountCredentialMessage, AccountKeys, CredentialDeploymentInfo,
        CredentialPublicKeys, VerifyKey,
    },
    random_oracle::RandomOracle,
    smart_contracts, updates,
};
use concordium_contracts_common as concordium_std;
use concordium_std::SignatureThreshold;
use derive_more::*;
use rand::{CryptoRng, Rng};
use sha2::Digest;
use std::{collections::BTreeMap, marker::PhantomData};
use thiserror::Error;

#[derive(SerdeSerialize, SerdeDeserialize, Serial, Debug, Clone, AsRef, Into)]
#[serde(transparent)]
/// A data that was registered on the chain.
pub struct Memo {
    #[serde(with = "crate::internal::byte_array_hex")]
    #[size_length = 2]
    bytes: Vec<u8>,
}

/// An error used to signal that an object was too big to be converted.
#[derive(Display, Error, Debug)]
pub struct TooBig;

impl TryFrom<Vec<u8>> for Memo {
    type Error = TooBig;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        if value.len() <= crate::constants::MAX_MEMO_SIZE {
            Ok(Self { bytes: value })
        } else {
            Err(TooBig)
        }
    }
}

impl Deserial for Memo {
    fn deserial<R: crate::common::ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u16 = source.get()?;
        anyhow::ensure!(
            usize::from(len) <= crate::constants::MAX_MEMO_SIZE,
            "Memo too big.."
        );
        let bytes = crate::common::deserial_bytes(source, len.into())?;
        Ok(Memo { bytes })
    }
}

#[derive(SerdeSerialize, SerdeDeserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, Display)]
#[serde(rename_all = "camelCase")]
// Since all variants are fieldless, the default JSON serialization will convert
// all the variants to simple strings.
/// Types of account transactions.
pub enum TransactionType {
    /// Deploy a Wasm module.
    DeployModule,
    /// Initialize a smart contract instance.
    InitContract,
    /// Update a smart contract instance.
    Update,
    /// Transfer CCD from an account to another.
    Transfer,
    /// Register an account as a baker.
    AddBaker,
    /// Remove an account as a baker.
    RemoveBaker,
    /// Update the staked amount.
    UpdateBakerStake,
    /// Update whether the baker automatically restakes earnings.
    UpdateBakerRestakeEarnings,
    /// Update baker keys
    UpdateBakerKeys,
    /// Update given credential keys
    UpdateCredentialKeys,
    /// Transfer encrypted amount.
    EncryptedAmountTransfer,
    /// Transfer from public to encrypted balance of the same account.
    TransferToEncrypted,
    /// Transfer from encrypted to public balance of the same account.
    TransferToPublic,
    /// Transfer a CCD with a release schedule.
    TransferWithSchedule,
    /// Update the account's credentials.
    UpdateCredentials,
    /// Register some data on the chain.
    RegisterData,
    /// Same as transfer but with a memo field.
    TransferWithMemo,
    /// Same as encrypted transfer, but with a memo.
    EncryptedAmountTransferWithMemo,
    /// Same as transfer with schedule, but with an added memo.
    TransferWithScheduleAndMemo,
    ///  Configure an account's baker.
    ConfigureBaker,
    ///  Configure an account's stake delegation.
    ConfigureDelegation,
}

/// An error that occurs when trying to convert
/// an invalid i32 tag to a [TransactionType].
#[derive(Debug, Error)]
#[error("{0} is not a valid TransactionType tag.")]
pub struct TransactionTypeConversionError(pub i32);

impl TryFrom<i32> for TransactionType {
    type Error = TransactionTypeConversionError;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        Ok(match value {
            0 => Self::DeployModule,
            1 => Self::InitContract,
            2 => Self::Update,
            3 => Self::Transfer,
            4 => Self::AddBaker,
            5 => Self::RemoveBaker,
            6 => Self::UpdateBakerStake,
            7 => Self::UpdateBakerRestakeEarnings,
            8 => Self::UpdateBakerKeys,
            9 => Self::UpdateCredentialKeys,
            10 => Self::EncryptedAmountTransfer,
            11 => Self::TransferToEncrypted,
            12 => Self::TransferToPublic,
            13 => Self::TransferWithSchedule,
            14 => Self::UpdateCredentials,
            15 => Self::RegisterData,
            16 => Self::TransferWithMemo,
            17 => Self::EncryptedAmountTransferWithMemo,
            18 => Self::TransferWithScheduleAndMemo,
            19 => Self::ConfigureBaker,
            20 => Self::ConfigureDelegation,
            n => return Err(TransactionTypeConversionError(n)),
        })
    }
}

#[derive(
    Debug, Copy, Clone, Serial, SerdeSerialize, SerdeDeserialize, Into, From, Display, Eq, PartialEq,
)]
#[serde(transparent)]
/// Type safe wrapper to record the size of the transaction payload.
pub struct PayloadSize {
    pub(crate) size: u32,
}

impl Deserial for PayloadSize {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let size: u32 = source.get()?;
        anyhow::ensure!(
            size <= MAX_PAYLOAD_SIZE,
            "Size of the payload exceeds maximum allowed."
        );
        Ok(PayloadSize { size })
    }
}

#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(rename_all = "camelCase")]
/// Header of an account transaction that contains basic data to check whether
/// the sender and the transaction is valid.
pub struct TransactionHeader {
    /// Sender account of the transaction.
    pub sender:        AccountAddress,
    /// Sequence number of the transaction.
    pub nonce:         Nonce,
    /// Maximum amount of energy the transaction can take to execute.
    pub energy_amount: Energy,
    /// Size of the transaction payload. This is used to deserialize the
    /// payload.
    pub payload_size:  PayloadSize,
    /// Latest time the transaction can be included in a block.
    pub expiry:        TransactionTime,
}

#[derive(Debug, Clone, SerdeSerialize, SerdeDeserialize, Into, AsRef)]
#[serde(transparent)]
/// An account transaction payload that has not yet been deserialized.
/// This is a simple wrapper around [`Vec<u8>`](Vec) with bespoke serialization.
pub struct EncodedPayload {
    #[serde(with = "crate::internal::byte_array_hex")]
    pub(crate) payload: Vec<u8>,
}

#[derive(Debug, Error)]
#[error("The given byte array of size {actual}B exceeds maximum payload size {max}B")]
pub struct ExceedsPayloadSize {
    pub actual: usize,
    pub max:    u32,
}

impl TryFrom<Vec<u8>> for EncodedPayload {
    type Error = ExceedsPayloadSize;

    fn try_from(payload: Vec<u8>) -> Result<Self, Self::Error> {
        let actual = payload.len();
        if actual
            .try_into()
            .map_or(false, |x: u32| x <= MAX_PAYLOAD_SIZE)
        {
            Ok(Self { payload })
        } else {
            Err(ExceedsPayloadSize {
                actual,
                max: MAX_PAYLOAD_SIZE,
            })
        }
    }
}

impl EncodedPayload {
    /// Attempt to decode the [`EncodedPayload`] into a structured [`Payload`].
    /// This also checks that all data is used, i.e., that there are no
    /// remaining trailing bytes.
    pub fn decode(&self) -> ParseResult<Payload> {
        let mut source = std::io::Cursor::new(&self.payload);
        let payload = source.get()?;
        // ensure payload length matches the stated size.
        let consumed = source.position();
        anyhow::ensure!(
            consumed == self.payload.len() as u64,
            "Payload length information is inaccurate: {} bytes of input remaining.",
            self.payload.len() as u64 - consumed
        );
        Ok(payload)
    }
}

/// This serial instance does not have an inverse. It needs a context with the
/// length.
impl Serial for EncodedPayload {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.write_all(&self.payload)
            .expect("Writing to buffer should succeed.");
    }
}

/// Parse an encoded payload of specified length.
pub fn get_encoded_payload<R: ReadBytesExt>(
    source: &mut R,
    len: PayloadSize,
) -> ParseResult<EncodedPayload> {
    // The use of deserial_bytes is safe here (no execessive allocations) because
    // payload_size is limited
    let payload = crate::common::deserial_bytes(source, u32::from(len) as usize)?;
    Ok(EncodedPayload { payload })
}

/// A helper trait so that we can treat payload and encoded payload in the same
/// place.
pub trait PayloadLike {
    /// Encode the transaction payload by serializing.
    fn encode(&self) -> EncodedPayload;
    /// Encode the payload directly to a buffer. This will in general be more
    /// efficient than `encode`. However this will only matter if serialization
    /// was to be done in a tight loop.
    fn encode_to_buffer<B: Buffer>(&self, out: &mut B);
}

impl PayloadLike for EncodedPayload {
    fn encode(&self) -> EncodedPayload { self.clone() }

    fn encode_to_buffer<B: Buffer>(&self, out: &mut B) {
        out.write_all(&self.payload)
            .expect("Writing to buffer is always safe.");
    }
}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize)]
#[serde(rename_all = "camelCase")]
/// An account transaction signed and paid for by a sender account.
/// The payload type is a generic parameter to support two kinds of payloads,
/// a fully deserialized [Payload] type, and an [EncodedPayload]. The latter is
/// useful since deserialization of some types of payloads is expensive. It is
/// thus useful to delay deserialization until after we have checked signatures
/// and the sender account information.
pub struct AccountTransaction<PayloadType> {
    pub signature: TransactionSignature,
    pub header:    TransactionHeader,
    pub payload:   PayloadType,
}

impl<P: PayloadLike> Serial for AccountTransaction<P> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.signature);
        out.put(&self.header);
        self.payload.encode_to_buffer(out)
    }
}

impl Deserial for AccountTransaction<EncodedPayload> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let signature = source.get()?;
        let header: TransactionHeader = source.get()?;
        let payload = get_encoded_payload(source, header.payload_size)?;
        Ok(AccountTransaction {
            signature,
            header,
            payload,
        })
    }
}

impl Deserial for AccountTransaction<Payload> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let signature = source.get()?;
        let header: TransactionHeader = source.get()?;
        let payload_len = u64::from(u32::from(header.payload_size));
        let mut limited = <&mut R as std::io::Read>::take(source, payload_len);
        let payload = limited.get()?;
        // ensure payload length matches the stated size.
        anyhow::ensure!(
            limited.limit() == 0,
            "Payload length information is inaccurate: {} bytes of input remaining.",
            limited.limit()
        );
        Ok(AccountTransaction {
            signature,
            header,
            payload,
        })
    }
}

impl<P: PayloadLike> AccountTransaction<P> {
    /// Verify signature on the transaction given the public keys.
    pub fn verify_transaction_signature(&self, keys: &impl HasAccountAccessStructure) -> bool {
        let hash = compute_transaction_sign_hash(&self.header, &self.payload);
        verify_signature_transaction_sign_hash(keys, &hash, &self.signature)
    }
}

/// Marker for `BakerKeysPayload` indicating the proofs contained in
/// `BakerKeysPayload` have been generated for an `AddBaker` transaction.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AddBakerKeysMarker {}

/// Marker for `BakerKeysPayload` indicating the proofs contained in
/// `BakerKeysPayload` have been generated for an `UpdateBakerKeys` transaction.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum UpdateBakerKeysMarker {}

/// Marker for `ConfigureBakerKeysPayload` indicating the proofs contained in
/// `ConfigureBaker` have been generated for an `ConfigureBaker` transaction.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConfigureBakerKeysMarker {}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize)]
#[serde(rename_all = "camelCase")]
/// Auxiliary type that contains public keys and proof of ownership of those
/// keys. This is used in the `AddBaker` and `UpdateBakerKeys` transaction
/// types.
/// The proofs are either constructed for `AddBaker` or `UpdateBakerKeys` and
/// the generic `V` is used as a marker to distinguish this in the type. See the
/// markers: `AddBakerKeysMarker` and `UpdateBakerKeysMarker`.
pub struct BakerKeysPayload<V> {
    #[serde(skip)] // use default when deserializing
    phantom: PhantomData<V>,
    /// New public key for participating in the election lottery.
    pub election_verify_key:    BakerElectionVerifyKey,
    /// New public key for verifying this baker's signatures.
    pub signature_verify_key:   BakerSignatureVerifyKey,
    /// New public key for verifying this baker's signature on finalization
    /// records.
    pub aggregation_verify_key: BakerAggregationVerifyKey,
    /// Proof of knowledge of the secret key corresponding to the signature
    /// verification key.
    pub proof_sig:              crate::eddsa_ed25519::Ed25519DlogProof,
    /// Proof of knowledge of the election secret key.
    pub proof_election:         crate::eddsa_ed25519::Ed25519DlogProof,
    /// Proof of knowledge of the secret key for signing finalization
    /// records.
    pub proof_aggregation:      crate::aggregate_sig::Proof<AggregateSigPairing>,
}

/// Baker keys payload containing proofs construct for a `AddBaker` transaction.
pub type BakerAddKeysPayload = BakerKeysPayload<AddBakerKeysMarker>;
/// Baker keys payload containing proofs construct for a `UpdateBakerKeys`
/// transaction.
pub type BakerUpdateKeysPayload = BakerKeysPayload<UpdateBakerKeysMarker>;

/// Baker keys payload containing proofs construct for a `ConfigureBaker`
/// transaction.
pub type ConfigureBakerKeysPayload = BakerKeysPayload<ConfigureBakerKeysMarker>;

impl<T> BakerKeysPayload<T> {
    /// Construct a BakerKeysPayload taking a prefix for the challenge.
    fn new_payload<R: Rng + CryptoRng>(
        baker_keys: &BakerKeyPairs,
        sender: AccountAddress,
        challenge_prefix: &[u8],
        csprng: &mut R,
    ) -> Self {
        let mut challenge = challenge_prefix.to_vec();

        sender.serial(&mut challenge);
        baker_keys.election_verify.serial(&mut challenge);
        baker_keys.signature_verify.serial(&mut challenge);
        baker_keys.aggregation_verify.serial(&mut challenge);

        let proof_election = crate::eddsa_ed25519::prove_dlog_ed25519(
            csprng,
            &mut RandomOracle::domain(&challenge),
            &baker_keys.election_verify.verify_key,
            &baker_keys.election_sign.sign_key,
        );
        let proof_sig = crate::eddsa_ed25519::prove_dlog_ed25519(
            csprng,
            &mut RandomOracle::domain(&challenge),
            &baker_keys.signature_verify.verify_key,
            &baker_keys.signature_sign.sign_key,
        );
        let proof_aggregation = baker_keys
            .aggregation_sign
            .prove(csprng, &mut RandomOracle::domain(&challenge));

        BakerKeysPayload {
            phantom: PhantomData,
            election_verify_key: baker_keys.election_verify.clone(),
            signature_verify_key: baker_keys.signature_verify.clone(),
            aggregation_verify_key: baker_keys.aggregation_verify.clone(),
            proof_sig,
            proof_election,
            proof_aggregation,
        }
    }
}

impl BakerAddKeysPayload {
    /// Construct a BakerKeysPayload with proofs for adding a baker.
    pub fn new<T: Rng + CryptoRng>(
        baker_keys: &BakerKeyPairs,
        sender: AccountAddress,
        csprng: &mut T,
    ) -> Self {
        BakerKeysPayload::new_payload(baker_keys, sender, b"addBaker", csprng)
    }
}

impl BakerUpdateKeysPayload {
    /// Construct a BakerKeysPayload with proofs for updating baker keys.
    pub fn new<T: Rng + CryptoRng>(
        baker_keys: &BakerKeyPairs,
        sender: AccountAddress,
        csprng: &mut T,
    ) -> Self {
        BakerKeysPayload::new_payload(baker_keys, sender, b"updateBakerKeys", csprng)
    }
}

impl ConfigureBakerKeysPayload {
    /// Construct a BakerKeysPayload with proofs for updating baker keys.
    pub fn new<T: Rng + CryptoRng>(
        baker_keys: &BakerKeyPairs,
        sender: AccountAddress,
        csprng: &mut T,
    ) -> Self {
        BakerKeysPayload::new_payload(baker_keys, sender, b"configureBaker", csprng)
    }
}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize)]
#[serde(rename_all = "camelCase")]
/// Payload of the `AddBaker` transaction. This transaction registers the
/// account as a baker.
pub struct AddBakerPayload {
    /// The keys with which the baker registered.
    #[serde(flatten)]
    pub keys:             BakerAddKeysPayload,
    /// Initial baking stake.
    pub baking_stake:     Amount,
    /// Whether to add earnings to the stake automatically or not.
    pub restake_earnings: bool,
}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize)]
#[serde(rename_all = "camelCase")]
/// Data needed to initialize a smart contract.
pub struct InitContractPayload {
    /// Deposit this amount of CCD.
    pub amount:    Amount,
    /// Reference to the module from which to initialize the instance.
    pub mod_ref:   concordium_contracts_common::ModuleReference,
    /// Name of the contract in the module.
    pub init_name: smart_contracts::OwnedContractName,
    /// Message to invoke the initialization method with.
    pub param:     smart_contracts::OwnedParameter,
}

impl InitContractPayload {
    /// Get the size of the payload in number of bytes.
    pub fn size(&self) -> usize {
        8 + // Amount
        32 + // Module reference
        2 + // Init name size
        self.init_name.as_contract_name().get_chain_name().len() +
        2 + // Parameter size
        self.param.as_ref().len()
    }
}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize)]
#[serde(rename_all = "camelCase")]
/// Data needed to update a smart contract instance.
pub struct UpdateContractPayload {
    /// Send the given amount of CCD together with the message to the
    /// contract instance.
    pub amount:       Amount,
    /// Address of the contract instance to invoke.
    pub address:      ContractAddress,
    /// Name of the method to invoke on the contract.
    pub receive_name: smart_contracts::OwnedReceiveName,
    /// Message to send to the contract instance.
    pub message:      smart_contracts::OwnedParameter,
}

impl UpdateContractPayload {
    /// Get the size of the payload in number of bytes.
    pub fn size(&self) -> usize {
        8 + // Amount
        16 + // Contract address
        2 + // Receive name size
        self.receive_name.as_receive_name().get_chain_name().len() +
        2 + // Parameter size
        self.message.as_ref().len()
    }
}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize, Default)]
#[serde(rename_all = "camelCase")]
/// Payload for configuring a baker. The different constructors cover
/// the different common cases.
/// The [Default] implementation produces an empty configure that will have no
/// effects.
pub struct ConfigureBakerPayload {
    /// The equity capital of the baker
    pub capital: Option<Amount>,
    /// Whether the baker's earnings are restaked
    pub restake_earnings: Option<bool>,
    /// Whether the pool is open for delegators
    pub open_for_delegation: Option<OpenStatus>,
    /// The key/proof pairs to verify the baker.
    pub keys_with_proofs: Option<ConfigureBakerKeysPayload>,
    /// The URL referencing the baker's metadata.
    pub metadata_url: Option<UrlText>,
    /// The commission the pool owner takes on transaction fees.
    pub transaction_fee_commission: Option<AmountFraction>,
    /// The commission the pool owner takes on baking rewards.
    pub baking_reward_commission: Option<AmountFraction>,
    /// The commission the pool owner takes on finalization rewards.
    pub finalization_reward_commission: Option<AmountFraction>,
}

impl ConfigureBakerPayload {
    pub fn new() -> Self { Self::default() }

    /// Construct a new payload to remove a baker.
    pub fn new_remove_baker() -> Self {
        Self {
            capital: Some(Amount::from_micro_ccd(0)),
            ..Self::new()
        }
    }

    /// Set the new baker capital.
    pub fn set_capital(&mut self, amount: Amount) -> &mut Self {
        self.capital = Some(amount);
        self
    }

    /// Set whether or not earnings are automatically added to the stake.
    pub fn set_restake_earnings(&mut self, restake_earnings: bool) -> &mut Self {
        self.restake_earnings = Some(restake_earnings);
        self
    }

    /// Update the delegation status of the pool.
    pub fn set_open_for_delegation(&mut self, open_for_delegation: OpenStatus) -> &mut Self {
        self.open_for_delegation = Some(open_for_delegation);
        self
    }

    /// Add keys to the payload. This will construct proofs of validity and
    /// insert the public keys into the payload.
    pub fn add_keys<T: Rng + CryptoRng>(
        &mut self,
        baker_keys: &BakerKeyPairs,
        sender: AccountAddress,
        csprng: &mut T,
    ) -> &mut Self {
        let keys_with_proofs =
            BakerKeysPayload::new_payload(baker_keys, sender, b"configureBaker", csprng);
        self.keys_with_proofs = Some(keys_with_proofs);
        self
    }

    /// Add metadata URL to the payload.
    pub fn set_metadata_url(&mut self, metadata_url: UrlText) -> &mut Self {
        self.metadata_url = Some(metadata_url);
        self
    }

    /// Set a new transaction fee commission.
    pub fn set_transaction_fee_commission(
        &mut self,
        transaction_fee_commission: AmountFraction,
    ) -> &mut Self {
        self.transaction_fee_commission = Some(transaction_fee_commission);
        self
    }

    /// Set a new baking reward commission.
    pub fn set_baking_reward_commission(
        &mut self,
        baking_reward_commission: AmountFraction,
    ) -> &mut Self {
        self.baking_reward_commission = Some(baking_reward_commission);
        self
    }

    /// Set a new finalization reward commission.
    pub fn set_finalization_reward_commission(
        &mut self,
        finalization_reward_commission: AmountFraction,
    ) -> &mut Self {
        self.finalization_reward_commission = Some(finalization_reward_commission);
        self
    }
}

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize, Default)]
#[serde(rename_all = "camelCase")]
/// Payload for configuring delegation. The [Default] implementation produces an
/// empty configuration that will not change anything.
pub struct ConfigureDelegationPayload {
    /// The capital delegated to the pool.
    pub capital:           Option<Amount>,
    /// Whether the delegator's earnings are restaked.
    pub restake_earnings:  Option<bool>,
    /// The target of the delegation.
    pub delegation_target: Option<DelegationTarget>,
}

impl ConfigureDelegationPayload {
    /// Construct a new payload that has all the options unset.
    pub fn new() -> Self { Self::default() }

    /// Construct a new payload to remove a delegation.
    pub fn new_remove_delegation() -> Self {
        Self {
            capital: Some(Amount::from_micro_ccd(0)),
            ..Self::new()
        }
    }

    pub fn set_capital(&mut self, amount: Amount) -> &mut Self {
        self.capital = Some(amount);
        self
    }

    pub fn set_restake_earnings(&mut self, restake_earnings: bool) -> &mut Self {
        self.restake_earnings = Some(restake_earnings);
        self
    }

    pub fn set_delegation_target(&mut self, target: DelegationTarget) -> &mut Self {
        self.delegation_target = Some(target);
        self
    }
}

#[derive(SerdeSerialize, SerdeDeserialize, Serial, Debug, Clone, AsRef, Into, AsMut)]
#[serde(transparent)]
/// A data that was registered on the chain.
pub struct RegisteredData {
    #[serde(with = "crate::internal::byte_array_hex")]
    #[size_length = 2]
    bytes: Vec<u8>,
}

/// Registered data is too large.
#[derive(Debug, Error, Copy, Clone)]
#[error("Data is too large to be registered ({actual_size}).")]
pub struct TooLargeError {
    actual_size: usize,
}

impl TryFrom<Vec<u8>> for RegisteredData {
    type Error = TooLargeError;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        let actual_size = bytes.len();
        if actual_size <= crate::constants::MAX_REGISTERED_DATA_SIZE {
            Ok(RegisteredData { bytes })
        } else {
            Err(TooLargeError { actual_size })
        }
    }
}

impl From<[u8; 32]> for RegisteredData {
    fn from(data: [u8; 32]) -> Self {
        Self {
            bytes: data.to_vec(),
        }
    }
}

impl<M> From<crate::hashes::HashBytes<M>> for RegisteredData {
    fn from(data: crate::hashes::HashBytes<M>) -> Self {
        Self {
            bytes: data.as_ref().to_vec(),
        }
    }
}

impl Deserial for RegisteredData {
    fn deserial<R: crate::common::ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u16 = source.get()?;
        anyhow::ensure!(
            usize::from(len) <= crate::constants::MAX_REGISTERED_DATA_SIZE,
            "Data too big to register."
        );
        let bytes = crate::common::deserial_bytes(source, len.into())?;
        Ok(RegisteredData { bytes })
    }
}

/// Mapping of credential indices to account credentials with proofs.
/// This structure is used when sending transactions that update credentials.
pub type AccountCredentialsMap = BTreeMap<
    CredentialIndex,
    CredentialDeploymentInfo<
        crate::id::constants::IpPairing,
        crate::id::constants::ArCurve,
        crate::id::constants::AttributeKind,
    >,
>;

#[derive(Debug, Clone, SerdeDeserialize, SerdeSerialize)]
#[serde(rename_all = "camelCase")]
/// Payload of an account transaction.
pub enum Payload {
    /// Deploy a Wasm module with the given source.
    DeployModule {
        #[serde(rename = "mod")]
        module: smart_contracts::WasmModule,
    },
    /// Initialize a new smart contract instance.
    InitContract {
        #[serde(flatten)]
        payload: InitContractPayload,
    },
    /// Update a smart contract instance by invoking a specific function.
    Update {
        #[serde(flatten)]
        payload: UpdateContractPayload,
    },
    /// Transfer CCD to an account.
    Transfer {
        /// Address to send to.
        to_address: AccountAddress,
        /// Amount to send.
        amount:     Amount,
    },
    /// Register the sender account as a baker.
    AddBaker {
        #[serde(flatten)]
        payload: Box<AddBakerPayload>,
    },
    /// Deregister the account as a baker.
    RemoveBaker,
    /// Update baker's stake.
    UpdateBakerStake {
        /// The new stake.
        stake: Amount,
    },
    /// Modify whether to add earnings to the baker stake automatically or not.
    UpdateBakerRestakeEarnings {
        /// New value of the flag.
        restake_earnings: bool,
    },
    /// Update the baker's keys.
    UpdateBakerKeys {
        #[serde(flatten)]
        payload: Box<BakerUpdateKeysPayload>,
    },
    /// Update signing keys of a specific credential.
    UpdateCredentialKeys {
        /// Id of the credential whose keys are to be updated.
        cred_id: CredentialRegistrationID,
        /// The new public keys.
        keys:    CredentialPublicKeys,
    },
    /// Transfer an encrypted amount.
    EncryptedAmountTransfer {
        /// The recepient's address.
        to:   AccountAddress,
        /// The (encrypted) amount to transfer and proof of correctness of
        /// accounting.
        data: Box<EncryptedAmountTransferData<EncryptedAmountsCurve>>,
    },
    /// Transfer from public to encrypted balance of the sender account.
    TransferToEncrypted {
        /// The amount to transfer.
        amount: Amount,
    },
    /// Transfer an amount from encrypted to the public balance of the account.
    TransferToPublic {
        /// The amount to transfer and proof of correctness of accounting.
        #[serde(flatten)]
        data: Box<SecToPubAmountTransferData<EncryptedAmountsCurve>>,
    },
    /// Transfer an amount with schedule.
    TransferWithSchedule {
        /// The recepient.
        to:       AccountAddress,
        /// The release schedule. This can be at most 255 elements.
        schedule: Vec<(Timestamp, Amount)>,
    },
    /// Update the account's credentials.
    UpdateCredentials {
        /// New credentials to add.
        new_cred_infos:  AccountCredentialsMap,
        /// Ids of credentials to remove.
        remove_cred_ids: Vec<CredentialRegistrationID>,
        /// The new account threshold.
        new_threshold:   AccountThreshold,
    },
    /// Register the given data on the chain.
    RegisterData {
        /// The data to register.
        data: RegisteredData,
    },
    /// Transfer CCD to an account with an additional memo.
    TransferWithMemo {
        /// Address to send to.
        to_address: AccountAddress,
        /// Memo to include in the transfer.
        memo:       Memo,
        /// Amount to send.
        amount:     Amount,
    },
    /// Transfer an encrypted amount.
    EncryptedAmountTransferWithMemo {
        /// The recepient's address.
        to:   AccountAddress,
        /// Memo to include in the transfer.
        memo: Memo,
        /// The (encrypted) amount to transfer and proof of correctness of
        /// accounting.
        data: Box<EncryptedAmountTransferData<EncryptedAmountsCurve>>,
    },
    /// Transfer an amount with schedule.
    TransferWithScheduleAndMemo {
        /// The recepient.
        to:       AccountAddress,
        /// Memo to include in the transfer.
        memo:     Memo,
        /// The release schedule. This can be at most 255 elements.
        schedule: Vec<(Timestamp, Amount)>,
    },
    /// Configure a baker on an account.
    ConfigureBaker {
        #[serde(flatten)]
        data: Box<ConfigureBakerPayload>,
    },
    ///  Configure an account's stake delegation.
    ConfigureDelegation {
        #[serde(flatten)]
        data: ConfigureDelegationPayload,
    },
}

impl Payload {
    /// Resolve the [TransactionType] corresponding to the variant of the
    /// Payload.
    pub fn transaction_type(&self) -> TransactionType {
        match self {
            Payload::DeployModule { .. } => TransactionType::DeployModule,
            Payload::InitContract { .. } => TransactionType::InitContract,
            Payload::Update { .. } => TransactionType::Update,
            Payload::Transfer { .. } => TransactionType::Transfer,
            Payload::AddBaker { .. } => TransactionType::AddBaker,
            Payload::RemoveBaker { .. } => TransactionType::RemoveBaker,
            Payload::UpdateBakerStake { .. } => TransactionType::UpdateBakerStake,
            Payload::UpdateBakerRestakeEarnings { .. } => {
                TransactionType::UpdateBakerRestakeEarnings
            }
            Payload::UpdateBakerKeys { .. } => TransactionType::UpdateBakerKeys,
            Payload::UpdateCredentialKeys { .. } => TransactionType::UpdateCredentialKeys,
            Payload::EncryptedAmountTransfer { .. } => TransactionType::EncryptedAmountTransfer,
            Payload::TransferToEncrypted { .. } => TransactionType::TransferToEncrypted,
            Payload::TransferToPublic { .. } => TransactionType::TransferToPublic,
            Payload::TransferWithSchedule { .. } => TransactionType::TransferWithSchedule,
            Payload::UpdateCredentials { .. } => TransactionType::UpdateCredentials,
            Payload::RegisterData { .. } => TransactionType::RegisterData,
            Payload::TransferWithMemo { .. } => TransactionType::TransferWithMemo,
            Payload::EncryptedAmountTransferWithMemo { .. } => {
                TransactionType::EncryptedAmountTransferWithMemo
            }
            Payload::TransferWithScheduleAndMemo { .. } => {
                TransactionType::TransferWithScheduleAndMemo
            }
            Payload::ConfigureBaker { .. } => TransactionType::ConfigureBaker,
            Payload::ConfigureDelegation { .. } => TransactionType::ConfigureDelegation,
        }
    }
}

impl Serial for Payload {
    fn serial<B: Buffer>(&self, out: &mut B) {
        match &self {
            Payload::DeployModule { module } => {
                out.put(&0u8);
                out.put(module);
            }
            Payload::InitContract { payload } => {
                out.put(&1u8);
                out.put(payload)
            }
            Payload::Update { payload } => {
                out.put(&2u8);
                out.put(payload)
            }
            Payload::Transfer { to_address, amount } => {
                out.put(&3u8);
                out.put(to_address);
                out.put(amount);
            }
            Payload::AddBaker { payload } => {
                out.put(&4u8);
                out.put(payload);
            }
            Payload::RemoveBaker => {
                out.put(&5u8);
            }
            Payload::UpdateBakerStake { stake } => {
                out.put(&6u8);
                out.put(stake);
            }
            Payload::UpdateBakerRestakeEarnings { restake_earnings } => {
                out.put(&7u8);
                out.put(restake_earnings);
            }
            Payload::UpdateBakerKeys { payload } => {
                out.put(&8u8);
                out.put(payload)
            }
            Payload::UpdateCredentialKeys { cred_id, keys } => {
                out.put(&13u8);
                out.put(cred_id);
                out.put(keys);
            }
            Payload::EncryptedAmountTransfer { to, data } => {
                out.put(&16u8);
                out.put(to);
                out.put(data);
            }
            Payload::TransferToEncrypted { amount } => {
                out.put(&17u8);
                out.put(amount);
            }
            Payload::TransferToPublic { data } => {
                out.put(&18u8);
                out.put(data);
            }
            Payload::TransferWithSchedule { to, schedule } => {
                out.put(&19u8);
                out.put(to);
                out.put(&(schedule.len() as u8));
                crate::common::serial_vector_no_length(schedule, out);
            }
            Payload::UpdateCredentials {
                new_cred_infos,
                remove_cred_ids,
                new_threshold,
            } => {
                out.put(&20u8);
                out.put(&(new_cred_infos.len() as u8));
                crate::common::serial_map_no_length(new_cred_infos, out);
                out.put(&(remove_cred_ids.len() as u8));
                crate::common::serial_vector_no_length(remove_cred_ids, out);
                out.put(new_threshold);
            }
            Payload::RegisterData { data } => {
                out.put(&21u8);
                out.put(data);
            }
            Payload::TransferWithMemo {
                to_address,
                memo,
                amount,
            } => {
                out.put(&22u8);
                out.put(to_address);
                out.put(memo);
                out.put(amount);
            }
            Payload::EncryptedAmountTransferWithMemo { to, memo, data } => {
                out.put(&23u8);
                out.put(to);
                out.put(memo);
                out.put(data);
            }
            Payload::TransferWithScheduleAndMemo { to, memo, schedule } => {
                out.put(&24u8);
                out.put(to);
                out.put(memo);
                out.put(&(schedule.len() as u8));
                crate::common::serial_vector_no_length(schedule, out);
            }
            Payload::ConfigureBaker { data } => {
                out.put(&25u8);
                let set_if = |n, b| if b { 1u16 << n } else { 0 };
                let bitmap: u16 = set_if(0, data.capital.is_some())
                    | set_if(1, data.restake_earnings.is_some())
                    | set_if(2, data.open_for_delegation.is_some())
                    | set_if(3, data.keys_with_proofs.is_some())
                    | set_if(4, data.metadata_url.is_some())
                    | set_if(5, data.transaction_fee_commission.is_some())
                    | set_if(6, data.baking_reward_commission.is_some())
                    | set_if(7, data.finalization_reward_commission.is_some());
                out.put(&bitmap);
                if let Some(capital) = &data.capital {
                    out.put(capital);
                }
                if let Some(restake_earnings) = &data.restake_earnings {
                    out.put(restake_earnings);
                }
                if let Some(open_for_delegation) = &data.open_for_delegation {
                    out.put(open_for_delegation);
                }
                if let Some(keys_with_proofs) = &data.keys_with_proofs {
                    // this is serialized manually since the serialization in Haskell is not
                    // consistent with the serialization of baker add
                    // transactions. The order of fields is different.
                    out.put(&keys_with_proofs.election_verify_key);
                    out.put(&keys_with_proofs.proof_election);
                    out.put(&keys_with_proofs.signature_verify_key);
                    out.put(&keys_with_proofs.proof_sig);
                    out.put(&keys_with_proofs.aggregation_verify_key);
                    out.put(&keys_with_proofs.proof_aggregation);
                }
                if let Some(metadata_url) = &data.metadata_url {
                    out.put(metadata_url);
                }
                if let Some(transaction_fee_commission) = &data.transaction_fee_commission {
                    out.put(transaction_fee_commission);
                }
                if let Some(baking_reward_commission) = &data.baking_reward_commission {
                    out.put(baking_reward_commission);
                }
                if let Some(finalization_reward_commission) = &data.finalization_reward_commission {
                    out.put(finalization_reward_commission);
                }
            }
            Payload::ConfigureDelegation {
                data:
                    ConfigureDelegationPayload {
                        capital,
                        restake_earnings,
                        delegation_target,
                    },
            } => {
                out.put(&26u8);
                let set_if = |n, b| if b { 1u16 << n } else { 0 };
                let bitmap: u16 = set_if(0, capital.is_some())
                    | set_if(1, restake_earnings.is_some())
                    | set_if(2, delegation_target.is_some());
                out.put(&bitmap);
                if let Some(capital) = capital {
                    out.put(capital);
                }
                if let Some(restake_earnings) = restake_earnings {
                    out.put(restake_earnings);
                }
                if let Some(delegation_target) = delegation_target {
                    out.put(delegation_target);
                }
            }
        }
    }
}

impl Deserial for Payload {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let tag: u8 = source.get()?;
        match tag {
            0 => {
                let module = source.get()?;
                Ok(Payload::DeployModule { module })
            }
            1 => {
                let payload = source.get()?;
                Ok(Payload::InitContract { payload })
            }
            2 => {
                let payload = source.get()?;
                Ok(Payload::Update { payload })
            }
            3 => {
                let to_address = source.get()?;
                let amount = source.get()?;
                Ok(Payload::Transfer { to_address, amount })
            }
            4 => {
                let payload_data = source.get()?;
                Ok(Payload::AddBaker {
                    payload: Box::new(payload_data),
                })
            }
            5 => Ok(Payload::RemoveBaker),
            6 => {
                let stake = source.get()?;
                Ok(Payload::UpdateBakerStake { stake })
            }
            7 => {
                let restake_earnings = source.get()?;
                Ok(Payload::UpdateBakerRestakeEarnings { restake_earnings })
            }
            8 => {
                let payload_data = source.get()?;
                Ok(Payload::UpdateBakerKeys {
                    payload: Box::new(payload_data),
                })
            }
            13 => {
                let cred_id = source.get()?;
                let keys = source.get()?;
                Ok(Payload::UpdateCredentialKeys { cred_id, keys })
            }
            16 => {
                let to = source.get()?;
                let data = source.get()?;
                Ok(Payload::EncryptedAmountTransfer { to, data })
            }
            17 => {
                let amount = source.get()?;
                Ok(Payload::TransferToEncrypted { amount })
            }
            18 => {
                let data_data = source.get()?;
                Ok(Payload::TransferToPublic {
                    data: Box::new(data_data),
                })
            }
            19 => {
                let to = source.get()?;
                let len: u8 = source.get()?;
                let schedule = crate::common::deserial_vector_no_length(source, len.into())?;
                Ok(Payload::TransferWithSchedule { to, schedule })
            }
            20 => {
                let cred_infos_len: u8 = source.get()?;
                let new_cred_infos =
                    crate::common::deserial_map_no_length(source, cred_infos_len.into())?;
                let remove_cred_ids_len: u8 = source.get()?;
                let remove_cred_ids =
                    crate::common::deserial_vector_no_length(source, remove_cred_ids_len.into())?;
                let new_threshold = source.get()?;
                Ok(Payload::UpdateCredentials {
                    new_cred_infos,
                    remove_cred_ids,
                    new_threshold,
                })
            }
            21 => {
                let data = source.get()?;
                Ok(Payload::RegisterData { data })
            }
            22 => {
                let to_address = source.get()?;
                let memo = source.get()?;
                let amount = source.get()?;
                Ok(Payload::TransferWithMemo {
                    to_address,
                    memo,
                    amount,
                })
            }
            23 => {
                let to = source.get()?;
                let memo = source.get()?;
                let data = source.get()?;
                Ok(Payload::EncryptedAmountTransferWithMemo { to, memo, data })
            }
            24 => {
                let to = source.get()?;
                let memo = source.get()?;
                let len: u8 = source.get()?;
                let schedule = crate::common::deserial_vector_no_length(source, len.into())?;
                Ok(Payload::TransferWithScheduleAndMemo { to, memo, schedule })
            }
            25 => {
                let bitmap: u16 = source.get()?;
                let mut capital = None;
                let mut restake_earnings = None;
                let mut open_for_delegation = None;
                let mut keys_with_proofs = None;
                let mut metadata_url = None;
                let mut transaction_fee_commission = None;
                let mut baking_reward_commission = None;
                let mut finalization_reward_commission = None;
                if bitmap & 1 != 0 {
                    capital = Some(source.get()?);
                }
                if bitmap & (1 << 1) != 0 {
                    restake_earnings = Some(source.get()?);
                }
                if bitmap & (1 << 2) != 0 {
                    open_for_delegation = Some(source.get()?);
                }
                if bitmap & (1 << 3) != 0 {
                    // this is serialized manually since the serialization in Haskell is not
                    // consistent with the serialization of baker add
                    // transactions. The order of fields is different.
                    let election_verify_key = source.get()?;
                    let proof_election = source.get()?;
                    let signature_verify_key = source.get()?;
                    let proof_sig = source.get()?;
                    let aggregation_verify_key = source.get()?;
                    let proof_aggregation = source.get()?;
                    keys_with_proofs = Some(BakerKeysPayload {
                        phantom: PhantomData,
                        election_verify_key,
                        signature_verify_key,
                        aggregation_verify_key,
                        proof_sig,
                        proof_election,
                        proof_aggregation,
                    });
                }
                if bitmap & (1 << 4) != 0 {
                    metadata_url = Some(source.get()?);
                }
                if bitmap & (1 << 5) != 0 {
                    transaction_fee_commission = Some(source.get()?);
                }
                if bitmap & (1 << 6) != 0 {
                    baking_reward_commission = Some(source.get()?);
                }
                if bitmap & (1 << 7) != 0 {
                    finalization_reward_commission = Some(source.get()?);
                }
                let data = Box::new(ConfigureBakerPayload {
                    capital,
                    restake_earnings,
                    open_for_delegation,
                    keys_with_proofs,
                    metadata_url,
                    transaction_fee_commission,
                    baking_reward_commission,
                    finalization_reward_commission,
                });
                Ok(Payload::ConfigureBaker { data })
            }
            26 => {
                let mut data = ConfigureDelegationPayload::default();
                let bitmap: u16 = source.get()?;
                anyhow::ensure!(
                    bitmap & 0b111 == bitmap,
                    "Incorrect bitmap for configure delegation."
                );
                if bitmap & 1 != 0 {
                    data.capital = Some(source.get()?);
                }
                if bitmap & (1 << 1) != 0 {
                    data.restake_earnings = Some(source.get()?);
                }
                if bitmap & (1 << 2) != 0 {
                    data.delegation_target = Some(source.get()?);
                }
                Ok(Payload::ConfigureDelegation { data })
            }
            _ => {
                anyhow::bail!("Unsupported transaction payload tag {}", tag)
            }
        }
    }
}

impl PayloadLike for Payload {
    fn encode(&self) -> EncodedPayload {
        let payload = crate::common::to_bytes(&self);
        EncodedPayload { payload }
    }

    fn encode_to_buffer<B: Buffer>(&self, out: &mut B) { out.put(&self) }
}

impl EncodedPayload {
    pub fn size(&self) -> PayloadSize {
        let size = self.payload.len() as u32;
        PayloadSize { size }
    }
}

/// Compute the transaction sign hash from an encoded payload and header.
pub fn compute_transaction_sign_hash(
    header: &TransactionHeader,
    payload: &impl PayloadLike,
) -> hashes::TransactionSignHash {
    let mut hasher = sha2::Sha256::new();
    hasher.put(header);
    payload.encode_to_buffer(&mut hasher);
    hashes::HashBytes::new(hasher.result())
}

/// Abstraction of private keys.
pub trait TransactionSigner {
    /// Sign the specified transaction hash, allocating and returning the
    /// signatures.
    fn sign_transaction_hash(
        &self,
        hash_to_sign: &hashes::TransactionSignHash,
    ) -> TransactionSignature;
}

/// A signing implementation that knows the number of keys up-front.
pub trait ExactSizeTransactionSigner: TransactionSigner {
    /// Return the number of keys that the signer will sign with.
    /// This must match what [TransactionSigner::sign_transaction_hash] returns.
    fn num_keys(&self) -> u32;
}

impl<S: TransactionSigner> TransactionSigner for std::sync::Arc<S> {
    fn sign_transaction_hash(
        &self,
        hash_to_sign: &hashes::TransactionSignHash,
    ) -> TransactionSignature {
        self.as_ref().sign_transaction_hash(hash_to_sign)
    }
}

impl<S: ExactSizeTransactionSigner> ExactSizeTransactionSigner for std::sync::Arc<S> {
    fn num_keys(&self) -> u32 { self.as_ref().num_keys() }
}

impl<S: TransactionSigner> TransactionSigner for std::rc::Rc<S> {
    fn sign_transaction_hash(
        &self,
        hash_to_sign: &hashes::TransactionSignHash,
    ) -> TransactionSignature {
        self.as_ref().sign_transaction_hash(hash_to_sign)
    }
}

impl<S: ExactSizeTransactionSigner> ExactSizeTransactionSigner for std::rc::Rc<S> {
    fn num_keys(&self) -> u32 { self.as_ref().num_keys() }
}

/// This signs with the first `threshold` credentials and for each
/// credential with the first threshold keys for that credential.
impl TransactionSigner for AccountKeys {
    fn sign_transaction_hash(
        &self,
        hash_to_sign: &hashes::TransactionSignHash,
    ) -> TransactionSignature {
        let iter = self
            .keys
            .iter()
            .take(usize::from(u8::from(self.threshold)))
            .map(|(k, v)| {
                (k, {
                    let num = u8::from(v.threshold);
                    v.keys.iter().take(num.into())
                })
            });
        let mut signatures = BTreeMap::<CredentialIndex, BTreeMap<KeyIndex, _>>::new();
        for (ci, cred_keys) in iter {
            let cred_sigs = cred_keys
                .into_iter()
                .map(|(ki, kp)| (*ki, kp.sign(hash_to_sign.as_ref()).into()))
                .collect::<BTreeMap<_, _>>();
            signatures.insert(*ci, cred_sigs);
        }
        TransactionSignature { signatures }
    }
}

impl ExactSizeTransactionSigner for AccountKeys {
    fn num_keys(&self) -> u32 {
        self.keys
            .values()
            .take(usize::from(u8::from(self.threshold)))
            .map(|v| u32::from(u8::from(v.threshold)))
            .sum::<u32>()
    }
}

impl<'a, X: TransactionSigner> TransactionSigner for &'a X {
    fn sign_transaction_hash(
        &self,
        hash_to_sign: &hashes::TransactionSignHash,
    ) -> TransactionSignature {
        (*self).sign_transaction_hash(hash_to_sign)
    }
}

impl<'a, X: ExactSizeTransactionSigner> ExactSizeTransactionSigner for &'a X {
    fn num_keys(&self) -> u32 { (*self).num_keys() }
}

impl TransactionSigner for BTreeMap<CredentialIndex, BTreeMap<KeyIndex, KeyPair>> {
    fn sign_transaction_hash(
        &self,
        hash_to_sign: &hashes::TransactionSignHash,
    ) -> TransactionSignature {
        let mut signatures = BTreeMap::<CredentialIndex, BTreeMap<KeyIndex, _>>::new();
        for (ci, cred_keys) in self {
            let cred_sigs = cred_keys
                .iter()
                .map(|(ki, kp)| (*ki, kp.sign(hash_to_sign.as_ref()).into()))
                .collect::<BTreeMap<_, _>>();
            signatures.insert(*ci, cred_sigs);
        }
        TransactionSignature { signatures }
    }
}

impl ExactSizeTransactionSigner for BTreeMap<CredentialIndex, BTreeMap<KeyIndex, KeyPair>> {
    fn num_keys(&self) -> u32 { self.values().map(|v| v.len() as u32).sum::<u32>() }
}

/// Sign the header and payload, construct the transaction, and return it.
pub fn sign_transaction<S: TransactionSigner, P: PayloadLike>(
    signer: &S,
    header: TransactionHeader,
    payload: P,
) -> AccountTransaction<P> {
    let hash_to_sign = compute_transaction_sign_hash(&header, &payload);
    let signature = signer.sign_transaction_hash(&hash_to_sign);
    AccountTransaction {
        signature,
        header,
        payload,
    }
}

/// Implementations of this trait are structures which can produce public keys
/// with which transaction signatures can be verified.
pub trait HasAccountAccessStructure {
    /// The number of credentials that must sign a transaction.
    fn threshold(&self) -> AccountThreshold;
    /// Access a credential at the provided index.
    fn credential_keys(&self, idx: CredentialIndex) -> Option<&CredentialPublicKeys>;
}

#[derive(PartialEq, Eq, Debug, Clone, concordium_std::Serialize)]
/// The most straighforward account access structure is a map of public keys
/// with the account threshold.
pub struct AccountAccessStructure {
    /// Keys indexed by credential.
    #[concordium(size_length = 1)]
    pub keys:      BTreeMap<CredentialIndex, CredentialPublicKeys>,
    /// The number of credentials that needed to sign a transaction.
    pub threshold: AccountThreshold,
}

/// Input parameter containing indices, signature thresholds,
/// and public keys for creating a new `AccountAccessStructure`.
pub type AccountStructure<'a> = &'a [(
    CredentialIndex,
    SignatureThreshold,
    &'a [(KeyIndex, ed25519_dalek::VerifyingKey)],
)];

impl AccountAccessStructure {
    /// Generate a new [`AccountAccessStructure`] for the thresholds, public
    /// keys, and key indices specified in the input. If there are duplicate
    /// indices then later ones override the previous ones.
    pub fn new(account_threshold: AccountThreshold, structure: AccountStructure) -> Self {
        let mut map: BTreeMap<CredentialIndex, CredentialPublicKeys> = BTreeMap::new();

        for credential_structure in structure {
            let mut inner_map: BTreeMap<KeyIndex, VerifyKey> = BTreeMap::new();

            for key_structure in credential_structure.2 {
                inner_map.insert(
                    key_structure.0,
                    VerifyKey::Ed25519VerifyKey(key_structure.1),
                );
            }

            map.insert(credential_structure.0, CredentialPublicKeys {
                keys:      inner_map,
                threshold: credential_structure.1,
            });
        }

        AccountAccessStructure {
            keys:      map,
            threshold: account_threshold,
        }
    }

    /// Generate a new [`AccountAccessStructure`] with a single credential and
    /// public key, at credential and key indices 0.
    pub fn singleton(public_key: ed25519_dalek::VerifyingKey) -> Self {
        Self::new(AccountThreshold::ONE, &[(
            0.into(),
            SignatureThreshold::ONE,
            &[(0.into(), public_key)],
        )])
    }
}

impl From<&AccountKeys> for AccountAccessStructure {
    fn from(value: &AccountKeys) -> Self {
        Self {
            threshold: value.threshold,
            keys:      value
                .keys
                .iter()
                .map(|(k, v)| {
                    (*k, CredentialPublicKeys {
                        keys:      v
                            .keys
                            .iter()
                            .map(|(ki, kp)| {
                                (
                                    *ki,
                                    VerifyKey::Ed25519VerifyKey(kp.as_ref().verifying_key()),
                                )
                            })
                            .collect(),
                        threshold: v.threshold,
                    })
                })
                .collect(),
        }
    }
}

impl HasAccountAccessStructure for AccountAccessStructure {
    fn threshold(&self) -> AccountThreshold { self.threshold }

    fn credential_keys(&self, idx: CredentialIndex) -> Option<&CredentialPublicKeys> {
        self.keys.get(&idx)
    }
}

// The serial and deserial implementations must match the serialization of
// `AccountInformation` in Haskell.
impl Serial for AccountAccessStructure {
    fn serial<B: Buffer>(&self, out: &mut B) {
        (self.keys.len() as u8).serial(out);
        for (k, v) in self.keys.iter() {
            k.serial(out);
            v.serial(out);
        }
        self.threshold.serial(out)
    }
}

// The serial and deserial implementations must match the serialization of
// `AccountInformation` in Haskell.
impl Deserial for AccountAccessStructure {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len = u8::deserial(source)?;
        let keys = common::deserial_map_no_length(source, len.into())?;
        let threshold = source.get()?;
        Ok(Self { threshold, keys })
    }
}

impl AccountAccessStructure {
    /// Return the total number of keys present in the access structure.
    pub fn num_keys(&self) -> u32 { self.keys.values().map(|m| m.keys.len() as u32).sum() }
}

/// Verify a signature on the transaction sign hash. This is a low-level
/// operation that is useful to avoid recomputing the transaction hash.
pub fn verify_signature_transaction_sign_hash(
    keys: &impl HasAccountAccessStructure,
    hash: &hashes::TransactionSignHash,
    signature: &TransactionSignature,
) -> bool {
    verify_data_signature(keys, hash, &signature.signatures)
}

/// Verify a signature on the provided data with respect to the account access
/// structure.
///
/// This is not the same as verifying a signature on a serialized transaction.
/// Transaction signature verification is a different protocol that first
/// involves hashing the message.
pub fn verify_data_signature<T: ?Sized + AsRef<[u8]>>(
    keys: &impl HasAccountAccessStructure,
    data: &T,
    signatures: &BTreeMap<CredentialIndex, BTreeMap<KeyIndex, Signature>>,
) -> bool {
    if usize::from(u8::from(keys.threshold())) > signatures.len() {
        return false;
    }
    // There are enough signatures.
    for (&ci, cred_sigs) in signatures.iter() {
        if let Some(cred_keys) = keys.credential_keys(ci) {
            if usize::from(u8::from(cred_keys.threshold)) > cred_sigs.len() {
                return false;
            }
            for (&ki, sig) in cred_sigs {
                if let Some(pk) = cred_keys.get(ki) {
                    if !pk.verify(data, sig) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
    }
    true
}

#[derive(Debug, Clone)]
/// A block item are data items that are transmitted on the network either as
/// separate messages, or as part of blocks. They are the only user-generated
/// (as opposed to protocol-generated) message.
pub enum BlockItem<PayloadType> {
    /// Account transactions are messages which are signed and paid for by an
    /// account.
    AccountTransaction(AccountTransaction<PayloadType>),
    /// Credential deployments create new accounts. They are not paid for
    /// directly by the sender. Instead, bakers are rewarded by the protocol for
    /// including them.
    CredentialDeployment(
        Box<
            AccountCredentialMessage<
                crate::id::constants::IpPairing,
                crate::id::constants::ArCurve,
                crate::id::constants::AttributeKind,
            >,
        >,
    ),
    UpdateInstruction(updates::UpdateInstruction),
}

impl<PayloadType> From<AccountTransaction<PayloadType>> for BlockItem<PayloadType> {
    fn from(at: AccountTransaction<PayloadType>) -> Self { Self::AccountTransaction(at) }
}

impl<PayloadType>
    From<
        AccountCredentialMessage<
            crate::id::constants::IpPairing,
            crate::id::constants::ArCurve,
            crate::id::constants::AttributeKind,
        >,
    > for BlockItem<PayloadType>
{
    fn from(
        at: AccountCredentialMessage<
            crate::id::constants::IpPairing,
            crate::id::constants::ArCurve,
            crate::id::constants::AttributeKind,
        >,
    ) -> Self {
        Self::CredentialDeployment(Box::new(at))
    }
}

impl<PayloadType> From<updates::UpdateInstruction> for BlockItem<PayloadType> {
    fn from(ui: updates::UpdateInstruction) -> Self { Self::UpdateInstruction(ui) }
}

impl<PayloadType> BlockItem<PayloadType> {
    /// Compute the hash of the block item that identifies the block item on the
    /// chain.
    pub fn hash(&self) -> hashes::TransactionHash
    where
        BlockItem<PayloadType>: Serial, {
        let mut hasher = sha2::Sha256::new();
        hasher.put(&self);
        hashes::HashBytes::new(hasher.result())
    }
}

impl<V> Serial for BakerKeysPayload<V> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.election_verify_key);
        out.put(&self.signature_verify_key);
        out.put(&self.aggregation_verify_key);
        out.put(&self.proof_sig);
        out.put(&self.proof_election);
        out.put(&self.proof_aggregation);
    }
}

impl<V> Deserial for BakerKeysPayload<V> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let election_verify_key = source.get()?;
        let signature_verify_key = source.get()?;
        let aggregation_verify_key = source.get()?;
        let proof_sig = source.get()?;
        let proof_election = source.get()?;
        let proof_aggregation = source.get()?;
        Ok(Self {
            phantom: PhantomData,
            election_verify_key,
            signature_verify_key,
            aggregation_verify_key,
            proof_sig,
            proof_election,
            proof_aggregation,
        })
    }
}

impl Serial for AddBakerPayload {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.keys);
        out.put(&self.baking_stake);
        out.put(&self.restake_earnings);
    }
}

impl Deserial for AddBakerPayload {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let keys = source.get()?;
        let baking_stake = source.get()?;
        let restake_earnings = source.get()?;
        Ok(Self {
            keys,
            baking_stake,
            restake_earnings,
        })
    }
}

impl Serial for InitContractPayload {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.amount);
        out.put(&self.mod_ref);
        out.put(&self.init_name);
        out.put(&self.param);
    }
}

impl Deserial for InitContractPayload {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let amount = source.get()?;
        let mod_ref = source.get()?;
        let init_name = source.get()?;
        let param = source.get()?;
        Ok(InitContractPayload {
            amount,
            mod_ref,
            init_name,
            param,
        })
    }
}

impl Serial for UpdateContractPayload {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.amount);
        out.put(&self.address);
        out.put(&self.receive_name);
        out.put(&self.message);
    }
}

impl Deserial for UpdateContractPayload {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let amount = source.get()?;
        let address = source.get()?;
        let receive_name = source.get()?;
        let message = source.get()?;
        Ok(UpdateContractPayload {
            amount,
            address,
            receive_name,
            message,
        })
    }
}

impl<P: PayloadLike> Serial for BlockItem<P> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        match &self {
            BlockItem::AccountTransaction(at) => {
                out.put(&0u8);
                out.put(at)
            }
            BlockItem::CredentialDeployment(acdi) => {
                out.put(&1u8);
                out.put(acdi);
            }
            BlockItem::UpdateInstruction(ui) => {
                out.put(&2u8);
                out.put(ui);
            }
        }
    }
}

impl Deserial for BlockItem<EncodedPayload> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let tag: u8 = source.get()?;
        match tag {
            0 => {
                let at = source.get()?;
                Ok(BlockItem::AccountTransaction(at))
            }
            1 => {
                let acdi = source.get()?;
                Ok(BlockItem::CredentialDeployment(acdi))
            }
            2 => {
                let ui = source.get()?;
                Ok(BlockItem::UpdateInstruction(ui))
            }
            _ => anyhow::bail!("Unsupported block item type: {}.", tag),
        }
    }
}

/// Energy costs of transactions.
pub mod cost {
    use crate::id::types::CredentialType;

    use super::*;

    /// The B constant for NRG assignment. This scales the effect of the number
    /// of signatures on the energy.
    pub const A: u64 = 100;

    /// The A constant for NRG assignment. This scales the effect of transaction
    /// size on the energy.
    pub const B: u64 = 1;

    /// Base cost of a transaction is the minimum cost that accounts for
    /// transaction size and signature checking. In addition to base cost
    /// each transaction has a transaction-type specific cost.
    pub fn base_cost(transaction_size: u64, num_signatures: u32) -> Energy {
        Energy::from(B * transaction_size + A * u64::from(num_signatures))
    }

    /// Additional cost of a normal, account to account, transfer.
    pub const SIMPLE_TRANSFER: Energy = Energy { energy: 300 };

    /// Additional cost of an encrypted transfer.
    pub const ENCRYPTED_TRANSFER: Energy = Energy { energy: 27000 };

    /// Additional cost of a transfer from public to encrypted balance.
    pub const TRANSFER_TO_ENCRYPTED: Energy = Energy { energy: 600 };

    /// Additional cost of a transfer from encrypted to public balance.
    pub const TRANSFER_TO_PUBLIC: Energy = Energy { energy: 14850 };

    /// Cost of a scheduled transfer, parametrized by the number of releases.
    pub fn scheduled_transfer(num_releases: u16) -> Energy {
        Energy::from(u64::from(num_releases) * (300 + 64))
    }

    /// Additional cost of registerding the account as a baker.
    pub const ADD_BAKER: Energy = Energy { energy: 4050 };

    /// Additional cost of updating baker's keys.
    pub const UPDATE_BAKER_KEYS: Energy = Energy { energy: 4050 };

    /// Additional cost of updating the baker's stake, either increasing or
    /// lowering it.
    pub const UPDATE_BAKER_STAKE: Energy = Energy { energy: 300 };

    /// Additional cost of updating the baker's restake flag.
    pub const UPDATE_BAKER_RESTAKE: Energy = Energy { energy: 300 };

    /// Additional cost of removing a baker.
    pub const REMOVE_BAKER: Energy = Energy { energy: 300 };

    /// Additional cost of updating existing credential keys. Parametrised by
    /// amount of existing credentials and new keys. Due to the way the
    /// accounts are stored a new copy of all credentials will be created,
    /// so we need to account for that storage increase.
    pub fn update_credential_keys(num_credentials_before: u16, num_keys: u16) -> Energy {
        Energy {
            energy: 500u64 * u64::from(num_credentials_before) + 100 * u64::from(num_keys),
        }
    }

    /// Additional cost of updating account's credentials, parametrized by
    /// - the number of credentials on the account before the update
    /// - list of keys of credentials to be added.
    pub fn update_credentials(num_credentials_before: u16, num_keys: &[u16]) -> Energy {
        UPDATE_CREDENTIALS_BASE + update_credentials_variable(num_credentials_before, num_keys)
    }

    /// Additional cost of registering a piece of data.
    pub const REGISTER_DATA: Energy = Energy { energy: 300 };

    /// Additional cost of configuring a baker if new keys are registered.
    pub const CONFIGURE_BAKER_WITH_KEYS: Energy = Energy { energy: 4050 };

    /// Additional cost of configuring a baker if new keys are **not**
    /// registered.
    pub const CONFIGURE_BAKER_WITHOUT_KEYS: Energy = Energy { energy: 300 };

    /// Additional cost of configuring delegation.
    pub const CONFIGURE_DELEGATION: Energy = Energy { energy: 300 };

    /// Additional cost of deploying a smart contract module, parametrized by
    /// the size of the module, which is defined to be the size of
    /// the binary `.wasm` file that is sent as part of the transaction.
    pub fn deploy_module(module_size: u64) -> Energy { Energy::from(module_size / 10) }

    /// There is a non-trivial amount of lookup
    /// that needs to be done before we can start any checking. This ensures
    /// that those lookups are not a problem. If the credential updates are
    /// genuine then this cost is going to be negligible compared to
    /// verifying the credential.
    const UPDATE_CREDENTIALS_BASE: Energy = Energy { energy: 500 };

    /// Additional cost of deploying a credential of the given type and with the
    /// given number of keys.
    pub fn deploy_credential(ty: CredentialType, num_keys: u16) -> Energy {
        match ty {
            CredentialType::Initial => Energy::from(1000 + 100 * u64::from(num_keys)),
            CredentialType::Normal => Energy::from(54000 + 100 * u64::from(num_keys)),
        }
    }

    /// Helper function. This together with [`UPDATE_CREDENTIALS_BASE`]
    /// determines the cost of updating credentials on an account.
    fn update_credentials_variable(num_credentials_before: u16, num_keys: &[u16]) -> Energy {
        // the 500 * num_credentials_before is to account for transactions which do
        // nothing, e.g., don't add don't remove, and don't update the
        // threshold. These still have a cost since the way the accounts are
        // stored it will update the stored account data, which does take up
        // quite a bit of space per credential.
        let energy: u64 = 500 * u64::from(num_credentials_before)
            + num_keys
                .iter()
                .map(|&nk| u64::from(deploy_credential(CredentialType::Normal, nk)))
                .sum::<u64>();
        Energy::from(energy)
    }
}

/// High level wrappers for making transactions with minimal user input.
/// These wrappers handle encoding, setting energy costs when those are fixed
/// for transaction.
/// See also the [send] module above which combines construction with signing.
pub mod construct {
    use super::*;

    /// A transaction that is prepared to be signed.
    /// The serde instance serializes the structured payload and skips
    /// serializing the encoded one.
    #[derive(Debug, Clone, SerdeSerialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PreAccountTransaction {
        pub header:       TransactionHeader,
        /// The payload.
        pub payload:      Payload,
        /// The encoded payload. This is already serialized payload that is
        /// constructed during construction of the prepared transaction
        /// since we need it to compute the cost.
        #[serde(skip_serializing)]
        pub encoded:      EncodedPayload,
        /// Hash of the transaction to sign.
        pub hash_to_sign: hashes::TransactionSignHash,
    }

    impl PreAccountTransaction {
        /// Sign the transaction with the provided signer. Note that this signer
        /// must match the account address and the number of keys that
        /// were used in construction, otherwise the transaction will be
        /// invalid.
        pub fn sign(self, signer: &impl TransactionSigner) -> AccountTransaction<EncodedPayload> {
            sign_transaction(signer, self.header, self.encoded)
        }
    }

    /// Serialize only the header and payload, so that this can be deserialized
    /// as a transaction body.
    impl Serial for PreAccountTransaction {
        fn serial<B: Buffer>(&self, out: &mut B) {
            self.header.serial(out);
            self.encoded.serial(out);
        }
    }

    impl Deserial for PreAccountTransaction {
        fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
            let header: TransactionHeader = source.get()?;
            let encoded = get_encoded_payload(source, header.payload_size)?;
            let payload = encoded.decode()?;
            let hash_to_sign = compute_transaction_sign_hash(&header, &encoded);
            Ok(Self {
                header,
                payload,
                encoded,
                hash_to_sign,
            })
        }
    }

    /// Helper structure to store the intermediate state of a transaction.
    /// The problem this helps solve is that to compute the exact energy
    /// requirements for the transaction we need to know its exact size when
    /// serialized. For some we could compute this manually, but in general it
    /// is less error prone to serialize and get the length. To avoid doing
    /// double work we first serialize with a dummy `energy_amount` value, then
    /// in the [TransactionBuilder::finalize] method we compute the correct
    /// energy amount and overwrite it in the transaction, before signing
    /// it.
    /// This is deliberately made private so that the inconsistent internal
    /// state does not leak.
    struct TransactionBuilder {
        header:  TransactionHeader,
        payload: Payload,
        encoded: EncodedPayload,
    }

    /// Size of a transaction header. This is currently always 60 bytes.
    /// Future chain updates might revise this, but this is a big change so this
    /// is expected to change seldomly.
    pub const TRANSACTION_HEADER_SIZE: u64 = 32 + 8 + 8 + 4 + 8;

    impl TransactionBuilder {
        pub fn new(
            sender: AccountAddress,
            nonce: Nonce,
            expiry: TransactionTime,
            payload: Payload,
        ) -> Self {
            let encoded = payload.encode();
            let header = TransactionHeader {
                sender,
                nonce,
                energy_amount: 0.into(),
                payload_size: encoded.size(),
                expiry,
            };
            Self {
                header,
                payload,
                encoded,
            }
        }

        #[inline]
        fn size(&self) -> u64 {
            TRANSACTION_HEADER_SIZE + u64::from(u32::from(self.header.payload_size))
        }

        #[inline]
        pub fn construct(mut self, f: impl FnOnce(u64) -> Energy) -> PreAccountTransaction {
            let size = self.size();
            self.header.energy_amount = f(size);
            let hash_to_sign = compute_transaction_sign_hash(&self.header, &self.encoded);
            PreAccountTransaction {
                header: self.header,
                payload: self.payload,
                encoded: self.encoded,
                hash_to_sign,
            }
        }
    }

    /// Construct a transfer transaction.
    pub fn transfer(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        amount: Amount,
    ) -> PreAccountTransaction {
        let payload = Payload::Transfer {
            to_address: receiver,
            amount,
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::SIMPLE_TRANSFER,
            },
            payload,
        )
    }

    /// Construct a transfer transaction with a memo.
    pub fn transfer_with_memo(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        amount: Amount,
        memo: Memo,
    ) -> PreAccountTransaction {
        let payload = Payload::TransferWithMemo {
            to_address: receiver,
            memo,
            amount,
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::SIMPLE_TRANSFER,
            },
            payload,
        )
    }

    /// Make an encrypted transfer. The payload can be constructed using
    /// [`make_transfer_data`](crate::encrypted_transfers::make_transfer_data).
    pub fn encrypted_transfer(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        data: EncryptedAmountTransferData<EncryptedAmountsCurve>,
    ) -> PreAccountTransaction {
        let payload = Payload::EncryptedAmountTransfer {
            to:   receiver,
            data: Box::new(data),
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::ENCRYPTED_TRANSFER,
            },
            payload,
        )
    }

    /// Make an encrypted transfer with a memo.
    /// The payload can be constructed using
    /// [make_transfer_data](crate::encrypted_transfers::make_transfer_data).
    pub fn encrypted_transfer_with_memo(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        data: EncryptedAmountTransferData<EncryptedAmountsCurve>,
        memo: Memo,
    ) -> PreAccountTransaction {
        // FIXME: This payload could be returned as well since it is only borrowed.
        let payload = Payload::EncryptedAmountTransferWithMemo {
            to: receiver,
            memo,
            data: Box::new(data),
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::ENCRYPTED_TRANSFER,
            },
            payload,
        )
    }

    /// Transfer the given amount from public to encrypted balance of the given
    /// account.
    pub fn transfer_to_encrypted(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        amount: Amount,
    ) -> PreAccountTransaction {
        let payload = Payload::TransferToEncrypted { amount };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::TRANSFER_TO_ENCRYPTED,
            },
            payload,
        )
    }

    /// Transfer the given amount from encrypted to public balance of the given
    /// account. The payload may be constructed using
    /// [`make_sec_to_pub_transfer_data`][anchor]
    ///
    /// [anchor]: crate::encrypted_transfers::make_sec_to_pub_transfer_data
    pub fn transfer_to_public(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        data: SecToPubAmountTransferData<EncryptedAmountsCurve>,
    ) -> PreAccountTransaction {
        // FIXME: This payload could be returned as well since it is only borrowed.
        let payload = Payload::TransferToPublic {
            data: Box::new(data),
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::TRANSFER_TO_PUBLIC,
            },
            payload,
        )
    }

    /// Construct a transfer with schedule transaction, sending to the given
    /// account.
    pub fn transfer_with_schedule(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        schedule: Vec<(Timestamp, Amount)>,
    ) -> PreAccountTransaction {
        let num_releases = schedule.len() as u16;
        let payload = Payload::TransferWithSchedule {
            to: receiver,
            schedule,
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::scheduled_transfer(num_releases),
            },
            payload,
        )
    }

    /// Construct a transfer with schedule and memo transaction, sending to the
    /// given account.
    pub fn transfer_with_schedule_and_memo(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        schedule: Vec<(Timestamp, Amount)>,
        memo: Memo,
    ) -> PreAccountTransaction {
        let num_releases = schedule.len() as u16;
        let payload = Payload::TransferWithScheduleAndMemo {
            to: receiver,
            memo,
            schedule,
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::scheduled_transfer(num_releases),
            },
            payload,
        )
    }

    /// Register the sender account as a baker.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    pub fn add_baker(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        baking_stake: Amount,
        restake_earnings: bool,
        keys: BakerAddKeysPayload,
    ) -> PreAccountTransaction {
        let payload = Payload::AddBaker {
            payload: Box::new(AddBakerPayload {
                keys,
                baking_stake,
                restake_earnings,
            }),
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::ADD_BAKER,
            },
            payload,
        )
    }

    /// Update keys of the baker associated with the sender account.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    pub fn update_baker_keys(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        keys: BakerUpdateKeysPayload,
    ) -> PreAccountTransaction {
        // FIXME: This payload could be returned as well since it is only borrowed.
        let payload = Payload::UpdateBakerKeys {
            payload: Box::new(keys),
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::UPDATE_BAKER_KEYS,
            },
            payload,
        )
    }

    /// Deregister the account as a baker.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    pub fn remove_baker(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
    ) -> PreAccountTransaction {
        // FIXME: This payload could be returned as well since it is only borrowed.
        let payload = Payload::RemoveBaker;
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::REMOVE_BAKER,
            },
            payload,
        )
    }

    /// Update the amount the account stakes for being a baker.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    pub fn update_baker_stake(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        new_stake: Amount,
    ) -> PreAccountTransaction {
        // FIXME: This payload could be returned as well since it is only borrowed.
        let payload = Payload::UpdateBakerStake { stake: new_stake };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::UPDATE_BAKER_STAKE,
            },
            payload,
        )
    }

    /// Update whether the earnings are automatically added to the baker's stake
    /// or not.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    pub fn update_baker_restake_earnings(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        restake_earnings: bool,
    ) -> PreAccountTransaction {
        // FIXME: This payload could be returned as well since it is only borrowed.
        let payload = Payload::UpdateBakerRestakeEarnings { restake_earnings };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::UPDATE_BAKER_RESTAKE,
            },
            payload,
        )
    }

    /// Construct a transction to register the given piece of data.
    pub fn register_data(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        data: RegisteredData,
    ) -> PreAccountTransaction {
        let payload = Payload::RegisterData { data };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::REGISTER_DATA,
            },
            payload,
        )
    }

    /// Deploy the given Wasm module. The module is given as a binary source,
    /// and no processing is done to the module.
    pub fn deploy_module(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        module: smart_contracts::WasmModule,
    ) -> PreAccountTransaction {
        let module_size = module.source.size();
        let payload = Payload::DeployModule { module };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::deploy_module(module_size),
            },
            payload,
        )
    }

    /// Initialize a smart contract, giving it the given amount of energy for
    /// execution. The unique parameters are
    /// - `energy` -- the amount of energy that can be used for contract
    ///   execution. The base energy amount for transaction verification will be
    ///   added to this cost.
    pub fn init_contract(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: InitContractPayload,
        energy: Energy,
    ) -> PreAccountTransaction {
        let payload = Payload::InitContract { payload };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add { num_sigs, energy },
            payload,
        )
    }

    /// Update a smart contract intance, giving it the given amount of energy
    /// for execution. The unique parameters are
    /// - `energy` -- the amount of energy that can be used for contract
    ///   execution. The base energy amount for transaction verification will be
    ///   added to this cost.
    pub fn update_contract(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: UpdateContractPayload,
        energy: Energy,
    ) -> PreAccountTransaction {
        let payload = Payload::Update { payload };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add { num_sigs, energy },
            payload,
        )
    }

    /// Configure the account as a baker. Only valid for protocol version 4 and
    /// up.
    pub fn configure_baker(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: ConfigureBakerPayload,
    ) -> PreAccountTransaction {
        let energy = if payload.keys_with_proofs.is_some() {
            cost::CONFIGURE_BAKER_WITH_KEYS
        } else {
            cost::CONFIGURE_BAKER_WITHOUT_KEYS
        };
        let payload = Payload::ConfigureBaker {
            data: Box::new(payload),
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add { num_sigs, energy },
            payload,
        )
    }

    /// Configure the account as a delegator. Only valid for protocol version 4
    /// and up.
    pub fn configure_delegation(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: ConfigureDelegationPayload,
    ) -> PreAccountTransaction {
        let payload = Payload::ConfigureDelegation { data: payload };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                num_sigs,
                energy: cost::CONFIGURE_DELEGATION,
            },
            payload,
        )
    }

    /// Construct a transaction to update keys of a single credential on an
    /// account. The transaction specific arguments are
    ///
    /// - `num_existing_credentials` - the number of existing credentials on the
    ///   account. This will affect the estimated transaction cost. It is safe
    ///   to over-approximate this.
    /// - `cred_id` - `credId` of a credential whose keys are to be updated.
    /// - `keys` - the new keys associated with the credential.
    pub fn update_credential_keys(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        num_existing_credentials: u16,
        cred_id: CredentialRegistrationID,
        keys: CredentialPublicKeys,
    ) -> PreAccountTransaction {
        let num_cred_keys = keys.keys.len() as u16;
        let payload = Payload::UpdateCredentialKeys { cred_id, keys };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                energy: cost::update_credential_keys(num_existing_credentials, num_cred_keys),
                num_sigs,
            },
            payload,
        )
    }

    /// Construct a transaction to update credentials on an account.
    /// The transaction specific arguments are
    ///
    /// - `num_existing_credentials` - the number of existing credentials on the
    ///   account. This will affect the estimated transaction cost. It is safe
    ///   to over-approximate this.
    /// - `new_credentials` - the new credentials to be deployed to the account
    ///   with the desired indices. The credential with index 0 cannot be
    ///   replaced.
    /// - `remove_credentials` - the list of credentials, by `credId`'s, to be
    ///   removed
    /// - `new_threshold` - the new account threshold.
    #[allow(clippy::too_many_arguments)]
    pub fn update_credentials(
        num_sigs: u32,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        num_existing_credentials: u16,
        new_credentials: AccountCredentialsMap,
        remove_credentials: Vec<CredentialRegistrationID>,
        new_threshold: AccountThreshold,
    ) -> PreAccountTransaction {
        let num_cred_keys = new_credentials
            .values()
            .map(|v| v.values.cred_key_info.keys.len() as u16)
            .collect::<Vec<_>>();
        let payload = Payload::UpdateCredentials {
            new_cred_infos: new_credentials,
            remove_cred_ids: remove_credentials,
            new_threshold,
        };
        make_transaction(
            sender,
            nonce,
            expiry,
            GivenEnergy::Add {
                energy: cost::update_credentials(num_existing_credentials, &num_cred_keys),
                num_sigs,
            },
            payload,
        )
    }

    /// An upper bound on the amount of energy to spend on a transaction.
    /// Transaction costs have two components, one is based on the size of the
    /// transaction and the number of signatures, and then there is a
    /// transaction specific one. This construction helps handle the fixed
    /// costs and allows the user to focus only on the transaction specific
    /// ones. The most important case for this are smart contract
    /// initialisations and updates.
    pub enum GivenEnergy {
        /// Use this exact amount of energy.
        Absolute(Energy),
        /// Add the given amount of energy to the base amount.
        /// The base amount covers transaction size and signature checking.
        Add { energy: Energy, num_sigs: u32 },
    }

    /// A convenience wrapper around `sign_transaction` that construct the
    /// transaction and signs it. Compared to transaction-type-specific wrappers
    /// above this allows selecting the amount of energy
    pub fn make_transaction(
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        energy: GivenEnergy,
        payload: Payload,
    ) -> PreAccountTransaction {
        let builder = TransactionBuilder::new(sender, nonce, expiry, payload);
        let cost = |size| match energy {
            GivenEnergy::Absolute(energy) => energy,
            GivenEnergy::Add { num_sigs, energy } => cost::base_cost(size, num_sigs) + energy,
        };
        builder.construct(cost)
    }
}

/// High level wrappers for making transactions with minimal user input.
/// These wrappers handle encoding, setting energy costs when those are fixed
/// for transaction.
pub mod send {
    use super::*;

    /// Construct a transfer transaction.
    pub fn transfer(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        amount: Amount,
    ) -> AccountTransaction<EncodedPayload> {
        construct::transfer(signer.num_keys(), sender, nonce, expiry, receiver, amount).sign(signer)
    }

    /// Construct a transfer transaction with a memo.
    pub fn transfer_with_memo(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        amount: Amount,
        memo: Memo,
    ) -> AccountTransaction<EncodedPayload> {
        construct::transfer_with_memo(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            receiver,
            amount,
            memo,
        )
        .sign(signer)
    }

    /// Make an encrypted transfer. The payload can be constructed using
    /// [`make_transfer_data`](crate::encrypted_transfers::make_transfer_data).
    pub fn encrypted_transfer(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        data: EncryptedAmountTransferData<EncryptedAmountsCurve>,
    ) -> AccountTransaction<EncodedPayload> {
        construct::encrypted_transfer(signer.num_keys(), sender, nonce, expiry, receiver, data)
            .sign(signer)
    }

    /// Make an encrypted transfer with a memo.
    /// The payload can be constructed using
    /// [`make_transfer_data`](crate::encrypted_transfers::make_transfer_data).
    pub fn encrypted_transfer_with_memo(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        data: EncryptedAmountTransferData<EncryptedAmountsCurve>,
        memo: Memo,
    ) -> AccountTransaction<EncodedPayload> {
        construct::encrypted_transfer_with_memo(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            receiver,
            data,
            memo,
        )
        .sign(signer)
    }

    /// Transfer the given amount from public to encrypted balance of the given
    /// account.
    pub fn transfer_to_encrypted(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        amount: Amount,
    ) -> AccountTransaction<EncodedPayload> {
        construct::transfer_to_encrypted(signer.num_keys(), sender, nonce, expiry, amount)
            .sign(signer)
    }

    /// Transfer the given amount from encrypted to public balance of the given
    /// account.
    /// The payload may be constructed using
    /// [`make_sec_to_pub_transfer_data`][anchor]
    ///
    /// [anchor]: crate::encrypted_transfers::make_sec_to_pub_transfer_data
    pub fn transfer_to_public(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        data: SecToPubAmountTransferData<EncryptedAmountsCurve>,
    ) -> AccountTransaction<EncodedPayload> {
        construct::transfer_to_public(signer.num_keys(), sender, nonce, expiry, data).sign(signer)
    }

    /// Construct a transfer with schedule transaction, sending to the given
    /// account.
    pub fn transfer_with_schedule(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        schedule: Vec<(Timestamp, Amount)>,
    ) -> AccountTransaction<EncodedPayload> {
        construct::transfer_with_schedule(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            receiver,
            schedule,
        )
        .sign(signer)
    }

    /// Construct a transfer with schedule and memo transaction, sending to the
    /// given account.
    pub fn transfer_with_schedule_and_memo(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        receiver: AccountAddress,
        schedule: Vec<(Timestamp, Amount)>,
        memo: Memo,
    ) -> AccountTransaction<EncodedPayload> {
        construct::transfer_with_schedule_and_memo(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            receiver,
            schedule,
            memo,
        )
        .sign(signer)
    }

    /// Register the sender account as a baker.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    #[allow(deprecated)]
    pub fn add_baker(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        baking_stake: Amount,
        restake_earnings: bool,
        keys: BakerAddKeysPayload,
    ) -> AccountTransaction<EncodedPayload> {
        construct::add_baker(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            baking_stake,
            restake_earnings,
            keys,
        )
        .sign(signer)
    }

    /// Update keys of the baker associated with the sender account.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    #[allow(deprecated)]
    pub fn update_baker_keys(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        keys: BakerUpdateKeysPayload,
    ) -> AccountTransaction<EncodedPayload> {
        construct::update_baker_keys(signer.num_keys(), sender, nonce, expiry, keys).sign(signer)
    }

    /// Deregister the account as a baker.
    ///
    /// **Note that this transaction only applies to protocol versions 1-3.**
    /// Use [`configure_baker`](Self::configure_baker) instead for protocols
    /// after 4.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    #[allow(deprecated)]
    pub fn remove_baker(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
    ) -> AccountTransaction<EncodedPayload> {
        construct::remove_baker(signer.num_keys(), sender, nonce, expiry).sign(signer)
    }

    /// Update the amount the account stakes for being a baker.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    #[allow(deprecated)]
    pub fn update_baker_stake(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        new_stake: Amount,
    ) -> AccountTransaction<EncodedPayload> {
        construct::update_baker_stake(signer.num_keys(), sender, nonce, expiry, new_stake)
            .sign(signer)
    }

    /// Update whether the earnings are automatically added to the baker's stake
    /// or not.
    #[deprecated(
        since = "2.0.0",
        note = "This transaction only applies to protocol versions 1-3. Use configure_baker \
                instead."
    )]
    #[doc(hidden)]
    #[allow(deprecated)]
    pub fn update_baker_restake_earnings(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        restake_earnings: bool,
    ) -> AccountTransaction<EncodedPayload> {
        construct::update_baker_restake_earnings(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            restake_earnings,
        )
        .sign(signer)
    }

    /// Configure the account as a baker. Only valid for protocol version 4 and
    /// up.
    pub fn configure_baker(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: ConfigureBakerPayload,
    ) -> AccountTransaction<EncodedPayload> {
        construct::configure_baker(signer.num_keys(), sender, nonce, expiry, payload).sign(signer)
    }

    /// Configure the account as a delegator. Only valid for protocol version 4
    /// and up.
    pub fn configure_delegation(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: ConfigureDelegationPayload,
    ) -> AccountTransaction<EncodedPayload> {
        construct::configure_delegation(signer.num_keys(), sender, nonce, expiry, payload)
            .sign(signer)
    }

    /// Construct a transaction to update keys of a single credential on an
    /// account. The transaction specific arguments are
    ///
    /// - `num_existing_credentials` - the number of existing credentials on the
    ///   account. This will affect the estimated transaction cost. It is safe
    ///   to over-approximate this.
    /// - `cred_id` - `credId` of a credential whose keys are to be updated.
    /// - `keys` - the new keys associated with the credential.
    pub fn update_credential_keys(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        num_existing_credentials: u16,
        cred_id: CredentialRegistrationID,
        keys: CredentialPublicKeys,
    ) -> AccountTransaction<EncodedPayload> {
        construct::update_credential_keys(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            num_existing_credentials,
            cred_id,
            keys,
        )
        .sign(signer)
    }

    /// Construct a transaction to update credentials on an account.
    /// The transaction specific arguments are
    ///
    /// - `num_existing_credentials` - the number of existing credentials on the
    ///   account. This will affect the estimated transaction cost. It is safe
    ///   to over-approximate this.
    /// - `new_credentials` - the new credentials to be deployed to the account
    ///   with the desired indices. The credential with index 0 cannot be
    ///   replaced.
    /// - `remove_credentials` - the list of credentials, by `credId`'s, to be
    ///   removed
    /// - `new_threshold` - the new account threshold.
    #[allow(clippy::too_many_arguments)]
    pub fn update_credentials(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        num_existing_credentials: u16,
        new_credentials: AccountCredentialsMap,
        remove_credentials: Vec<CredentialRegistrationID>,
        new_threshold: AccountThreshold,
    ) -> AccountTransaction<EncodedPayload> {
        construct::update_credentials(
            signer.num_keys(),
            sender,
            nonce,
            expiry,
            num_existing_credentials,
            new_credentials,
            remove_credentials,
            new_threshold,
        )
        .sign(signer)
    }

    /// Construct a transction to register the given piece of data.
    pub fn register_data(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        data: RegisteredData,
    ) -> AccountTransaction<EncodedPayload> {
        construct::register_data(signer.num_keys(), sender, nonce, expiry, data).sign(signer)
    }

    /// Deploy the given Wasm module. The module is given as a binary source,
    /// and no processing is done to the module.
    pub fn deploy_module(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        module: smart_contracts::WasmModule,
    ) -> AccountTransaction<EncodedPayload> {
        construct::deploy_module(signer.num_keys(), sender, nonce, expiry, module).sign(signer)
    }

    /// Initialize a smart contract, giving it the given amount of energy for
    /// execution. The unique parameters are
    /// - `energy` -- the amount of energy that can be used for contract
    ///   execution. The base energy amount for transaction verification will be
    ///   added to this cost.
    pub fn init_contract(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: InitContractPayload,
        energy: Energy,
    ) -> AccountTransaction<EncodedPayload> {
        construct::init_contract(signer.num_keys(), sender, nonce, expiry, payload, energy)
            .sign(signer)
    }

    /// Update a smart contract intance, giving it the given amount of energy
    /// for execution. The unique parameters are
    /// - `energy` -- the amount of energy that can be used for contract
    ///   execution. The base energy amount for transaction verification will be
    ///   added to this cost.
    pub fn update_contract(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        payload: UpdateContractPayload,
        energy: Energy,
    ) -> AccountTransaction<EncodedPayload> {
        construct::update_contract(signer.num_keys(), sender, nonce, expiry, payload, energy)
            .sign(signer)
    }

    #[derive(Debug, Copy, Clone)]
    /// An upper bound on the amount of energy to spend on a transaction.
    /// Transaction costs have two components, one is based on the size of the
    /// transaction and the number of signatures, and then there is a
    /// transaction specific one. This construction helps handle the fixed
    /// costs and allows the user to focus only on the transaction specific
    /// ones. The most important case for this are smart contract
    /// initialisations and updates.
    pub enum GivenEnergy {
        /// Use this exact amount of energy.
        Absolute(Energy),
        /// Add the given amount of energy to the base amount.
        /// The base amount covers transaction size and signature checking.
        Add(Energy),
    }

    /// A convenience wrapper around `sign_transaction` that construct the
    /// transaction and signs it. Compared to transaction-type-specific wrappers
    /// above this allows selecting the amount of energy
    pub fn make_and_sign_transaction(
        signer: &impl ExactSizeTransactionSigner,
        sender: AccountAddress,
        nonce: Nonce,
        expiry: TransactionTime,
        energy: GivenEnergy,
        payload: Payload,
    ) -> AccountTransaction<EncodedPayload> {
        match energy {
            GivenEnergy::Absolute(energy) => construct::make_transaction(
                sender,
                nonce,
                expiry,
                construct::GivenEnergy::Absolute(energy),
                payload,
            )
            .sign(signer),
            GivenEnergy::Add(energy) => construct::make_transaction(
                sender,
                nonce,
                expiry,
                construct::GivenEnergy::Add {
                    energy,
                    num_sigs: signer.num_keys(),
                },
                payload,
            )
            .sign(signer),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        hashes::TransactionSignHash,
        id::types::{SignatureThreshold, VerifyKey},
    };
    use rand::Rng;
    use std::convert::TryFrom;

    use super::*;
    #[test]
    fn test_transaction_signature_check() {
        let mut rng = rand::thread_rng();
        let mut keys = BTreeMap::<CredentialIndex, BTreeMap<KeyIndex, KeyPair>>::new();
        let bound: usize = rng.gen_range(1..20);
        for _ in 0..bound {
            let c_idx = CredentialIndex::from(rng.gen::<u8>());
            if keys.get(&c_idx).is_none() {
                let inner_bound: usize = rng.gen_range(1..20);
                let mut cred_keys = BTreeMap::new();
                for _ in 0..inner_bound {
                    let k_idx = KeyIndex::from(rng.gen::<u8>());
                    cred_keys.insert(k_idx, KeyPair::generate(&mut rng));
                }
                keys.insert(c_idx, cred_keys);
            }
        }
        let hash = TransactionSignHash::new(rng.gen());
        let sig = keys.sign_transaction_hash(&hash);
        let threshold =
            AccountThreshold::try_from(rng.gen_range(1..(keys.len() + 1) as u8)).unwrap();
        let pub_keys = keys
            .iter()
            .map(|(&ci, keys)| {
                let threshold =
                    SignatureThreshold::try_from(rng.gen_range(1..keys.len() + 1) as u8).unwrap();
                let keys = keys
                    .iter()
                    .map(|(&ki, kp)| (ki, VerifyKey::from(kp)))
                    .collect();
                (ci, CredentialPublicKeys { keys, threshold })
            })
            .collect::<BTreeMap<_, _>>();
        let mut access_structure = AccountAccessStructure {
            threshold,
            keys: pub_keys,
        };
        assert!(
            verify_signature_transaction_sign_hash(&access_structure, &hash, &sig),
            "Transaction signature must validate."
        );

        access_structure.threshold = AccountThreshold::try_from((keys.len() + 1) as u8).unwrap();

        assert!(
            !verify_signature_transaction_sign_hash(&access_structure, &hash, &sig),
            "Transaction signature must not validate with invalid threshold."
        );
    }
}