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
//! Main types used in the identity layer, and their serialization
//! implementations.
use super::secret_sharing::Threshold;
pub use crate::common::types::{AccountAddress, ACCOUNT_ADDRESS_SIZE};
use crate::{
    bulletproofs::{range_proof::RangeProof, utils::Generators},
    common::{
        types::{CredentialIndex, KeyIndex, KeyPair, Signature},
        *,
    },
    curve_arithmetic::*,
    dodis_yampolskiy_prf as prf,
    elgamal::{ChunkSize, Cipher, Message, SecretKey as ElgamalSecretKey},
    pedersen_commitment::{
        Commitment as PedersenCommitment, CommitmentKey as PedersenKey,
        Randomness as PedersenRandomness, Value as PedersenValue,
    },
    random_oracle::Challenge,
    sigma_protocols::{
        com_enc_eq, com_eq, com_eq_different_groups, com_eq_sig, com_mult,
        common::{ReplicateAdapter, ReplicateResponse},
        dlog,
    },
};
use anyhow::{anyhow, bail};
use byteorder::ReadBytesExt;
use concordium_contracts_common as concordium_std;
pub use concordium_contracts_common::SignatureThreshold;
use concordium_contracts_common::{AccountThreshold, ZeroSignatureThreshold};
use derive_more::*;
use ed25519_dalek as ed25519;
use ed25519_dalek::Verifier;
use either::Either;
use ff::Field;
use hex::{decode, encode};
use serde::{
    de, de::Visitor, ser::SerializeMap, Deserialize as SerdeDeserialize, Deserializer,
    Serialize as SerdeSerialize, Serializer,
};
use sha2::{Digest, Sha256};
use std::{
    cmp::Ordering,
    collections::{btree_map::BTreeMap, hash_map::HashMap, BTreeSet},
    convert::{TryFrom, TryInto},
    fmt,
    io::{Cursor, Read},
    str::FromStr,
};
use thiserror::Error;

/// NB: This includes digits of PI (starting with 314...) as ASCII characters
/// this could be what is desired, but it is important to be aware of it.
pub static PI_DIGITS: &[u8] = include_bytes!("../../data/pi-1000-digits.dat");

/// This is currently the number required, since the only
/// place these are used is for encrypted amounts.
pub const NUM_BULLETPROOF_GENERATORS: usize = 32 * 8;

/// Chunk size for encryption of prf key
pub const CHUNK_SIZE: ChunkSize = ChunkSize::ThirtyTwo;

/// Construct account address from the registration id.
pub fn account_address_from_registration_id(reg_id: &impl Curve) -> AccountAddress {
    let mut hasher = Sha256::new();
    reg_id.serial(&mut hasher);
    AccountAddress(hasher.finalize().into())
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, SerdeBase16Serialize)]
/// Signature by the identity provider on the initial account creation. This is
/// an ordinary ed25519 signature for performance reasons, and not the complex
/// BLS signature that the identity provider signs normal credentials with.
pub struct IpCdiSignature(ed25519::Signature);

impl std::ops::Deref for IpCdiSignature {
    type Target = ed25519::Signature;

    fn deref(&self) -> &Self::Target { &self.0 }
}

impl From<ed25519::Signature> for IpCdiSignature {
    fn from(sig: ed25519::Signature) -> Self { IpCdiSignature(sig) }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, SerdeBase16Serialize)]
/// Signature produced by the account holder when deploying a credential that
/// ensures that they are the owner of the account keys that are part of the
/// credential.
pub struct AccountOwnershipSignature(ed25519::Signature);

impl std::ops::Deref for AccountOwnershipSignature {
    type Target = ed25519::Signature;

    fn deref(&self) -> &Self::Target { &self.0 }
}

impl From<ed25519::Signature> for AccountOwnershipSignature {
    fn from(sig: ed25519::Signature) -> Self { AccountOwnershipSignature(sig) }
}

#[derive(Debug, PartialEq, Eq)]
/// A list of pairs of index of key and Ed25519 signatures on the challenge
/// of the proofs of the credential
/// The list should be non-empty and at most 255 elements long, and have no
/// duplicates. The current choice of data structure disallows duplicates by
/// design.
#[derive(SerdeSerialize, SerdeDeserialize, Clone)]
#[serde(transparent)]
pub struct AccountOwnershipProof {
    pub sigs: BTreeMap<KeyIndex, AccountOwnershipSignature>,
}

// Manual implementation to be able to encode length as 1, as well as to
// make sure there is at least one proof.
impl Serial for AccountOwnershipProof {
    fn serial<B: Buffer>(&self, out: &mut B) {
        let len = self.sigs.len() as u8;
        out.put(&len);
        serial_map_no_length(&self.sigs, out)
    }
}

impl Deserial for AccountOwnershipProof {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u8 = source.get()?;
        if len == 0 {
            bail!("Need at least one proof.")
        }
        let sigs = deserial_map_no_length(source, usize::from(len))?;
        Ok(AccountOwnershipProof { sigs })
    }
}

impl AccountOwnershipProof {
    /// Number of individual signatures in this proof.
    /// NB: This method relies on the invariant that signatures should not
    /// have more than 255 elements, and has at least one signature.
    pub fn num_proofs(&self) -> Result<SignatureThreshold, ZeroSignatureThreshold> {
        SignatureThreshold::try_from(self.sigs.len() as u8)
    }
}

#[derive(
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Clone,
    Copy,
    Hash,
    From,
    Serialize,
    SerdeSerialize,
    SerdeDeserialize,
    FromStr,
)]
#[repr(transparent)]
#[serde(transparent)]
/// A succinct identifier of an identity provider on the chain.
/// In credential deployments, and other interactions with the chain this is
/// used to identify which identity provider is meant.
pub struct IpIdentity(pub u32);

impl fmt::Display for IpIdentity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) }
}

#[derive(
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Clone,
    Copy,
    Hash,
    Serial,
    SerdeSerialize,
    SerdeDeserialize,
)]
#[serde(into = "u32", try_from = "u32")]
/// Identity of the anonymity revoker on the chain. This defines their
/// evaluation point for secret sharing, and thus it cannot be 0.
pub struct ArIdentity(u32);

impl Deserial for ArIdentity {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let x = source.get()?;
        if x == 0 {
            bail!("ArIdentity must be non-zero.")
        } else {
            Ok(ArIdentity(x))
        }
    }
}

impl fmt::Display for ArIdentity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) }
}

impl From<ArIdentity> for u32 {
    fn from(x: ArIdentity) -> Self { x.0 }
}

impl From<ArIdentity> for u64 {
    fn from(x: ArIdentity) -> Self { x.0.into() }
}

impl TryFrom<u32> for ArIdentity {
    type Error = &'static str;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value == 0 {
            Err("Zero is not a valid ArIdentity.")
        } else {
            Ok(ArIdentity(value))
        }
    }
}

impl FromStr for ArIdentity {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let x = u32::from_str(s).map_err(|_| "Could not read u32.")?;
        ArIdentity::try_from(x)
    }
}

impl ArIdentity {
    /// Curve scalars must be big enough to accommodate all 32 bit unsigned
    /// integers.
    pub fn to_scalar<C: Curve>(self) -> C::Scalar { C::scalar_from_u64(u64::from(self.0)) }

    #[cfg(any(test, feature = "internal-test-helpers"))]
    // This is unchecked, and only used in tests.
    pub fn new(x: u32) -> Self {
        assert_ne!(x, 0, "Trying to construct ArIdentity 0.");
        ArIdentity(x)
    }
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash, Serialize, Into)]
#[repr(transparent)]
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(try_from = "AttributeStringTag", into = "AttributeStringTag")]
/// Attribute tags have two representations. The "internal" one which is a u8
/// element, and an external, human-readable one, which is a string. There is a
/// defined mapping between them defined by the [ATTRIBUTE_NAMES] array (indices
/// are internal tags, values at those indices are string tags).
/// The JSON instances for this type are via the [AttributeStringTag] type
/// defined below.
pub struct AttributeTag(pub u8);

impl std::borrow::Borrow<u8> for AttributeTag {
    fn borrow(&self) -> &u8 { &self.0 }
}

/// NB: The length of this list must be less than 256.
/// This must be consistent with the value of attributeNames in
/// haskell-src/Concordium/ID/Types.hs
pub const ATTRIBUTE_NAMES: [&str; 14] = [
    "firstName",
    "lastName",
    "sex",
    "dob",
    "countryOfResidence",
    "nationality",
    "idDocType",
    "idDocNo",
    "idDocIssuer",
    "idDocIssuedAt",
    "idDocExpiresAt",
    "nationalIdNo",
    "taxIdNo",
    "lei",
];

/// Attribute tag for the LEI attribute.
pub const ATTRIBUTE_TAG_LEI: AttributeTag = AttributeTag(13);

#[derive(Debug, PartialEq, Eq, Clone)]
#[repr(transparent)]
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(transparent)]
/// Attribute tags have two representations. The "internal" one which is a u8
/// element, and an external, human-readable one, which is a string. There is a
/// defined mapping between them defined by the [ATTRIBUTE_NAMES] array (indices
/// are internal tags, values at those indices are string tags).
pub struct AttributeStringTag(String);

impl fmt::Display for AttributeStringTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) }
}

// NB: This requires that the length of ATTRIBUTE_NAMES is no more than 256.
// FIXME: This method's complexity is linear in the size of the set of
// attributes.
impl TryFrom<AttributeStringTag> for AttributeTag {
    type Error = anyhow::Error;

    fn try_from(v: AttributeStringTag) -> Result<Self, Self::Error> {
        if let Some(idx) = ATTRIBUTE_NAMES.iter().position(|&x| x == v.0) {
            Ok(AttributeTag(idx as u8))
        } else {
            match v.0.strip_prefix("UNNAMED#").and_then(|x| x.parse().ok()) {
                Some(num) if num < 254 => Ok(AttributeTag(num)), // 254 is the capacity of the
                // BLS curve field
                _ => Err(anyhow!("Unrecognized attribute tag.")),
            }
        }
    }
}

impl std::convert::From<AttributeTag> for AttributeStringTag {
    fn from(v: AttributeTag) -> Self {
        let v_usize: usize = v.into();
        if v_usize < ATTRIBUTE_NAMES.len() {
            AttributeStringTag(ATTRIBUTE_NAMES[v_usize].to_owned())
        } else {
            AttributeStringTag(format!("UNNAMED#{}", v.0))
        }
    }
}

impl fmt::Display for AttributeTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let l: usize = (*self).into();
        if l < ATTRIBUTE_NAMES.len() {
            f.write_str(ATTRIBUTE_NAMES[l])
        } else {
            write!(f, "UNNAMED#{}", l)
        }
    }
}

impl std::str::FromStr for AttributeTag {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(idx) = ATTRIBUTE_NAMES.iter().position(|&x| x == s) {
            Ok(AttributeTag(idx as u8))
        } else {
            match s.strip_prefix("UNNAMED#").and_then(|x| x.parse().ok()) {
                Some(num) if num < 254 => Ok(AttributeTag(num)), // 254 is the capacity of the
                // BLS curve field
                _ => Err(anyhow!("Unrecognized attribute tag.")),
            }
        }
    }
}

impl From<AttributeTag> for usize {
    fn from(tag: AttributeTag) -> Self { tag.0.into() }
}

impl From<u8> for AttributeTag {
    fn from(tag: u8) -> Self { AttributeTag(tag) }
}

/// An abstraction of an attribute. In the id library internals the only thing
/// we care about attributes is that they can be encoded as field elements.
/// The meaning of attributes is then assigned at the outer layers when the
/// library is used. In order to make the library as generic (and ultimately
/// simple) as possible this trait is used.
pub trait Attribute<F: Field>:
    Clone + Sized + Send + Sync + fmt::Display + Serialize + Ord {
    /// Convert an attribute to a field element
    fn to_field_element(&self) -> F;
}

/// YearMonth in Gregorian calendar.
/// The year is in Gregorian calendar and months are numbered from 1, i.e.,
/// 1 is January, ..., 12 is December.
/// Year must be a 4 digit year, i.e., between 1000 and 9999.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct YearMonth {
    pub year:  u16,
    pub month: u8,
}

impl YearMonth {
    /// Return the time at the beginning of the month. This is typically
    /// used as the lower bound of a validity of a credential.
    pub fn lower(self) -> Option<chrono::DateTime<chrono::Utc>> {
        let date = chrono::NaiveDate::from_ymd_opt(self.year.into(), self.month.into(), 1)?;
        let time = chrono::NaiveTime::from_hms_opt(0, 0, 0)?;
        let dt = date.and_time(time);
        Some(chrono::DateTime::from_utc(dt, chrono::Utc))
    }

    /// Return the time at the beginning of the next month. This is typically
    /// used as the strict upper bound of a validity of a credential.
    pub fn upper(self) -> Option<chrono::DateTime<chrono::Utc>> {
        let date = chrono::NaiveDate::from_ymd_opt(self.year.into(), self.month.into(), 1)?;
        let time = chrono::NaiveTime::from_hms_opt(0, 0, 0)?;
        let date = date.checked_add_months(chrono::Months::new(1))?;
        let dt = date.and_time(time);
        Some(chrono::DateTime::from_utc(dt, chrono::Utc))
    }
}

impl ToString for YearMonth {
    fn to_string(&self) -> String { format!("{:04}{:02}", self.year, self.month) }
}

impl SerdeSerialize for YearMonth {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer, {
        let s = format!("{}{:0>2}", self.year, self.month);
        serializer.serialize_str(&s)
    }
}

impl<'de> SerdeDeserialize<'de> for YearMonth {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>, {
        deserializer.deserialize_str(YearMonthVisitor)
    }
}

struct YearMonthVisitor;

impl<'de> Visitor<'de> for YearMonthVisitor {
    type Value = YearMonth;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a year and month in format YYYYMM")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: de::Error, {
        YearMonth::from_str(s).map_err(de::Error::custom)
    }
}

impl Serial for YearMonth {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.year);
        out.put(&self.month);
    }
}

impl Deserial for YearMonth {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let year = source.get()?;
        let month = source.get()?;
        YearMonth::new(year, month).ok_or_else(|| anyhow!("Invalid year/month."))
    }
}

impl std::str::FromStr for YearMonth {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> ParseResult<Self> {
        if !s.chars().all(|c| c.is_ascii() && c.is_numeric()) {
            bail!("Unsupported date in format YYYYMM")
        }
        if s.len() != 6 {
            bail!("Invalid length of YYYYMM.")
        }
        let (s_year, s_month) = s.split_at(4);
        let year = s_year.parse::<u16>()?;
        let month = s_month.parse::<u8>()?;
        if let Some(ym) = YearMonth::new(year, month) {
            Ok(ym)
        } else {
            bail!("Year or month out of range.")
        }
    }
}

impl YearMonth {
    /// Construct a new YearMonth object.
    /// This method checks that year and month are in range.
    pub fn new(year: u16, month: u8) -> Option<Self> {
        if (1000..10000).contains(&year) && (1..=12).contains(&month) {
            Some(YearMonth { year, month })
        } else {
            None
        }
    }

    pub fn now() -> YearMonth {
        use chrono::Datelike;
        let now = chrono::Utc::now();
        YearMonth {
            year:  now.year() as u16,
            month: now.month() as u8,
        }
    }

    /// Construct a [`YearMonth`](Self) from a unix timestamp in seconds.
    /// This fails if the conversion would lead to an out of range value,
    /// meaning a year outside of the range `1000..=9999`.
    pub fn from_timestamp(unix_seconds: i64) -> Option<YearMonth> {
        use chrono::{Datelike, TimeZone};
        let date = chrono::Utc.timestamp_opt(unix_seconds, 0).earliest()?;
        let year = date.year().try_into().ok()?;
        let month = date.month().try_into().ok()?;
        Self::new(year, month)
    }
}

impl TryFrom<u64> for YearMonth {
    type Error = ();

    /// Try to convert unsigned 64-bit integer to year and month. Least
    /// significant byte is month, following two bytes is year in big endian
    fn try_from(v: u64) -> Result<Self, Self::Error> {
        let month = (v & 0xFF) as u8;
        let year = ((v >> 8) & 0xFFFF) as u16;
        YearMonth::new(year, month).ok_or(())
    }
}

impl From<YearMonth> for u64 {
    /// Convert expiry (year and month) to unsigned 64-bit integer.
    /// Least significant byte is month, following two bytes are year
    fn from(v: YearMonth) -> Self { u64::from(v.month) | (u64::from(v.year) << 8) }
}

impl From<&YearMonth> for u64 {
    /// Convert expiry (year and month) to unsigned 64-bit integer.
    /// Least significant byte is month, following two bytes are year
    fn from(v: &YearMonth) -> Self { u64::from(v.month) | (u64::from(v.year) << 8) }
}

impl From<&YearMonth> for u32 {
    /// Convert expiry (year and month) to unsigned 32-bit integer.
    /// Least significant byte is month, following two bytes are year
    fn from(v: &YearMonth) -> Self { u32::from(v.month) | (u32::from(v.year) << 8) }
}

impl From<YearMonth> for u32 {
    /// Convert expiry (year and month) to unsigned 32-bit integer.
    /// Least significant byte is month, following two bytes are year
    fn from(v: YearMonth) -> Self { u32::from(v.month) | (u32::from(v.year) << 8) }
}

#[derive(Clone, Debug, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "F: Field, AttributeType: Attribute<F> + SerdeSerialize",
    deserialize = "F: Field, AttributeType: Attribute<F> + SerdeDeserialize<'de>"
))]
/// An attribute list that is part of a normal credential. It consists of some
/// mandatory attributes and some user selected attributes.
pub struct AttributeList<F: Field, AttributeType: Attribute<F>> {
    #[serde(rename = "validTo")]
    /// The latest month and year where the credential is still valid.
    pub valid_to:     YearMonth,
    #[serde(rename = "createdAt")]
    /// The year and month when the identity object from which the credential is
    /// derived was created. This deliberately has low granularity since if it
    /// was, e.g., a unix timestamp in seconds then the identity provider could
    /// link accounts on the chain to identities they have issued.
    pub created_at:   YearMonth,
    /// Maximum number of accounts that can be created from the owning identity
    /// object.
    #[serde(rename = "maxAccounts")]
    pub max_accounts: u8,
    /// The attributes map. The map size can be at most `k` where `k` is the
    /// number of bits that fit into a field element.
    #[serde(rename = "chosenAttributes")]
    #[map_size_length = 2]
    pub alist:        BTreeMap<AttributeTag, AttributeType>,
    #[serde(skip)]
    pub _phantom:     std::marker::PhantomData<F>,
}

impl<F: Field, AttributeType: Attribute<F>> HasAttributeValues<F, AttributeTag, AttributeType>
    for AttributeList<F, AttributeType>
{
    fn get_attribute_value(&self, attribute_tag: &AttributeTag) -> Option<&AttributeType> {
        self.alist.get(attribute_tag)
    }
}

#[derive(Debug, Serialize)]
/// In our case C: will be G1 and T will be G1 for now A secret credential is
/// a scalar raising a generator to this scalar gives a public credentials. If
/// two groups have the same scalar field we can have two different public
/// credentials from the same secret credentials.
#[derive(SerdeBase16Serialize, From, Into)]
pub struct IdCredentials<C: Curve> {
    /// Secret id credentials.
    /// Since the use of this value is quite complex, we allocate
    /// it on the heap and retain a pointer to it for easy sharing.
    pub id_cred_sec: PedersenValue<C>,
}

impl<C: Curve> IdCredentials<C> {
    /// Use a cryptographically secure random number generator to
    /// generate a fresh secret credential.
    pub fn generate<R: rand::Rng>(csprng: &mut R) -> Self {
        IdCredentials {
            id_cred_sec: PedersenValue::generate(csprng),
        }
    }
}

/// Private credential holder information. A user maintaints these
/// through many different interactions with the identity provider and
/// the chain.
#[derive(Debug, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct CredentialHolderInfo<C: Curve> {
    /// Public and private keys of the credential holder. NB: These are distinct
    /// from the public/private keys of the account holders.
    #[serde(rename = "idCredSecret")]
    pub id_cred: IdCredentials<C>,
}

/// Private and public data chosen by the credential holder before the
/// interaction with the identity provider. The credential holder chooses a prf
/// key and an attribute list.
#[derive(Debug, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct AccCredentialInfo<C: Curve> {
    #[serde(rename = "credentialHolderInformation")]
    pub cred_holder_info: CredentialHolderInfo<C>,
    /// Chosen prf key of the credential holder.
    #[serde(rename = "prfKey")]
    pub prf_key:          prf::SecretKey<C>,
}

/// The data relating to a single anonymity revoker
/// sent by the account holder to the identity provider.
/// Typically the account holder will send a vector of these.
#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct IpArData<C: Curve> {
    /// Encryption in chunks (in little endian) of the PRF key share
    #[serde(
        rename = "encPrfKeyShare",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub enc_prf_key_share: [Cipher<C>; 8],
    /// Response in the proof that the computed commitment to the share
    /// contains the same value as the encryption
    /// the commitment to the share is not sent but computed from
    /// the commitments to the sharing coefficients
    #[serde(rename = "proofComEncEq")]
    pub proof_com_enc_eq:  com_enc_eq::Response<C>,
}

/// Data structure for when a anonymity revoker decrypts its encrypted share
/// This is the decrypted counterpart of IpArData.
#[derive(Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct IpArDecryptedData<C: Curve> {
    /// identity of the anonymity revoker
    #[serde(rename = "arIdentity")]
    pub ar_identity:   ArIdentity,
    /// share of prf key
    #[serde(rename = "prfKeyShare")]
    pub prf_key_share: Value<C>,
}

/// Data relating to a single anonymity revoker sent by the account holder to
/// the chain.
/// Typically a vector of these will be sent to the chain.
#[derive(Debug, PartialEq, Eq, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct ChainArData<C: Curve> {
    /// encrypted share of id cred pub
    #[serde(rename = "encIdCredPubShare")]
    pub enc_id_cred_pub_share: Cipher<C>,
}

/// Data structure for when a anonymity revoker decrypts its encrypted share
/// This is the decrypted counterpart of ChainArData.
/// This structure contains an explicit ArIdentity in contrast to the
/// `ChainArData`. The reason for that is the use-case for this structure is
/// that an individual anonymity revoker decrypts its share and sends it, and we
/// need the context for that. In the other cases the data is always in the
/// context of a credential or pre-identity object, and as a result part of the
/// map.
#[derive(Debug, PartialEq, Eq, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct ChainArDecryptedData<C: Curve> {
    /// identity of the anonymity revoker
    #[serde(rename = "arIdentity")]
    pub ar_identity:       ArIdentity,
    /// share of id cred pub
    #[serde(rename = "idCredPubShare")]
    pub id_cred_pub_share: Message<C>,
}

// NOTE: This struct is redundant, but we will
// will keep it for now for compatibility.
// We need to remove it in the future.
/// Choice of anonymity revocation parameters
#[derive(Debug, Clone, SerdeSerialize, SerdeDeserialize, Serialize)]
pub struct ChoiceArParameters {
    #[serde(rename = "arIdentities")]
    #[set_size_length = 2]
    pub ar_identities: BTreeSet<ArIdentity>,
    #[serde(rename = "threshold")]
    pub threshold:     Threshold,
}

/// Proof that the data sent to the identity provider
/// is well-formed. The serialize instance is implemented manually in order to
/// be backwards-compatible.
#[derive(Debug, Clone)]
pub struct PreIdentityProof<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    pub common_proof_fields: CommonPioProofFields<P, C>,
    /// Response in the proof that reg_id = PRF(prf_key, 0)
    pub prf_regid_proof:     com_eq::Response<C>,
    /// Signature on the public information for the IP from the account holder
    pub proof_acc_sk:        AccountOwnershipProof,
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>> Serial for PreIdentityProof<P, C> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.common_proof_fields.challenge);
        out.put(&self.common_proof_fields.id_cred_sec_response);
        out.put(&self.common_proof_fields.commitments_same_proof);
        out.put(&self.common_proof_fields.commitments_prf_same);
        out.put(&self.prf_regid_proof);
        out.put(&self.proof_acc_sk);
        out.put(&self.common_proof_fields.bulletproofs);
    }
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>> Deserial for PreIdentityProof<P, C> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let challenge: Challenge = source.get()?;
        let id_cred_sec_response: dlog::Response<C> = source.get()?;
        let commitments_same_proof: com_eq::Response<C> = source.get()?;
        let commitments_prf_same: com_eq_different_groups::Response<P::G1, C> = source.get()?;
        let prf_regid_proof: com_eq::Response<C> = source.get()?;
        let proof_acc_sk: AccountOwnershipProof = source.get()?;
        let bulletproofs: Vec<RangeProof<C>> = source.get()?;
        let common_proof_fields = CommonPioProofFields {
            challenge,
            id_cred_sec_response,
            commitments_same_proof,
            commitments_prf_same,
            bulletproofs,
        };
        Ok(PreIdentityProof {
            common_proof_fields,
            prf_regid_proof,
            proof_acc_sk,
        })
    }
}

/// Common proof for both identity creation flows that the data sent to the
/// identity provider is well-formed.
#[derive(Debug, Clone, Serialize)]
pub struct CommonPioProofFields<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    /// Challenge for the combined proof. This includes the three proofs below,
    /// and additionally also the proofs in IpArData.
    pub challenge:              Challenge,
    /// Response in the proof of knowledge of IdCredSec.
    pub id_cred_sec_response:   dlog::Response<C>,
    /// Response in the proof that cmm_sc and id_cred_pub
    /// are hiding the same id_cred_sec.
    pub commitments_same_proof: com_eq::Response<C>,
    /// Response in the proof that cmm_prf and the
    /// second commitment to the prf key (hidden in cmm_prf_sharing_coeff)
    /// are hiding the same value.
    pub commitments_prf_same:   com_eq_different_groups::Response<P::G1, C>,
    /// Bulletproofs for showing that chunks are small so that encryption
    /// of the prf key can be decrypted
    pub bulletproofs:           Vec<RangeProof<C>>,
}

/// A type alias for the combined proofs relating to the shared encryption of
/// IdCredPub.
pub type IdCredPubVerifiers<C> = (
    ReplicateAdapter<com_enc_eq::ComEncEq<C>>,
    ReplicateResponse<com_enc_eq::Response<C>>,
);

/// Information sent from the account holder to the identity provider.
/// This includes only the cryptographic parts, the attribute list is
/// in a different object below. This is for the flow, where a initial account
/// is to be created.
#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>",
    deserialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>"
))]
pub struct PreIdentityObject<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    // TODO: consider renaming this struct
    /// Public credential of the account holder in the anonymity revoker's
    /// group.
    #[serde(rename = "pubInfoForIp")]
    pub pub_info_for_ip:       PublicInformationForIp<C>,
    /// Anonymity revocation data for the chosen anonymity revokers.
    #[serde(rename = "ipArData")]
    #[map_size_length = 4]
    pub ip_ar_data:            BTreeMap<ArIdentity, IpArData<C>>,
    /// Choice of anonyimity revocation parameters.
    /// NB:IP needs to check that they make sense in the context of the public
    /// keys they are allowed to use.
    #[serde(rename = "choiceArData")]
    pub choice_ar_parameters:  ChoiceArParameters,
    /// Commitment to id cred sec using the commitment key of IP derived from
    /// the PS public key. This is used to compute the message that the IP
    /// signs.
    #[serde(rename = "idCredSecCommitment")]
    pub cmm_sc:                PedersenCommitment<P::G1>,
    /// Commitment to the prf key in group G1.
    #[serde(rename = "prfKeyCommitmentWithIP")]
    pub cmm_prf:               PedersenCommitment<P::G1>,
    /// commitments to the coefficients of the polynomial
    /// used to share the prf key
    /// K + b1 X + b2 X^2...
    /// where K is the prf key
    #[serde(rename = "prfKeySharingCoeffCommitments")]
    pub cmm_prf_sharing_coeff: Vec<PedersenCommitment<C>>,
    /// Proofs of knowledge. See the documentation of PreIdentityProof for
    /// details.
    #[serde(
        rename = "proofsOfKnowledge",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub poks:                  PreIdentityProof<P, C>,
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>> PreIdentityObject<P, C> {
    pub fn get_common_pio_fields(&self) -> CommonPioFields<P, C> {
        CommonPioFields {
            ip_ar_data:            &self.ip_ar_data,
            choice_ar_parameters:  &self.choice_ar_parameters,
            cmm_sc:                &self.cmm_sc,
            cmm_prf:               &self.cmm_prf,
            cmm_prf_sharing_coeff: &self.cmm_prf_sharing_coeff,
        }
    }
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>> PreIdentityObjectV1<P, C> {
    pub fn get_common_pio_fields(&self) -> CommonPioFields<P, C> {
        CommonPioFields {
            ip_ar_data:            &self.ip_ar_data,
            choice_ar_parameters:  &self.choice_ar_parameters,
            cmm_sc:                &self.cmm_sc,
            cmm_prf:               &self.cmm_prf,
            cmm_prf_sharing_coeff: &self.cmm_prf_sharing_coeff,
        }
    }
}

/// Information sent from the account holder to the identity provider.
/// This includes only the cryptographic parts, the attribute list is
/// in a different object below. This is for the flow, where no initial account
/// is involved.
#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>",
    deserialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>"
))]
pub struct PreIdentityObjectV1<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    // TODO: consider renaming this struct
    #[serde(
        rename = "idCredPub",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub id_cred_pub:           C,
    /// Anonymity revocation data for the chosen anonymity revokers.
    #[serde(rename = "ipArData")]
    #[map_size_length = 4]
    pub ip_ar_data:            BTreeMap<ArIdentity, IpArData<C>>,
    /// Choice of anonyimity revocation parameters.
    /// NB:IP needs to check that they make sense in the context of the public
    /// keys they are allowed to use.
    #[serde(rename = "choiceArData")]
    pub choice_ar_parameters:  ChoiceArParameters,
    /// Commitment to id cred sec using the commitment key of IP derived from
    /// the PS public key. This is used to compute the message that the IP
    /// signs.
    #[serde(rename = "idCredSecCommitment")]
    pub cmm_sc:                PedersenCommitment<P::G1>,
    /// Commitment to the prf key in group G1.
    #[serde(rename = "prfKeyCommitmentWithIP")]
    pub cmm_prf:               PedersenCommitment<P::G1>,
    /// commitments to the coefficients of the polynomial
    /// used to share the prf key
    /// K + b1 X + b2 X^2...
    /// where K is the prf key
    #[serde(rename = "prfKeySharingCoeffCommitments")]
    pub cmm_prf_sharing_coeff: Vec<PedersenCommitment<C>>,
    /// Proofs of knowledge. See the documentation of PreIdentityProof for
    /// details.
    #[serde(
        rename = "proofsOfKnowledge",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub poks:                  CommonPioProofFields<P, C>,
}

pub struct CommonPioFields<'a, P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    /// Anonymity revocation data for the chosen anonymity revokers.
    pub ip_ar_data:            &'a BTreeMap<ArIdentity, IpArData<C>>,
    /// Choice of anonyimity revocation parameters.
    /// NB:IP needs to check that they make sense in the context of the public
    /// keys they are allowed to use.
    pub choice_ar_parameters:  &'a ChoiceArParameters,
    /// Commitment to id cred sec using the commitment key of IP derived from
    /// the PS public key. This is used to compute the message that the IP
    /// signs.
    pub cmm_sc:                &'a PedersenCommitment<P::G1>,
    /// Commitment to the prf key in group G1.
    pub cmm_prf:               &'a PedersenCommitment<P::G1>,
    /// commitments to the coefficients of the polynomial
    /// used to share the prf key
    /// K + b1 X + b2 X^2...
    /// where K is the prf key
    pub cmm_prf_sharing_coeff: &'a Vec<PedersenCommitment<C>>,
}

/// The data we get back from the identity provider in the version 0 flow.
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>, AttributeType: Attribute<C::Scalar> \
                 + SerdeSerialize",
    deserialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>, AttributeType: \
                   Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub struct IdentityObject<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(rename = "preIdentityObject")]
    pub pre_identity_object: PreIdentityObject<P, C>,
    /// Chosen attribute list.
    #[serde(rename = "attributeList")]
    pub alist:               AttributeList<C::Scalar, AttributeType>,
    #[serde(
        rename = "signature",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub signature:           crate::ps_sig::Signature<P>,
}

/// The data we get back from the identity provider in the version 1 flow.
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>, AttributeType: Attribute<C::Scalar> \
                 + SerdeSerialize",
    deserialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>, AttributeType: \
                   Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub struct IdentityObjectV1<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(rename = "preIdentityObject")]
    pub pre_identity_object: PreIdentityObjectV1<P, C>,
    /// Chosen attribute list.
    #[serde(rename = "attributeList")]
    pub alist:               AttributeList<C::Scalar, AttributeType>,
    #[serde(
        rename = "signature",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub signature:           crate::ps_sig::Signature<P>,
}

/// Trait for extracting the relevants parts of an identity object needed for
/// creating a credential
pub trait HasIdentityObjectFields<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    /// Get the common fields of the pre-identity object.
    fn get_common_pio_fields(&self) -> CommonPioFields<P, C>;

    /// Get the attribute list
    fn get_attribute_list(&self) -> &AttributeList<C::Scalar, AttributeType>;

    /// Get the signature
    fn get_signature(&self) -> &crate::ps_sig::Signature<P>;
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: Attribute<C::Scalar>>
    HasIdentityObjectFields<P, C, AttributeType> for IdentityObject<P, C, AttributeType>
{
    fn get_common_pio_fields(&self) -> CommonPioFields<P, C> {
        self.pre_identity_object.get_common_pio_fields()
    }

    fn get_attribute_list(&self) -> &AttributeList<C::Scalar, AttributeType> { &self.alist }

    fn get_signature(&self) -> &crate::ps_sig::Signature<P> { &self.signature }
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: Attribute<C::Scalar>>
    HasIdentityObjectFields<P, C, AttributeType> for IdentityObjectV1<P, C, AttributeType>
{
    fn get_common_pio_fields(&self) -> CommonPioFields<P, C> {
        self.pre_identity_object.get_common_pio_fields()
    }

    fn get_attribute_list(&self) -> &AttributeList<C::Scalar, AttributeType> { &self.alist }

    fn get_signature(&self) -> &crate::ps_sig::Signature<P> { &self.signature }
}

/// Anonymity revokers associated with a single identity provider
#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct IpAnonymityRevokers<C: Curve> {
    #[serde(rename = "anonymityRevokers")]
    pub ars:        Vec<ArInfo<C>>,
    /// List of approved anonymity revokers along with a shared commitment key.
    /// TODO: How is this shared commitment key generated??
    #[serde(rename = "arCommitmentKey")]
    pub ar_cmm_key: PedersenKey<C>,
    /// Chosen generator of the group used by the anonymity revokers.
    /// NB: All public keys of anonymity revokers must be generated with respect
    /// to this generator.
    #[serde(serialize_with = "base16_encode")]
    #[serde(deserialize_with = "base16_decode")]
    #[serde(rename = "arBase")]
    pub ar_base:    C,
}

/// Description either of an anonymity revoker or identity provider.
/// Metadata that should be visible on the chain.
#[derive(PartialEq, Eq, Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
pub struct Description {
    #[string_size_length = 4]
    #[serde(rename = "name")]
    pub name:        String,
    #[string_size_length = 4]
    #[serde(rename = "url")]
    pub url:         String,
    #[string_size_length = 4]
    #[serde(rename = "description")]
    pub description: String,
}

/// Make a dummy description with a given name.
pub fn mk_dummy_description(name: String) -> Description {
    Description {
        name,
        url: "".to_owned(),
        description: "".to_owned(),
    }
}

/// Public information about an identity provider.
#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "P: Pairing", deserialize = "P: Pairing"))]
pub struct IpInfo<P: Pairing> {
    /// Unique identifier of the identity provider.
    #[serde(rename = "ipIdentity")]
    pub ip_identity:       IpIdentity,
    /// Free form description, e.g., how to contact them off-chain
    #[serde(rename = "ipDescription")]
    pub ip_description:    Description,
    /// PS public key of the IP
    #[serde(rename = "ipVerifyKey")]
    pub ip_verify_key:     crate::ps_sig::PublicKey<P>,
    /// Ed public key of the IP
    #[serde(
        rename = "ipCdiVerifyKey",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub ip_cdi_verify_key: ed25519::PublicKey,
}

/// Collection of identity providers.
#[derive(Debug, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "P: Pairing", deserialize = "P: Pairing"))]
#[serde(transparent)]
pub struct IpInfos<P: Pairing> {
    #[serde(rename = "idps")]
    pub identity_providers: BTreeMap<IpIdentity, IpInfo<P>>,
}

/// Public key of an anonymity revoker.
pub type ArPublicKey<C> = crate::elgamal::PublicKey<C>;

/// Information on a single anonymity revoker held by the IP.
/// Typically an IP will hold a more than one.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct ArInfo<C: Curve> {
    /// unique identifier of the anonymity revoker
    #[serde(rename = "arIdentity")]
    pub ar_identity:    ArIdentity,
    /// description of the anonymity revoker (e.g. name, contact number)
    #[serde(rename = "arDescription")]
    pub ar_description: Description,
    /// elgamal encryption key of the anonymity revoker
    #[serde(rename = "arPublicKey")]
    pub ar_public_key:  ArPublicKey<C>,
}

/// Collection of anonymity revokers.
#[derive(Debug, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
#[serde(transparent)]
pub struct ArInfos<C: Curve> {
    pub anonymity_revokers: BTreeMap<ArIdentity, ArInfo<C>>,
}

/// A helper trait to access only the public key of the ArInfo structure.
/// We use this to have functions work both on a map of public keys only, as
/// well as on maps of ArInfos, see [super::chain::verify_cdi].

pub trait HasArPublicKey<C: Curve> {
    fn get_public_key(&self) -> &ArPublicKey<C>;
}

impl<C: Curve> HasArPublicKey<C> for ArInfo<C> {
    fn get_public_key(&self) -> &ArPublicKey<C> { &self.ar_public_key }
}

impl<C: Curve> HasArPublicKey<C> for ArPublicKey<C> {
    fn get_public_key(&self) -> &ArPublicKey<C> { self }
}

/// The commitments sent by the account holder to the chain in order to
/// deploy credentials
#[derive(Debug, PartialEq, Eq, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct CredentialDeploymentCommitments<C: Curve> {
    /// commitment to the prf key
    #[serde(rename = "cmmPrf")]
    pub cmm_prf: PedersenCommitment<C>,
    /// commitment to credential counter
    #[serde(rename = "cmmCredCounter")]
    pub cmm_cred_counter: PedersenCommitment<C>,
    /// commitment to the max account number.
    #[serde(rename = "cmmMaxAccounts")]
    pub cmm_max_accounts: PedersenCommitment<C>,
    /// List of commitments to the attributes that are not revealed.
    /// For the purposes of checking signatures, the commitments to those
    /// that are revealed as part of the policy are going to be computed by the
    /// verifier.
    #[map_size_length = 2]
    #[serde(rename = "cmmAttributes")]
    pub cmm_attributes: BTreeMap<AttributeTag, PedersenCommitment<C>>,
    /// commitments to the coefficients of the polynomial
    /// used to share id_cred_sec
    /// S + b1 X + b2 X^2...
    /// where S is id_cred_sec
    #[serde(rename = "cmmIdCredSecSharingCoeff")]
    pub cmm_id_cred_sec_sharing_coeff: Vec<PedersenCommitment<C>>,
}

#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
/// Randomness that is generated to commit to attributes when creating a
/// credential. This randomness is needed later on if the user wishes to do
/// something with those commitments, for example reveal the commited value, or
/// prove a property of the value.
pub struct CommitmentsRandomness<C: Curve> {
    #[serde(rename = "idCredSecRand")]
    /// Randomness of the commitment to idCredSec.
    pub id_cred_sec_rand:  PedersenRandomness<C>,
    #[serde(rename = "prfRand")]
    /// Randomness of the commitment to the PRF key.
    pub prf_rand:          PedersenRandomness<C>,
    #[serde(rename = "credCounterRand")]
    /// Randomness of the commitment to the credential nonce. This nonce is the
    /// number that is used to ensure that only a limited number of credentials
    /// can be created from a given identity object.
    pub cred_counter_rand: PedersenRandomness<C>,
    #[serde(rename = "maxAccountsRand")]
    /// Randomness of the commitment to the maximum number of accounts the user
    /// may create from the identity object.
    pub max_accounts_rand: PedersenRandomness<C>,
    #[serde(rename = "attributesRand")]
    /// Randomness, if any, used to commit to user-chosen attributes, such as
    /// country of nationality.
    pub attributes_rand:   HashMap<AttributeTag, PedersenRandomness<C>>,
}

#[derive(Debug, SerdeBase16IgnoreLengthSerialize, Clone)]
/// Proofs that the credential is well-formed.
pub struct CredDeploymentProofs<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    /// Proofs that ensure that the credential is derived in a valid way from a
    /// valid identity object.
    pub id_proofs:    IdOwnershipProofs<P, C>,
    /// Proof of knowledge of acc secret keys (signing keys corresponding to the
    /// verification keys either on the account already, or the ones which are
    /// part of this credential.
    pub proof_acc_sk: AccountOwnershipProof,
}

// This is an unfortunate situation, but we need to manually write a
// serialization instance for the proofs, so that we can insert the length of
// the whole proof upfront. This is needed for easier interoperability with
// Haskell. NB: The IdOwnershipProofs structure was introduced at a point
// where the serialization was locked, so we could not change the serialization,
// and because of the order of the serialization, we could not isolate the
// IdOwnershipProofs' serialization without making breaking changes.
impl<P: Pairing, C: Curve<Scalar = P::ScalarField>> Serial for CredDeploymentProofs<P, C> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        let mut tmp_out = Vec::new();
        tmp_out.put(&self.id_proofs.sig);
        tmp_out.put(&self.id_proofs.commitments);
        tmp_out.put(&self.id_proofs.challenge);
        tmp_out.put(&(self.id_proofs.proof_id_cred_pub.len() as u32));
        serial_map_no_length(&self.id_proofs.proof_id_cred_pub, &mut tmp_out);
        tmp_out.put(&self.id_proofs.proof_ip_sig);
        tmp_out.put(&self.id_proofs.proof_reg_id);
        tmp_out.put(&self.proof_acc_sk);
        tmp_out.put(&self.id_proofs.cred_counter_less_than_max_accounts);
        let len: u32 = tmp_out.len() as u32; // safe
        out.put(&len);
        out.write_all(&tmp_out).expect("Writing to buffer is safe.");
    }
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>> Deserial for CredDeploymentProofs<P, C> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let len: u32 = source.get()?;
        // Make sure to respect the length.
        let mut limited = source.take(u64::from(len));
        let sig = limited.get()?;
        let commitments = limited.get()?;
        let challenge = limited.get()?;
        let proof_id_cred_pub_len: u32 = limited.get()?;
        let proof_id_cred_pub =
            deserial_map_no_length(&mut limited, proof_id_cred_pub_len as usize)?;
        let proof_ip_sig = limited.get()?;
        let proof_reg_id = limited.get()?;
        let proof_acc_sk = limited.get()?;
        let cred_counter_less_than_max_accounts = limited.get()?;
        if limited.limit() == 0 {
            Ok(CredDeploymentProofs {
                id_proofs: IdOwnershipProofs {
                    sig,
                    commitments,
                    challenge,
                    proof_id_cred_pub,
                    proof_ip_sig,
                    proof_reg_id,
                    cred_counter_less_than_max_accounts,
                },
                proof_acc_sk,
            })
        } else {
            bail!("Length information is inaccurate. Credential proofs not valid.")
        }
    }
}

/// This structure contains all proofs, which are required to prove ownership of
/// an identity, in a credential deployment.
#[derive(Debug, Serialize, SerdeSerialize, SerdeDeserialize, Clone)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>",
    deserialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>"
))]
pub struct IdOwnershipProofs<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    /// (Blinded) Signature derived from the signature on the pre-identity
    /// object by the IP
    #[serde(
        rename = "sig",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub sig: crate::ps_sig::BlindedSignature<P>,
    /// list of  commitments to the attributes .
    #[serde(
        rename = "commitments",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub commitments: CredentialDeploymentCommitments<C>,
    /// Challenge used for all of the proofs.
    #[serde(
        rename = "challenge",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub challenge: Challenge,
    /// Responses in the proof that the computed commitment to the share
    /// contains the same value as the encryption
    /// the commitment to the share is not sent but computed from
    /// the commitments to the sharing coefficients
    #[serde(rename = "proofIdCredPub")]
    #[map_size_length = 4]
    pub proof_id_cred_pub: BTreeMap<ArIdentity, com_enc_eq::Response<C>>,
    /// Responses in the proof of knowledge of signature of Identity Provider on
    /// the list
    /// ```(idCredSec, prfKey, attributes[0], attributes[1],..., attributes[n],
    /// AR[1], ..., AR[m])```
    #[serde(
        rename = "proofIpSig",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub proof_ip_sig: com_eq_sig::Response<P, C>,
    /// Proof that reg_id = prf_K(x). Also establishes that reg_id is computed
    /// from the prf key signed by the identity provider.
    #[serde(
        rename = "proofRegId",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub proof_reg_id: com_mult::Response<C>,
    /// Proof that cred_counter is less than or equal to max_accounts
    #[serde(
        rename = "credCounterLessThanMaxAccounts",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub cred_counter_less_than_max_accounts: RangeProof<C>,
}

#[derive(Debug, PartialEq, Eq, Clone, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
/// A policy is (currently) revealed values of attributes that are part of the
/// identity object. Policies are part of credentials.
pub struct Policy<C: Curve, AttributeType: Attribute<C::Scalar>> {
    #[serde(rename = "validTo")]
    pub valid_to:   YearMonth,
    #[serde(rename = "createdAt")]
    pub created_at: YearMonth,
    /// Revealed attributes for now. In the future we might have
    /// additional items with (Tag, Property, Proof).
    #[serde(rename = "revealedAttributes")]
    pub policy_vec: BTreeMap<AttributeTag, AttributeType>,
    #[serde(skip)]
    pub _phantom:   std::marker::PhantomData<C>,
}

impl<C: Curve, AttributeType: Attribute<C::Scalar>> Serial for Policy<C, AttributeType> {
    fn serial<B: Buffer>(&self, out: &mut B) {
        out.put(&self.valid_to);
        out.put(&self.created_at);
        out.put(&(self.policy_vec.len() as u16));
        serial_map_no_length(&self.policy_vec, out)
    }
}

impl<C: Curve, AttributeType: Attribute<C::Scalar>> Deserial for Policy<C, AttributeType> {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let valid_to = source.get()?;
        let created_at = source.get()?;
        let len: u16 = source.get()?;
        let policy_vec = deserial_map_no_length(source, usize::from(len))?;
        Ok(Policy {
            valid_to,
            created_at,
            policy_vec,
            _phantom: Default::default(),
        })
    }
}

#[derive(Debug, PartialEq, Eq, concordium_std::Serialize)]
/// Which signature scheme is being used. Currently only one is supported.
pub enum SchemeId {
    Ed25519,
}

#[derive(Debug, Eq, Clone)]
/// Public AKA verification key for a given scheme. Only ed25519 is currently
/// supported.
pub enum VerifyKey {
    Ed25519VerifyKey(ed25519::PublicKey),
}

impl concordium_std::Serial for VerifyKey {
    fn serial<W: concordium_std::Write>(&self, out: &mut W) -> Result<(), W::Err> {
        match self {
            VerifyKey::Ed25519VerifyKey(key) => {
                concordium_std::Serial::serial(&0u8, out)?;
                concordium_std::Serial::serial(&key.as_bytes(), out)
            }
        }
    }
}

impl concordium_std::Deserial for VerifyKey {
    fn deserial<R: concordium_std::Read>(source: &mut R) -> concordium_std::ParseResult<Self> {
        let tag: u8 = concordium_std::Deserial::deserial(source)?;
        if tag == 0 {
            let bytes: [u8; ed25519::PUBLIC_KEY_LENGTH] =
                concordium_std::Deserial::deserial(source)?;
            let pk = ed25519::PublicKey::from_bytes(&bytes)
                .map_err(|_| concordium_std::ParseError {})?;
            Ok(Self::Ed25519VerifyKey(pk))
        } else {
            Err(concordium_std::ParseError {})
        }
    }
}

impl SerdeSerialize for VerifyKey {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        let mut map = ser.serialize_map(Some(2))?;
        match self {
            VerifyKey::Ed25519VerifyKey(ref key) => {
                map.serialize_entry("schemeId", "Ed25519")?;
                map.serialize_entry("verifyKey", &encode(to_bytes(key)))?;
            }
        }
        map.end()
    }
}

impl<'de> SerdeDeserialize<'de> for VerifyKey {
    fn deserialize<D: Deserializer<'de>>(des: D) -> Result<Self, D::Error> {
        struct VerifyKeyVisitor;

        impl<'de> Visitor<'de> for VerifyKeyVisitor {
            type Value = VerifyKey;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "Either a string or a map with verification key.")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
                let bytes = decode(v).map_err(de::Error::custom)?;
                let key = from_bytes(&mut Cursor::new(&bytes)).map_err(de::Error::custom)?;
                Ok(VerifyKey::Ed25519VerifyKey(key))
            }

            fn visit_map<A: de::MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
                let mut map = map;
                let mut tmp_map: BTreeMap<String, String> = BTreeMap::new();
                while tmp_map.len() < 2 {
                    if let Some((k, v)) = map.next_entry()? {
                        if k == "schemeId" {
                            if v != "Ed25519" {
                                return Err(de::Error::custom(format!(
                                    "Unknown signature scheme type {}",
                                    v
                                )));
                            }
                            if tmp_map.insert(k, v).is_some() {
                                return Err(de::Error::custom("Duplicate schemeId."));
                            }
                        } else if k == "verifyKey" {
                            tmp_map.insert(k, v);
                        }
                    } else {
                        return Err(de::Error::custom(
                            "At least the two keys 'schemeId' and 'verifyKey' are expected.",
                        ));
                    }
                }
                let vf_key_str = tmp_map.get("verifyKey").ok_or_else(|| {
                    de::Error::custom("Could not find verifyKey, should not happen.")
                })?;
                let bytes = decode(vf_key_str).map_err(de::Error::custom)?;
                let key = from_bytes(&mut Cursor::new(&bytes)).map_err(de::Error::custom)?;
                Ok(VerifyKey::Ed25519VerifyKey(key))
            }
        }
        des.deserialize_any(VerifyKeyVisitor)
    }
}

impl From<ed25519::PublicKey> for VerifyKey {
    fn from(pk: ed25519::PublicKey) -> Self { VerifyKey::Ed25519VerifyKey(pk) }
}

impl From<&ed25519::Keypair> for VerifyKey {
    fn from(kp: &ed25519::Keypair) -> Self { VerifyKey::Ed25519VerifyKey(kp.public) }
}

impl From<&KeyPair> for VerifyKey {
    fn from(kp: &KeyPair) -> Self { VerifyKey::Ed25519VerifyKey(kp.public) }
}

/// Compare byte representation.
impl Ord for VerifyKey {
    fn cmp(&self, other: &VerifyKey) -> Ordering {
        let VerifyKey::Ed25519VerifyKey(ref self_key) = self;
        let VerifyKey::Ed25519VerifyKey(ref other_key) = other;
        self_key.as_ref().cmp(other_key.as_ref())
    }
}

impl PartialOrd for VerifyKey {
    fn partial_cmp(&self, other: &VerifyKey) -> Option<Ordering> { Some(self.cmp(other)) }
}

impl PartialEq for VerifyKey {
    fn eq(&self, other: &VerifyKey) -> bool { self.cmp(other) == Ordering::Equal }
}

impl Serial for VerifyKey {
    fn serial<B: Buffer>(&self, out: &mut B) {
        use VerifyKey::*;
        match self {
            Ed25519VerifyKey(ref key) => {
                out.put(&SchemeId::Ed25519);
                out.put(key);
            }
        }
    }
}

impl Deserial for VerifyKey {
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        use VerifyKey::*;
        match source.get()? {
            SchemeId::Ed25519 => {
                let key = source.get()?;
                Ok(Ed25519VerifyKey(key))
            }
        }
    }
}

impl VerifyKey {
    /// Verify a signature on the given message.
    /// This checks
    /// - the proposed signature can be parsed as a valid signature
    /// - the signature validates with respect to the public key.
    pub fn verify(&self, msg: impl AsRef<[u8]>, sig: &crate::common::types::Signature) -> bool {
        match self {
            VerifyKey::Ed25519VerifyKey(pk) => {
                let sig: ed25519_dalek::Signature = {
                    if let Ok(x) = sig.as_ref().try_into() {
                        x
                    } else {
                        return false;
                    }
                };
                pk.verify(msg.as_ref(), &sig).is_ok()
            }
        }
    }
}

/// Values (as opposed to proofs) in credential deployment.
#[derive(Debug, PartialEq, Eq, Serialize, SerdeSerialize, SerdeDeserialize, Clone)]
#[serde(bound(
    serialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub struct CredentialDeploymentValues<C: Curve, AttributeType: Attribute<C::Scalar>> {
    /// Credential keys (i.e. account holder keys).
    #[serde(rename = "credentialPublicKeys")]
    pub cred_key_info: CredentialPublicKeys,
    /// Credential registration id of the credential.
    #[serde(
        rename = "credId",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub cred_id:       CredId<C>,
    /// Identity of the identity provider who signed the identity object from
    /// which this credential is derived.
    #[serde(rename = "ipIdentity")]
    pub ip_identity:   IpIdentity,
    /// Anonymity revocation threshold. Must be <= length of ar_data.
    #[serde(rename = "revocationThreshold")]
    pub threshold:     Threshold,
    /// Anonymity revocation data. List of anonymity revokers which can revoke
    /// identity. NB: The order is important since it is the same order as that
    /// signed by the identity provider, and permuting the list will invalidate
    /// the signature from the identity provider.
    #[map_size_length = 2]
    #[serde(rename = "arData", deserialize_with = "deserialize_ar_data")]
    pub ar_data:       BTreeMap<ArIdentity, ChainArData<C>>,
    /// Policy of this credential object.
    #[serde(rename = "policy")]
    pub policy:        Policy<C, AttributeType>,
}

/// Values in initial credential deployment.
#[derive(Debug, PartialEq, Eq, Serialize, SerdeSerialize, SerdeDeserialize, Clone)]
#[serde(bound(
    serialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub struct InitialCredentialDeploymentValues<C: Curve, AttributeType: Attribute<C::Scalar>> {
    /// Account this credential belongs to.
    #[serde(rename = "credentialPublicKeys")]
    pub cred_account: CredentialPublicKeys,
    /// Credential registration id of the credential.
    #[serde(
        rename = "regId",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub reg_id:       CredId<C>,
    /// Identity of the identity provider who signed the identity object from
    /// which this credential is derived.
    #[serde(rename = "ipIdentity")]
    pub ip_identity:  IpIdentity,
    /// Policy of this credential object.
    #[serde(rename = "policy")]
    pub policy:       Policy<C, AttributeType>,
}

fn deserialize_ar_data<'de, D: de::Deserializer<'de>, C: Curve>(
    des: D,
) -> Result<BTreeMap<ArIdentity, ChainArData<C>>, D::Error> {
    #[derive(Default)]
    struct ArIdentityVisitor<C>(std::marker::PhantomData<C>);

    impl<'de, C: Curve> Visitor<'de> for ArIdentityVisitor<C> {
        type Value = BTreeMap<ArIdentity, ChainArData<C>>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            write!(
                formatter,
                "An object with integer keys and ChainArData values."
            )
        }

        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
        where
            A: de::MapAccess<'de>, {
            let mut map = map;
            let mut res = BTreeMap::new();
            while let Some((k, v)) = map.next_entry::<String, _>()? {
                let k = ArIdentity::from_str(&k)
                    .map_err(|_| de::Error::custom("Cannot read ArIdentity key."))?;
                res.insert(k, v);
            }
            Ok(res)
        }
    }

    des.deserialize_map(ArIdentityVisitor(std::default::Default::default()))
}

#[derive(Debug, Serialize, SerdeSerialize, SerdeDeserialize, Clone)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                 Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                   Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
/// A credential with attributes, public keys, and proofs that it is
/// well-formed.
pub struct CredentialDeploymentInfo<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(flatten)]
    pub values: CredentialDeploymentValues<C, AttributeType>,
    #[serde(rename = "proofs")] // FIXME: This should remove the first 4 bytes
    pub proofs: CredDeploymentProofs<P, C>,
}

#[derive(SerdeSerialize, SerdeDeserialize, Debug, Clone, Copy)]
#[serde(rename_all = "camelCase")]
// Since all variants are fieldless, the default JSON serialization will convert
// all the variants to simple strings.
/// Enumeration of the types of credentials.
pub enum CredentialType {
    /// Initial credential is a credential that is submitted by the identity
    /// provider on behalf of the user. There is only one initial credential
    /// per identity.
    Initial,
    /// A normal credential is one where the identity behind it is only known to
    /// the owner of the account, unless the anonymity revocation process was
    /// followed.
    Normal,
}

/// Account credential with values and commitments, but without proofs.
/// Serialization must match the serializaiton of `AccountCredential` in
/// Haskell.
#[derive(SerdeSerialize, SerdeDeserialize, Debug, PartialEq, Eq)]
#[serde(tag = "type", content = "contents")]
#[serde(bound(
    serialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub enum AccountCredentialWithoutProofs<C: Curve, AttributeType: Attribute<C::Scalar>> {
    #[serde(rename = "initial")]
    Initial {
        #[serde(flatten)]
        icdv: InitialCredentialDeploymentValues<C, AttributeType>,
    },
    #[serde(rename = "normal")]
    Normal {
        #[serde(flatten)]
        cdv:         CredentialDeploymentValues<C, AttributeType>,
        #[serde(rename = "commitments")]
        commitments: CredentialDeploymentCommitments<C>,
    },
}

impl<C: Curve, AttributeType: Attribute<C::Scalar>>
    AccountCredentialWithoutProofs<C, AttributeType>
{
    /// Retrieve the policy of the credential.
    pub fn policy(&self) -> &Policy<C, AttributeType> {
        match self {
            AccountCredentialWithoutProofs::Initial { icdv } => &icdv.policy,
            AccountCredentialWithoutProofs::Normal { cdv, .. } => &cdv.policy,
        }
    }

    /// Retrieve the issuer of the credential. The [`IpIdentity`] is a reference
    /// to the identity provider on the chain of which the credential is a part
    /// of.
    pub fn issuer(&self) -> IpIdentity {
        match self {
            AccountCredentialWithoutProofs::Initial { icdv } => icdv.ip_identity,
            AccountCredentialWithoutProofs::Normal { cdv, .. } => cdv.ip_identity,
        }
    }
}

impl<C: Curve, AttributeType: Serial + Attribute<C::Scalar>> Serial
    for AccountCredentialWithoutProofs<C, AttributeType>
{
    fn serial<B: Buffer>(&self, out: &mut B) {
        match self {
            AccountCredentialWithoutProofs::Initial { icdv } => {
                0u8.serial(out);
                icdv.serial(out);
            }
            AccountCredentialWithoutProofs::Normal { cdv, commitments } => {
                1u8.serial(out);
                cdv.serial(out);
                commitments.serial(out);
            }
        }
    }
}

impl<C: Curve, AttributeType: Deserial + Attribute<C::Scalar>> Deserial
    for AccountCredentialWithoutProofs<C, AttributeType>
{
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        let tag = u8::deserial(source)?;
        match tag {
            0u8 => {
                let icdv = source.get()?;
                Ok(Self::Initial { icdv })
            }
            1u8 => {
                let cdv = source.get()?;
                let commitments = source.get()?;
                Ok(Self::Normal { cdv, commitments })
            }
            _ => bail!("Unsupported credential tag: {}", tag),
        }
    }
}

/// Type of credential registration IDs.
pub type CredId<C> = C;

impl<C: Curve, AttributeType: Attribute<C::Scalar>>
    AccountCredentialWithoutProofs<C, AttributeType>
{
    /// Return the credential registration ID of the account credential.
    pub fn cred_id(&self) -> &CredId<C> {
        match self {
            AccountCredentialWithoutProofs::Initial { icdv } => &icdv.reg_id,
            AccountCredentialWithoutProofs::Normal { cdv, .. } => &cdv.cred_id,
        }
    }
}

/// This is the CredentialDeploymentInfo structure, that instead of containing
/// CredDeploymentProofs, it contains UnsignedCredDeploymentProofs, and
/// the reg_id that also has to be signed.
#[derive(Debug, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                 Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                   Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub struct UnsignedCredentialDeploymentInfo<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(flatten)]
    pub values: CredentialDeploymentValues<C, AttributeType>,
    pub proofs: IdOwnershipProofs<P, C>,
}

#[derive(Debug, Serialize, SerdeSerialize, SerdeDeserialize, Clone)]
#[serde(bound(
    serialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
/// Information needed to create an `initial` account. This account is created
/// on behalf of the user by the identity provider.
pub struct InitialCredentialDeploymentInfo<
    // P: Pairing,
    C: Curve, //<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(flatten)]
    pub values: InitialCredentialDeploymentValues<C, AttributeType>,
    #[serde(rename = "sig")]
    pub sig:    IpCdiSignature,
}

/// This struct contains information from the account holder that the identity
/// provider needs in order to create the initial credential for the account
/// holder. It contains idCredPub, regId and the account keys.
/// It is part of the preidentity object.
#[derive(Debug, Serialize, Clone, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct PublicInformationForIp<C: Curve> {
    #[serde(
        rename = "idCredPub",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub id_cred_pub: C,
    #[serde(
        rename = "regId",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub reg_id:      C,
    #[serde(rename = "publicKeys")]
    pub vk_acc:      CredentialPublicKeys,
}

/// Context needed to generate pre-identity object as well as to check it.
/// This context is derived from the public information of the identity
/// provider, as well as some other global parameters which can be found in the
/// struct 'GlobalContext'.
#[derive(Clone)]
pub struct IpContext<'a, P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    /// Public information on the chosen identity provider.
    pub ip_info:        &'a IpInfo<P>,
    /// Public information on the __supported__ anonymity revokers.
    /// This is used by the identity provider and the chain to
    /// validate the identity object requests, to validate credentials,
    /// as well as by the account holder to create a credential.
    pub ars_infos:      &'a BTreeMap<ArIdentity, ArInfo<C>>,
    pub global_context: &'a GlobalContext<C>,
}

impl<'a, P: Pairing, C: Curve<Scalar = P::ScalarField>> Copy for IpContext<'a, P, C> {}

#[derive(Debug, Clone, Serialize, SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
/// A set of cryptographic parameters that are particular to the chain and
/// shared by everybody that interacts with the chain.
pub struct GlobalContext<C: Curve> {
    /// A shared commitment key known to the chain and the account holder (and
    /// therefore it is public). The account holder uses this commitment key to
    /// generate commitments to values in the attribute list.
    #[serde(rename = "onChainCommitmentKey")]
    pub on_chain_commitment_key: PedersenKey<C>,
    /// Generators for the bulletproofs.
    /// It is unclear what length we will require here, or whether we'll allow
    /// dynamic generation.
    #[serde(rename = "bulletproofGenerators")]
    pub bulletproof_generators:  Generators<C>,
    #[string_size_length = 4]
    #[serde(rename = "genesisString")]
    /// A free-form string used to distinguish between different chains even if
    /// they share other parameters.
    pub genesis_string:          String,
}

impl<C: Curve> GlobalContext<C> {
    /// Generate a new global context.
    pub fn generate(genesis_string: String) -> Self {
        Self::generate_size(genesis_string, NUM_BULLETPROOF_GENERATORS)
    }

    /// Generate a new global context with the given number of
    /// bulletproof generators, and a given seed string for generating group
    /// generators.
    ///
    /// This is intended mostly for testing, on-chain there will be a fixed
    /// amount, and a fixed seed.
    pub fn generate_from_seed(genesis_string: String, n: usize, seed: &[u8]) -> Self {
        // initialize the first generator from pi digits.
        let g = C::hash_to_group(seed);

        // generate next generator by hashing the previous one
        let h = C::hash_to_group(&to_bytes(&g));

        let cmm_key = PedersenKey { g, h };

        let mut generators = Vec::with_capacity(n);
        let mut generator = h;
        for _ in 0..n {
            generator = C::hash_to_group(&to_bytes(&generator));
            let g = generator;
            generator = C::hash_to_group(&to_bytes(&generator));
            let h = generator;
            generators.push((g, h));
        }

        GlobalContext {
            on_chain_commitment_key: cmm_key,
            bulletproof_generators: Generators { G_H: generators },
            genesis_string,
        }
    }

    /// Generate a new global context with the given number of
    /// bulletproof generators.
    ///
    /// This is intended mostly for testing, on-chain there will be a fixed
    /// amount.
    pub fn generate_size(genesis_string: String, n: usize) -> Self {
        // initialize the first generator from pi digits.
        Self::generate_from_seed(genesis_string, n, &PI_DIGITS[0..1000])
    }

    /// The generator for encryption in the exponent is the second component of
    /// the commitment key, the 'h'.
    pub fn encryption_in_exponent_generator(&self) -> &C { &self.on_chain_commitment_key.h }

    /// The generator used as the base for elgamal public keys.
    pub fn elgamal_generator(&self) -> &C { &self.on_chain_commitment_key.g }

    /// Get the commitment key for the vector Pedersen commitment.
    /// The return value is a triple of the base for randomness, the number of
    /// group elements, and the iterator over them.
    ///
    /// The group elements are all distinct from `g` that is part of the
    /// [`on_chain_commitment_key`](Self::on_chain_commitment_key).
    ///
    /// The base for randomness is the same as that in
    /// [`on_chain_commitment_key`](Self::on_chain_commitment_key).
    pub fn vector_commitment_base(&self) -> (&C, usize, impl Iterator<Item = &C>) {
        let base_size = self.bulletproof_generators.G_H.len();
        let iter = self.bulletproof_generators.G_H.iter().map(|x| &x.0);
        (&self.on_chain_commitment_key.h, base_size, iter)
    }

    /// A wrapper function to support changes in internal structure of the
    /// context in the future, e.g., lazy generation of generators.
    pub fn bulletproof_generators(&self) -> &Generators<C> { &self.bulletproof_generators }
}

/// Make a context in which the account holder can produce a pre-identity object
/// to send to the identity provider. Also requires access to the global context
/// of parameters, e.g., dlog-proof base point.
impl<'a, P: Pairing, C: Curve<Scalar = P::ScalarField>> IpContext<'a, P, C> {
    pub fn new(
        ip_info: &'a IpInfo<P>,                         // identity provider keys
        ars_infos: &'a BTreeMap<ArIdentity, ArInfo<C>>, // keys of anonymity revokers.
        global_context: &'a GlobalContext<C>,
    ) -> Self {
        IpContext {
            ip_info,
            ars_infos,
            global_context,
        }
    }
}

/// A helper trait to access the public parts of the InitialAccountData
/// structure. We use this to allow implementations that do not give or have
/// access to the secret keys.
/// NB: the threshold should be at most the number of keypairs.
pub trait PublicInitialAccountData {
    /// Get the public keys of the credential
    fn get_public_keys(&self) -> BTreeMap<KeyIndex, VerifyKey>;
    /// Get the signature threshold of the account.
    fn get_threshold(&self) -> SignatureThreshold;

    /// Get the CredentialPublicKeys struct directly
    fn get_cred_key_info(&self) -> CredentialPublicKeys {
        CredentialPublicKeys {
            keys:      self.get_public_keys(),
            threshold: self.get_threshold(),
        }
    }
}

/// A helper trait to allow signing PublicInformationForIP in an implementation
/// that does not give access to the secret keys.
pub trait InitialAccountDataWithSigning: PublicInitialAccountData {
    /// Sign a PublicInformationForIP structure with the secret keys that
    /// matches the public keys, which the structure provides.
    /// NB: the function should, for each secret key,
    /// sign the sha256 hash of the structure's serialization.
    fn sign_public_information_for_ip<C: Curve>(
        &self,
        info: &PublicInformationForIp<C>,
    ) -> BTreeMap<KeyIndex, AccountOwnershipSignature>;
}

/// A helper trait to access the public parts of the CredentialData
/// structure. We use this to allow implementations that does not give or have
/// access to the secret keys.
/// NB: the threshold should be at most the number of keypairs.
pub trait PublicCredentialData {
    /// Get the public keys of the credential
    fn get_public_keys(&self) -> BTreeMap<KeyIndex, VerifyKey>;
    /// Get the signature threshold of the account.
    fn get_threshold(&self) -> SignatureThreshold;

    /// Get the CredentialPublicKeys struct directly
    fn get_cred_key_info(&self) -> CredentialPublicKeys {
        CredentialPublicKeys {
            keys:      self.get_public_keys(),
            threshold: self.get_threshold(),
        }
    }
}

/// A helper trait to allow signing PublicInformationForIP in an implementation
/// that does not give access to the secret keys.
pub trait CredentialDataWithSigning: PublicCredentialData {
    /// Sign the credential deployment information, proving ownership of account
    /// keys.
    /// If the first argument is Right(addr) then this credential is intended
    /// for an existing account. If the first argument is Left(tt) then the
    /// credential is going to create a new account, and the payload is the
    /// expiry time of the transaction.
    fn sign<P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: Attribute<C::Scalar>>(
        &self,
        message_expiry: &Either<types::TransactionTime, AccountAddress>,
        unsigned_cred_info: &UnsignedCredentialDeploymentInfo<P, C, AttributeType>,
    ) -> BTreeMap<KeyIndex, AccountOwnershipSignature>;
}

/// All account keys indexed by credentials.
#[derive(Debug, SerdeSerialize, SerdeDeserialize)]
pub struct AccountKeys {
    /// All keys per credential
    #[serde(rename = "keys")]
    pub keys:      BTreeMap<CredentialIndex, CredentialData>,
    /// The account threshold.
    #[serde(rename = "threshold")]
    pub threshold: AccountThreshold,
}

/// Create account keys with a single credential at index 0
impl From<CredentialData> for AccountKeys {
    fn from(cd: CredentialData) -> Self { Self::from((CredentialIndex { index: 0 }, cd)) }
}

/// Create account keys with a single credential at the given index
impl From<(CredentialIndex, CredentialData)> for AccountKeys {
    fn from((ki, cd): (CredentialIndex, CredentialData)) -> Self {
        let mut keys = BTreeMap::new();
        keys.insert(ki, cd);
        Self {
            keys,
            threshold: AccountThreshold::ONE,
        }
    }
}

/// Create account keys with a single credential at index 0
impl From<InitialAccountData> for AccountKeys {
    fn from(cd: InitialAccountData) -> Self {
        let mut keys = BTreeMap::new();
        keys.insert(CredentialIndex { index: 0 }, CredentialData {
            keys:      cd.keys,
            threshold: cd.threshold,
        });
        Self {
            keys,
            threshold: AccountThreshold::ONE,
        }
    }
}

impl AccountKeys {
    /// Sign the provided data with all of the keys in [`AccountKeys`].
    /// The thresholds are ignored.
    pub fn sign_data(
        &self,
        msg: &[u8],
    ) -> BTreeMap<CredentialIndex, BTreeMap<KeyIndex, Signature>> {
        let mut signatures = BTreeMap::<CredentialIndex, BTreeMap<KeyIndex, _>>::new();
        for (ci, cred_keys) in self.keys.iter() {
            let cred_sigs = cred_keys
                .keys
                .iter()
                .map(|(ki, kp)| (*ki, kp.sign(msg)))
                .collect::<BTreeMap<_, _>>();
            signatures.insert(*ci, cred_sigs);
        }
        signatures
    }
}

impl AccountKeys {
    /// Generate new [`AccountKeys`] for the thresholds and key indices
    /// specified in the input. If there are duplicate indices then later
    /// ones override the previous ones.
    ///
    /// The keys sampled from the supplied random number generator in the order
    /// of key indices supplied, using [`KeyPair::generate`](KeyPair::generate).
    pub fn generate<R: rand::CryptoRng + rand::Rng>(
        account_threshold: AccountThreshold,
        indices: &[(CredentialIndex, SignatureThreshold, &[KeyIndex])],
        csprng: &mut R,
    ) -> Self {
        let keys = indices.iter().map(|(ci, threshold, kis)| {
            (*ci, CredentialData {
                keys:      kis
                    .iter()
                    .map(|ki| (*ki, KeyPair::generate(csprng)))
                    .collect(),
                threshold: *threshold,
            })
        });
        Self {
            keys:      keys.collect(),
            threshold: account_threshold,
        }
    }

    /// Generate account keys with a single credential and key, at credential
    /// and key indices 0.
    pub fn singleton<R: rand::CryptoRng + rand::Rng>(csprng: &mut R) -> Self {
        Self::generate(
            AccountThreshold::ONE,
            &[(0.into(), SignatureThreshold::ONE, &[0.into()])],
            csprng,
        )
    }
}

/// Credential data needed by the account holder to generate proofs to deploy
/// the credential object. This contains all the keys on the credential at the
/// moment of its deployment. If this creates the account then the account
/// starts with exactly these keys.
#[derive(Debug, SerdeSerialize, SerdeDeserialize)]
pub struct CredentialData {
    #[serde(rename = "keys")]
    pub keys:      BTreeMap<KeyIndex, crate::common::types::KeyPair>,
    #[serde(rename = "threshold")]
    pub threshold: SignatureThreshold,
}

impl PublicCredentialData for CredentialData {
    fn get_threshold(&self) -> SignatureThreshold { self.threshold }

    fn get_public_keys(&self) -> BTreeMap<KeyIndex, VerifyKey> {
        self.keys
            .iter()
            .map(|(&idx, kp)| (idx, VerifyKey::Ed25519VerifyKey(kp.public)))
            .collect()
    }
}

impl CredentialDataWithSigning for CredentialData {
    fn sign<P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: Attribute<C::Scalar>>(
        &self,
        new_or_existing: &Either<types::TransactionTime, AccountAddress>,
        unsigned_cred_info: &UnsignedCredentialDeploymentInfo<P, C, AttributeType>,
    ) -> BTreeMap<KeyIndex, AccountOwnershipSignature> {
        let to_sign = super::utils::credential_hash_to_sign(
            &unsigned_cred_info.values,
            &unsigned_cred_info.proofs,
            new_or_existing,
        );
        self.keys
            .iter()
            .map(|(&idx, kp)| {
                let expanded_sk = ed25519::ExpandedSecretKey::from(&kp.secret);
                (idx, expanded_sk.sign(&to_sign, &kp.public).into())
            })
            .collect()
    }
}
/// This contains all the keys on the account of the initial credential
/// deployment.
#[derive(SerdeSerialize, SerdeDeserialize)]
pub struct InitialAccountData {
    #[serde(rename = "keys")]
    pub keys:      BTreeMap<KeyIndex, crate::common::types::KeyPair>,
    #[serde(rename = "threshold")]
    pub threshold: SignatureThreshold,
}

impl PublicInitialAccountData for InitialAccountData {
    fn get_threshold(&self) -> SignatureThreshold { self.threshold }

    fn get_public_keys(&self) -> BTreeMap<KeyIndex, VerifyKey> {
        self.keys
            .iter()
            .map(|(&idx, kp)| (idx, VerifyKey::Ed25519VerifyKey(kp.public)))
            .collect()
    }
}

impl InitialAccountDataWithSigning for InitialAccountData {
    fn sign_public_information_for_ip<C: Curve>(
        &self,
        pub_info_for_ip: &PublicInformationForIp<C>,
    ) -> BTreeMap<KeyIndex, AccountOwnershipSignature> {
        let to_sign = Sha256::digest(to_bytes(pub_info_for_ip));
        self.keys
            .iter()
            .map(|(&idx, kp)| {
                let expanded_sk = ed25519::ExpandedSecretKey::from(&kp.secret);
                (idx, expanded_sk.sign(&to_sign, &kp.public).into())
            })
            .collect()
    }
}

/// Public credential keys currently on the account, together with the threshold
/// needed for a valid signature on a transaction.
#[derive(
    Debug, PartialEq, Eq, SerdeSerialize, SerdeDeserialize, Clone, concordium_std::Serialize,
)]
pub struct CredentialPublicKeys {
    #[serde(rename = "keys")]
    #[concordium(size_length = 1)]
    pub keys:      BTreeMap<KeyIndex, VerifyKey>,
    #[serde(rename = "threshold")]
    pub threshold: SignatureThreshold,
}

impl Serial for CredentialPublicKeys {
    fn serial<B: Buffer>(&self, out: &mut B) {
        let len = self.keys.len() as u8;
        out.put(&len);
        serial_map_no_length(&self.keys, out);
        out.put(&self.threshold);
    }
}

impl Deserial for CredentialPublicKeys {
    fn deserial<R: ReadBytesExt>(cur: &mut R) -> ParseResult<Self> {
        let len = cur.read_u8()?;
        if len == 0 {
            bail!(anyhow!("At least one key must be present."));
        }
        let keys = deserial_map_no_length(cur, usize::from(len))?;
        let threshold = cur.get()?;
        Ok(CredentialPublicKeys { keys, threshold })
    }
}

impl CredentialPublicKeys {
    pub fn get(&self, idx: KeyIndex) -> Option<&VerifyKey> { self.keys.get(&idx) }
}

/// Serialization of relevant types.
impl Serial for SchemeId {
    fn serial<B: Buffer>(&self, out: &mut B) {
        match self {
            SchemeId::Ed25519 => out.write_u8(0).expect("Writing to buffer is safe."),
        }
    }
}

impl Deserial for SchemeId {
    fn deserial<R: ReadBytesExt>(cur: &mut R) -> ParseResult<Self> {
        match cur.read_u8()? {
            0 => Ok(SchemeId::Ed25519),
            _ => bail!("Only Ed25519 signature scheme supported."),
        }
    }
}

/// Metadata that we need off-chain for various purposes, but should not go on
/// the chain.
#[derive(SerdeSerialize, SerdeDeserialize, Serialize, Default)]
pub struct IpMetadata {
    #[string_size_length = 4]
    #[serde(rename = "issuanceStart")]
    pub issuance_start: String,
    #[string_size_length = 4]
    #[serde(rename = "icon")]
    pub icon:           String,
}

/// Private and public data on an identity provider.
/// This is used purely off-chain.
#[derive(SerdeSerialize, SerdeDeserialize, Serialize)]
#[serde(bound(serialize = "P: Pairing", deserialize = "P: Pairing"))]
pub struct IpData<P: Pairing> {
    #[serde(rename = "ipInfo")]
    pub public_ip_info:    IpInfo<P>,
    #[serde(
        rename = "ipSecretKey",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub ip_secret_key:     crate::ps_sig::SecretKey<P>,
    #[serde(
        rename = "ipCdiSecretKey",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub ip_cdi_secret_key: ed25519::SecretKey,
}

/// Private and public data on an anonymity revoker.
/// This is used purely off-chain.
#[derive(SerdeSerialize, SerdeDeserialize, Serialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct ArData<C: Curve> {
    #[serde(rename = "arInfo")]
    pub public_ar_info: ArInfo<C>,
    #[serde(
        rename = "arSecretKey",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub ar_secret_key:  ElgamalSecretKey<C>,
}

/// Data needed to use the retrieved identity object to generate credentials.
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>",
    deserialize = "P: Pairing, C: Curve<Scalar=P::ScalarField>"
))]
pub struct IdObjectUseData<P: Pairing, C: Curve<Scalar = P::ScalarField>> {
    #[serde(rename = "aci")]
    pub aci:        AccCredentialInfo<C>,
    /// Randomness needed to retrieve the signature on the attribute list.
    #[serde(
        rename = "randomness",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub randomness: crate::ps_sig::SigRetrievalRandomness<P>,
}

/// Data that needs to be stored by the identity provider to support anonymity
/// revocation.
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct AnonymityRevocationRecord<C: Curve> {
    /// The number that identifies the identity object to the identity provider.
    #[serde(
        rename = "idCredPub",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub id_cred_pub:  C,
    /// Data that contains encryptions of the prf key that supports additional
    /// anonymity revocation.
    #[serde(rename = "arData")]
    pub ar_data:      BTreeMap<ArIdentity, IpArData<C>>,
    #[serde(rename = "maxAccounts")]
    pub max_accounts: u8,
    #[serde(rename = "revocationThreshold")]
    pub threshold:    Threshold,
}

/// A type encapsulating both types of credentials.
/// Serialization must match the one in Haskell.
#[derive(SerdeSerialize, SerdeDeserialize, Debug, Clone)]
#[serde(tag = "type", content = "contents")]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                 Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                   Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub enum AccountCredential<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(rename = "initial")]
    Initial {
        #[serde(flatten)]
        icdi: InitialCredentialDeploymentInfo<C, AttributeType>,
    },
    #[serde(rename = "normal")]
    Normal {
        #[serde(flatten)]
        cdi: CredentialDeploymentInfo<P, C, AttributeType>,
    },
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: Attribute<C::Scalar>> Serial
    for AccountCredential<P, C, AttributeType>
{
    fn serial<B: Buffer>(&self, out: &mut B) {
        match self {
            AccountCredential::Initial { icdi } => {
                0u8.serial(out);
                icdi.serial(out)
            }
            AccountCredential::Normal { cdi } => {
                1u8.serial(out);
                cdi.serial(out)
            }
        }
    }
}

impl<P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: Attribute<C::Scalar>> Deserial
    for AccountCredential<P, C, AttributeType>
{
    fn deserial<R: ReadBytesExt>(source: &mut R) -> ParseResult<Self> {
        match source.get()? {
            0u8 => {
                let icdi = source.get()?;
                Ok(AccountCredential::Initial { icdi })
            }
            1u8 => {
                let cdi = source.get()?;
                Ok(AccountCredential::Normal { cdi })
            }
            n => bail!("AccountCredential::deserial: Unsupported tag {}.", n),
        }
    }
}

#[derive(SerdeSerialize, SerdeDeserialize, Serialize, Debug, Clone)]
#[serde(bound(
    serialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                 Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "P: Pairing, C: Curve<Scalar = P::ScalarField>, AttributeType: \
                   Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
/// Account credential message is an account credential together with a message
/// expiry. This is the payload that is sent to the chain when new accounts are
/// created, either initial accounts or normal accounts.
pub struct AccountCredentialMessage<
    P: Pairing,
    C: Curve<Scalar = P::ScalarField>,
    AttributeType: Attribute<C::Scalar>,
> {
    #[serde(rename = "messageExpiry")]
    pub message_expiry: types::TransactionTime,
    #[serde(rename = "credential")]
    pub credential:     AccountCredential<P, C, AttributeType>,
}

/// A type encapsulating both types of credential values, analogous to
/// AccountCredential.
/// Serialization must match the one in Haskell.
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(tag = "type", content = "contents")]
#[serde(bound(
    serialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeSerialize",
    deserialize = "C: Curve, AttributeType: Attribute<C::Scalar> + SerdeDeserialize<'de>"
))]
pub enum AccountCredentialValues<C: Curve, AttributeType: Attribute<C::Scalar>> {
    #[serde(rename = "initial")]
    Initial {
        #[serde(flatten)]
        icdi: InitialCredentialDeploymentValues<C, AttributeType>,
    },
    #[serde(rename = "normal")]
    Normal {
        #[serde(flatten)]
        cdi: CredentialDeploymentValues<C, AttributeType>,
    },
}

pub trait HasAttributeRandomness<C: Curve, TagType = AttributeTag> {
    type ErrorType: 'static + Send + Sync + std::error::Error;

    fn get_attribute_commitment_randomness(
        &self,
        attribute_tag: &TagType,
    ) -> Result<PedersenRandomness<C>, Self::ErrorType>;
}

#[derive(thiserror::Error, Debug)]
#[error("The randomness for attribute {tag} is missing.")]
pub struct MissingAttributeRandomnessError<TagType> {
    tag: TagType,
}

impl<
        C: Curve,
        TagType: Ord + Clone + std::fmt::Display + std::fmt::Debug + Send + Sync + 'static,
    > HasAttributeRandomness<C, TagType> for BTreeMap<TagType, PedersenRandomness<C>>
{
    type ErrorType = MissingAttributeRandomnessError<TagType>;

    fn get_attribute_commitment_randomness(
        &self,
        attribute_tag: &TagType,
    ) -> Result<PedersenRandomness<C>, Self::ErrorType> {
        self.get(attribute_tag)
            .cloned()
            .ok_or(MissingAttributeRandomnessError {
                tag: attribute_tag.clone(),
            })
    }
}

impl<
        C: Curve,
        TagType: Ord + Clone + std::fmt::Display + std::fmt::Debug + Send + Sync + 'static,
    > HasAttributeRandomness<C, TagType> for BTreeMap<TagType, Value<C>>
{
    type ErrorType = MissingAttributeRandomnessError<TagType>;

    fn get_attribute_commitment_randomness(
        &self,
        attribute_tag: &TagType,
    ) -> Result<PedersenRandomness<C>, Self::ErrorType> {
        self.get(attribute_tag)
            .map(PedersenRandomness::from_value)
            .ok_or(MissingAttributeRandomnessError {
                tag: attribute_tag.clone(),
            })
    }
}

pub trait HasAttributeValues<F: Field, TagType, AttributeType: Attribute<F>> {
    fn get_attribute_value(&self, attribute_tag: &TagType) -> Option<&AttributeType>;
}

impl<F: Field, TagType: Serialize + std::cmp::Ord, AttributeType: Attribute<F>>
    HasAttributeValues<F, TagType, AttributeType> for BTreeMap<TagType, AttributeType>
{
    fn get_attribute_value(&self, attribute_tag: &TagType) -> Option<&AttributeType> {
        self.get(attribute_tag)
    }
}

/// The empty type, here used as an impossible error in the implemention of
/// `HasAttributeRandomness` for `SystemAttributeRandomness`.
#[derive(Debug, Error)]
pub enum ImpossibleError {}

/// Struct implementing `HasAttributeRandomness` using system randomness, to be
/// parsed to the `create_credential` function from account_holder.rs.
pub struct SystemAttributeRandomness;

impl<C: Curve> HasAttributeRandomness<C> for SystemAttributeRandomness {
    type ErrorType = ImpossibleError;

    fn get_attribute_commitment_randomness(
        &self,
        _attribute_tag: &AttributeTag,
    ) -> Result<PedersenRandomness<C>, Self::ErrorType> {
        let mut csprng = rand::thread_rng();
        Ok(PedersenRandomness::generate(&mut csprng))
    }
}

/// A request for recovering an identity
#[derive(SerdeSerialize, SerdeDeserialize)]
#[serde(bound(serialize = "C: Curve", deserialize = "C: Curve"))]
pub struct IdRecoveryRequest<C: Curve> {
    /// The idCredPub to recover the identity object for.
    #[serde(
        rename = "idCredPub",
        serialize_with = "base16_encode",
        deserialize_with = "base16_decode"
    )]
    pub id_cred_pub: C,
    /// Seconds since the unix epoch.
    #[serde(rename = "timestamp")]
    pub timestamp:   u64,
    /// The proof of knowledge of idCredSec corresponding to idCredPub.
    #[serde(rename = "proof")]
    pub proof:       dlog::Proof<C>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519::Signer;

    #[test]
    fn test_serde_sig() {
        use rand::thread_rng;

        let mut csprng = thread_rng();
        let keypair = ed25519::Keypair::generate(&mut csprng);
        for _ in 0..1000 {
            let message: &[u8] = b"test";
            let signature: AccountOwnershipSignature = keypair.sign(message).into();
            let serialized = serde_json::to_string(&signature).unwrap();
            let deserialized: AccountOwnershipSignature =
                serde_json::from_str(&serialized).unwrap();
            assert_eq!(signature, deserialized);
        }
    }

    #[test]
    fn test_yearmonth_serialization() {
        // Test equality
        let ym1 = YearMonth::new(2020, 2).unwrap();
        let ym2 = YearMonth::new(2020, 2).unwrap();
        assert_eq!(ym1, ym2);

        // Test serialization
        let mut buf = Vec::new();
        buf.put(&ym1);
        let mut cursor = std::io::Cursor::new(buf);
        let ym1_parsed = cursor.get().unwrap();
        assert_eq!(ym1, ym1_parsed);

        // Test JSON serialization
        let json = serde_json::to_string(&ym1).unwrap();
        assert_eq!("\"202002\"", json);
        let ym1_parsed = serde_json::from_str(&json).unwrap();
        assert_eq!(ym1, ym1_parsed);

        // Test u64 serialization
        // 202002 => hex: 00000111 11100100 00000010 = dec: 7 228 2 = u64: 517122
        let num: u64 = u64::from(ym1);
        assert_eq!(num, 517122);
        let ym1_parsed = YearMonth::try_from(num).unwrap();
        assert_eq!(ym1, ym1_parsed);
    }

    #[test]
    fn test_aliases() -> anyhow::Result<()> {
        use rand::{thread_rng, Rng};
        let base = AccountAddress(thread_rng().gen());
        for i in 0..(1 << 24) {
            let alias = base
                .get_alias(i)
                .expect("Counter < 2^24, so alias should exist.");
            anyhow::ensure!(
                alias.is_alias(&base),
                "Generated alias {:?} is not an alias of the base address {:?}.",
                alias,
                base
            )
        }
        anyhow::ensure!(base.get_alias(1 << 24).is_none());
        Ok(())
    }

    #[test]
    fn test_timestamp_lower_upper() {
        use chrono::Datelike;
        for year in 1000..=9999 {
            for month in 1..=12 {
                if month == 12 && year == 9999 {
                    continue;
                }
                let ym = YearMonth::new(year, month).unwrap();
                let lower = ym.lower().unwrap();
                let upper = ym.upper().unwrap();
                assert_eq!(lower.year(), year as i32);
                assert_eq!(lower.month(), month as u32);
                assert_eq!(
                    upper.year(),
                    if month == 12 { year + 1 } else { year } as i32
                );
                assert_eq!(
                    upper.month(),
                    if month == 12 { 1 } else { (month + 1) as u32 }
                );

                let lower_from_ts = YearMonth::from_timestamp(lower.timestamp()).unwrap();
                assert_eq!(ym, lower_from_ts);
            }
        }
    }
}