rasn-its 0.28.12

ASN.1 implementations for Intelligent Transport Systems (ITS) V2X communications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
extern crate alloc;
use crate::delegate;
use crate::ts103097::extension_module::*;
use alloc::string::ToString;
use bon::Builder;
use rasn::error::InnerSubtypeConstraintError;
use rasn::prelude::*;

/// IEEE 1609.2 Base Types
/// Based on <https://forge.etsi.org/rep/ITS/asn1/ieee1609.2>
pub mod base_types;
/// IEEE 1609.2 CRL Base Types
pub mod crl_base_types;
use base_types::*;

/// OID for IEEE 1609.2 module
pub const IEEE1609_DOT2_OID: &Oid = Oid::const_new(&[
    1,    // iso
    3,    // identified-organization
    111,  // ieee
    2,    // standards-association-numbered-series-standards
    1609, // wave-stds
    2,    // dot2
    1,    // base
    1,    // schema
    2,    // major-version-2
    6,    // minor-version-6
]);

pub const CERT_EXT_ID_OPERATING_ORGANIZATION: ExtId = ExtId(1);
pub const P2PCD8_BYTE_LEARNING_REQUEST_ID: ExtId = ExtId(1);

//***************************************************************************
//                               Secured Data
//***************************************************************************

/// Contains other data types in this clause.
///
/// # Fields
/// - `protocol_version`: Current version of the protocol (version 3, represented
///   by integer 3). There are no major or minor version numbers.
/// - `content`: Contains the content in the form of an `Ieee1609Dot2Content`
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2.
/// The canonicalization applies to the `Ieee1609Dot2Content`.
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct Ieee1609Dot2Data {
    #[builder(default = Ieee1609Dot2Data::VERSION)]
    #[rasn(value("3"), identifier = "protocolVersion")]
    pub protocol_version: Uint8,
    pub content: Ieee1609Dot2Content,
}
impl Ieee1609Dot2Data {
    pub const VERSION: u8 = 3;
}

/// Content types for IEEE 1609.2 data structures.
///
/// # Variants
/// - `UnsecuredData`: OCTET STRING to be consumed outside the SDS
/// - `SignedData`: Content signed according to this standard
/// - `EncryptedData`: Content encrypted according to this standard
/// - `SignedCertificateRequest`: Certificate request signed by an IEEE 1609.2
///   certificate or self-signed
/// - `SignedX509CertificateRequest`: Certificate request signed by an ITU-T X.509
///   certificate
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2 when type is
/// `SignedData`. The canonicalization applies to the `SignedData` structure.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum Ieee1609Dot2Content {
    UnsecuredData(Opaque),
    SignedData(alloc::boxed::Box<SignedData>),
    EncryptedData(EncryptedData),
    SignedCertificateRequest(Opaque),
    #[rasn(extension_addition)]
    SignedX509CertificateRequest(Opaque),
}
/// Structure containing signed data and signature information.
///
/// # Fields
/// - `hash_id`: Hash algorithm used to generate the message hash for signing
///   and verification
/// - `tbs_data`: Data that is hashed as input to the signature
/// - `signer`: Determines keying material and hash algorithm used to sign the data
/// - `signature`: Digital signature calculated as specified in 5.3.1
///
/// # Signature Calculation
/// ## For Self-Signed
/// When `signer` indicates "self":
/// - Data input: COER encoding of `tbs_data` field (canonicalized per 6.3.6)
/// - Verification type: self
/// - Signer identifier input: empty string
///
/// ## For Certificate or Digest
/// When `signer` indicates "certificate" or "digest":
/// - Data input: COER encoding of `tbs_data` field (canonicalized per 6.3.6)
/// - Verification type: certificate
/// - Signer identifier input: COER-encoding of the Certificate used for
///   verification (canonicalized per 6.4.3)
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2.
/// Applies to both `ToBeSignedData` and `Signature`.
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct SignedData {
    #[rasn(identifier = "hashId")]
    pub hash_id: HashAlgorithm,
    #[rasn(identifier = "tbsData")]
    pub tbs_data: ToBeSignedData,
    pub signer: SignerIdentifier,
    pub signature: Signature,
}
/// Contains the data to be hashed when generating or verifying a signature.
/// See section 6.3.4 for hash input specification.
///
/// # Fields
/// - `payload`: Data provided by the entity invoking the SDS
/// - `header_info`: Additional data inserted by the SDS
///
/// # Hash Operation Input
/// The data input to the hash operation (per 5.3.1.2.2 or 5.3.1.3) is determined as follows:
///
/// ## When payload is present
/// - Uses COER encoding of the `ToBeSignedData`
///
/// ## When payload is omitted
/// - Uses concatenation of:
///   1. COER encoding of the `ToBeSignedData`
///   2. Hash of the omitted payload (using same hash algorithm as main operation)
/// - No additional wrapping or length indication
/// - Method for establishing omitted payload contents between signer and verifier
///   is out of scope (see 5.2.4.3.4)
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2.
/// Applies to:
/// - `SignedDataPayload` (when type is "data")
/// - `HeaderInfo`
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct ToBeSignedData {
    pub payload: SignedDataPayload,
    #[rasn(identifier = "headerInfo")]
    pub header_info: HeaderInfo,
}

/// Contains the data payload of a `ToBeSignedData`. Must contain at least one
/// optional element, and may contain multiple. See section 5.2.4.3.4 for details.
///
/// # Implementation Support
/// The security profile in Annex C allows implementations to specify:
/// - Supported forms of `SignedDataPayload`
/// - Methods for signers and verifiers to obtain external data for hashing
///
/// SDEE specifications using external data must explicitly define:
/// - How to obtain the data
/// - How to format the data before hash processing
///
/// # Fields
/// - `data`: Data explicitly transported within the structure
/// - `ext_data_hash`: Hash of data not explicitly transported, which the creator
///   wishes to cryptographically bind to the signature
/// - `omitted`: Indicates external data to be included in signature hash calculation
///   (mechanism specified in 6.3.6)
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2.
/// The canonicalization applies to the `Ieee1609Dot2Data`.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
#[non_exhaustive]
pub struct SignedDataPayload {
    pub data: Option<Ieee1609Dot2Data>,
    #[rasn(identifier = "extDataHash")]
    pub ext_data_hash: Option<HashedData>,
    #[rasn(extension_addition)]
    pub omitted: Option<()>,
}

#[bon::bon]
impl SignedDataPayload {
    #[builder]
    pub fn new(
        data: Option<Ieee1609Dot2Data>,
        ext_data_hash: Option<HashedData>,
        omitted: Option<()>,
    ) -> Result<Self, InnerSubtypeConstraintError> {
        Self {
            data,
            ext_data_hash,
            omitted,
        }
        .validate_components()
    }
}

impl InnerSubtypeConstraint for SignedDataPayload {
    fn validate_and_decode_containing(
        self,
        _: Option<rasn::Codec>,
    ) -> Result<Self, rasn::error::InnerSubtypeConstraintError> {
        if self.data.is_none() && self.ext_data_hash.is_none() && self.omitted.is_none() {
            return Err(InnerSubtypeConstraintError::MissingRequiredComponent {
                component_path: "SignedDataPayload",
                components: &["data", "ext_data_hash", "omitted"],
            });
        }
        Ok(self)
    }
}

/// Contains the hash of data with a specified hash algorithm. See section 5.3.3
/// for permitted hash algorithms.
///
/// # Variants
/// - `Sha256HashedData`: Data hashed with SHA-256
/// - `Sha384HashedData`: Data hashed with SHA-384
/// - `Sm3HashedData`: Data hashed with SM3
///
/// # Critical Information Field
/// This is a critical information field as defined in 5.2.6:
/// - An implementation that does not recognize the indicated CHOICE when verifying
///   a signed SPDU shall indicate that the SPDU is invalid (per 4.2.2.3.2)
/// - Invalid in this context means its validity cannot be established
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum HashedData {
    Sha256HashedData(HashedId32),
    #[rasn(extension_addition)]
    Sha384HashedData(HashedId48),
    #[rasn(extension_addition)]
    Sm3HashedData(HashedId32),
}

/// Contains information used to establish validity per criteria in section 5.2.
///
/// # Fields
/// - `psid`: Application area with which sender claims payload association
///
/// - `generation_time`: Time of structure generation (see 5.2.5.2.2 and 5.2.5.2.3)
///
/// - `expiry_time`: Time after which data is no longer relevant
///   - If both `generation_time` and `expiry_time` present, SPDU is invalid if
///     `generation_time` is not strictly earlier than `expiry_time`
///
/// - `generation_location`: Location where signature was generated
///
/// - `p2pcd_learning_request`: Used to request certificates with known identifiers
///   but unknown full content
///   - Used for separate-certificate-pdu P2PCD (Clause 8)
///   - Mutually exclusive with `inline_p2pcd_request`
///   - `HashedId3` calculated using whole-certificate hash algorithm (see 6.4.3)
///
/// - `missing_crl_identifier`: For requesting known-issued but unreceived CRLs
///   (reserved for future use)
///
/// - `encryption_key`: Key for encrypting response SPDUs
///   - SDEE specification defines which responses use this key
///   - See 6.3.35, 6.3.37, and 6.3.34 for usage details
///   - Symmetric key type should only be used with encrypted SignedData
///
/// - `inline_p2pcd_request`: For requesting unknown certificates via inline P2PCD
///   - Mutually exclusive with `p2pcd_learning_request`
///   - `HashedId3` calculated as per 6.4.3
///
/// - `requested_certificate`: Provides certificates for inline P2PCD (Clause 8)
///
/// - `pdu_functional_type`: Indicates SPDU consumption by non-application process
///   (ISO 21177 B14a, see 6.3.23b)
///
/// - `contributed_extensions`: Additional extensions using `ContributedExtensionBlocks`
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2:
/// - Applies to `EncryptionKey`
/// - For public `EncryptionKey` with elliptic curve points (`EccP256CurvePoint` or
///   `EccP384CurvePoint`):
///   - Points must be in compressed form (`compressed-y-0` or `compressed-y-1`)
/// - Does not apply to fields after extension marker, including `contributed_extensions`
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
#[non_exhaustive]
pub struct HeaderInfo {
    pub psid: Psid,
    #[rasn(identifier = "generationTime")]
    pub generation_time: Option<Time64>,
    #[rasn(identifier = "expiryTime")]
    pub expiry_time: Option<Time64>,
    #[rasn(identifier = "generationLocation")]
    pub generation_location: Option<ThreeDLocation>,
    #[rasn(identifier = "p2pcdLearningRequest")]
    pub p2pcd_learning_request: Option<HashedId3>,
    #[rasn(identifier = "missingCrlIdentifier")]
    pub missing_crl_identifier: Option<MissingCrlIdentifier>,
    #[rasn(identifier = "encryptionKey")]
    pub encryption_key: Option<EncryptionKey>,
    #[rasn(extension_addition, identifier = "inlineP2pcdRequest")]
    pub inline_p2pcd_request: Option<SequenceOfHashedId3>,
    #[rasn(extension_addition, identifier = "requestedCertificate")]
    pub requested_certificate: Option<Certificate>,
    #[rasn(extension_addition, identifier = "pduFunctionalType")]
    pub pdu_functional_type: Option<PduFunctionalType>,
    #[rasn(extension_addition, identifier = "contributedExtensions")]
    pub contributed_extensions: Option<ContributedExtensionBlocks>,
}

/// Structure for requesting a known-issued but unreceived CRL.
/// Provided for future use; not defined in current standard version.
///
/// # Fields
/// - `craca_id`: HashedId3 of the CRACA (defined in 5.1.3)
///   - Calculated using whole-certificate hash algorithm (per 6.4.3)
///   - Applied to COER-encoded certificate
///   - Certificate must be canonicalized per Certificate definition
///
/// - `crl_series`: Requested CRL Series value (see 5.1.3 for details)
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
#[non_exhaustive]
pub struct MissingCrlIdentifier {
    #[rasn(identifier = "cracaId")]
    pub craca_id: HashedId3,
    #[rasn(identifier = "crlSeries")]
    pub crl_series: CrlSeries,
}

/// Identifies the functional entity intended to consume an SPDU, specifically for
/// security support services rather than application processes.
/// Further details defined in ISO 21177 B20.
///
/// # Values
/// - `1`: TLS Handshake
///   - Not for direct application PDU consumption
///   - Used for securing communications to application process
///   - Provides holder's permissions to TLS handshake
///   - References: IETF 5246 B15, IETF 8446 B16, ISO 21177 B20
///
/// - `2`: ISO 21177 Extended Auth
///   - Not for direct application PDU consumption
///   - Provides additional holder permissions information
///   - See ISO 21177 B20 for details
///
/// - `3`: ISO 21177 Session Extension
///   - Not for direct application PDU consumption
///   - Enables session persistence beyond certificate lifetime
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate, value("0..=255"))]
pub struct PduFunctionalType(pub u8);

delegate!(u8, PduFunctionalType);

/// TLS Handshake process
pub const TLS_HANDSHAKE: PduFunctionalType = PduFunctionalType(1);
/// ISO 21177 Extended Authentication
pub const ISO21177_EXTENDED_AUTH: PduFunctionalType = PduFunctionalType(2);
/// ISO 21177 Session Extension
pub const ISO21177_SESSION_EXTENSION: PduFunctionalType = PduFunctionalType(3);

/// This type is used for clarity of definitions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate, size("1.."))]
pub struct ContributedExtensionBlocks(pub SequenceOf<ContributedExtensionBlockType>);

delegate!(
    SequenceOf<ContributedExtensionBlockType>,
    ContributedExtensionBlocks
);

pub trait HeaderInfoContributedExtension {
    type Extn: AsnType + Encode + Decode;
    const ID: HeaderInfoContributorId;
}

#[derive(AsnType, Copy, Clone, Debug, Encode, Decode, PartialEq, Eq, Hash)]
#[rasn(enumerated)]
#[non_exhaustive]
pub enum Ieee1609HeaderInfoExtensions {}

impl ExtType for Ieee1609HeaderInfoExtensions {
    type ExtContent = HashedId8;
    const EXT_ID: ExtId = P2PCD8_BYTE_LEARNING_REQUEST_ID;
}

impl HeaderInfoContributedExtension for Ieee1609ContributedHeaderInfoExtension {
    type Extn = Extension<Ieee1609HeaderInfoExtensions>;
    const ID: HeaderInfoContributorId = IEEE1609_HEADER_INFO_CONTRIBUTOR_ID;
}
impl HeaderInfoContributedExtension for EtsiOriginatingHeaderInfoExtension {
    type Extn = EtsiOriginatingHeaderInfoExtension;
    const ID: HeaderInfoContributorId = ETSI_HEADER_INFO_CONTRIBUTOR_ID;
}

/// Uses the parameterized type `Extension` to define an
/// `Ieee1609ContributedHeaderInfoExtension`.
///
/// Contains an open Extension Content field identified by an extension identifier.
/// The extension identifier value is:
/// - Unique within ETSI-defined extensions
/// - Not required to be unique across all contributing organizations
#[derive(AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
pub struct Ieee1609ContributedHeaderInfoExtension(pub Extension<Ieee1609HeaderInfoExtensions>);

delegate!(
    Extension<Ieee1609HeaderInfoExtensions>,
    Ieee1609ContributedHeaderInfoExtension
);

/// Defines the format of an extension block provided by an identified contributor.
///
/// Uses the template from `IEEE1609DOT2-HEADERINFO-CONTRIBUTED-EXTENSION` class
/// constraint applied to objects in `Ieee1609Dot2HeaderInfoContributedExtensions`.
///
/// # Fields
/// - `contributor_id`: Uniquely identifies the contributor
/// - `extns`: List of extensions from that contributor
///   - Extensions typically follow format specified in section 6.5,
///     but this is not required
#[derive(AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
pub struct ContributedExtensionBlock<T: HeaderInfoContributedExtension> {
    #[rasn(identifier = "contributorId")]
    pub contributor_id: HeaderInfoContributorId,
    #[rasn(size("1.."))]
    pub extns: SequenceOf<T::Extn>,
}

#[derive(AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
#[rasn(choice)]
#[rasn(automatic_tags)]
#[non_exhaustive]
pub enum ContributedExtensionBlockType {
    Ieee1609(ContributedExtensionBlock<Ieee1609ContributedHeaderInfoExtension>),
    Etsi(ContributedExtensionBlock<EtsiOriginatingHeaderInfoExtension>),
}

/// Integer identifying a HeaderInfo extension contributing organization.
///
/// # Defined Values
/// - `1` (IEEE1609): Extensions originating with IEEE 1609
/// - `2` (ETSI): Extensions originating with ETSI TC ITS
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[rasn(delegate)]
pub struct HeaderInfoContributorId(pub u8);

delegate!(u8, HeaderInfoContributorId);

// Defined contributor IDs
pub const ETSI_HEADER_INFO_CONTRIBUTOR_ID: HeaderInfoContributorId = HeaderInfoContributorId(2);
pub const IEEE1609_HEADER_INFO_CONTRIBUTOR_ID: HeaderInfoContributorId = HeaderInfoContributorId(1);

/// Allows recipients to determine which keying material to use for data
/// authentication and indicates the verification type for hash generation
/// (specified in 5.3.1).
///
/// # Variants
/// ## Digest
/// Contains HashedId8 of the relevant certificate:
/// - Calculated with whole-certificate hash algorithm (per 6.4.3)
/// - Verification type: certificate
/// - Certificate data passed to hash function is authorization certificate
///
/// ## Certificate
/// Contains one or more Certificate structures:
/// - First certificate is authorization certificate
/// - Subsequent certificates are issuers of preceding certificates
/// - Verification type: certificate
/// - Certificate data passed to hash function is authorization certificate
///
/// ## SelfSigned
/// - Contains no additional data
/// - Verification type: self-signed
///
/// # Critical Information Fields
/// This is a critical information field (5.2.6):
/// - Implementation must recognize CHOICE value when verifying signed SPDU
/// - For Certificate variant:
///   - Must support at least one certificate
///   - Must support specified number of certificates
/// - Invalid SPDU if requirements not met
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2:
/// - Applies to every Certificate in the certificate field
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum SignerIdentifier {
    Digest(HashedId8),
    Certificate(SequenceOfCertificate),
    #[rasn(identifier = "self")]
    SelfSigned(()),
}

/// This data structure is used to perform a countersignature over an already-signed SPDU.
///
/// This is the profile of an Ieee1609Dot2Data containing a signedData.
/// The tbsData within content is composed of a payload containing the hash
/// (extDataHash) of the externally generated, pre-signed
/// SPDU over which the countersignature is performed.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct Countersignature(Ieee1609Dot2Data);
#[bon::bon]
impl Countersignature {
    #[builder]
    fn new(data: Ieee1609Dot2Data) -> Result<Self, InnerSubtypeConstraintError> {
        Self(data).validate_components()
    }
}

impl InnerSubtypeConstraint for Countersignature {
    fn validate_and_decode_containing(
        self,
        _: Option<rasn::Codec>,
    ) -> Result<Self, rasn::error::InnerSubtypeConstraintError> {
        if let Ieee1609Dot2Content::SignedData(ref signed_data) = self.0.content {
            if let SignedData {
                tbs_data:
                    ToBeSignedData {
                        payload:
                            SignedDataPayload {
                                data: None,
                                ext_data_hash: Some(_),
                                ..
                            },
                        header_info:
                            HeaderInfo {
                                generation_time: Some(_),
                                expiry_time: None,
                                generation_location: None,
                                p2pcd_learning_request: None,
                                missing_crl_identifier: None,
                                encryption_key: None,
                                ..
                            },
                        ..
                    },
                ..
            } = **signed_data
            {
                Ok(self)
            } else {
                Err(InnerSubtypeConstraintError::InvalidComponentVariant {
                    component_path: "Ieee1609Dot2Data.content.tbsData",
                    component_type: "Ieee1609Dot2Content::SignedData",
                    details:
                        "SignedData does not match inner subtype constraint for Countersignature"
                            .to_string(),
                })
            }
        } else {
            Err(InnerSubtypeConstraintError::InvalidComponentVariant {
                component_path: "Ieee1609Dot2Data.content",
                component_type: "Ieee1609Dot2Content",
                details: "SignedData variant is required for Countersignature".to_string(),
            })
        }
    }
}

// ***************************************************************************
// **                            Encrypted Data                             **
// ***************************************************************************

/// Encodes data encrypted to one or more recipients using their public or symmetric
/// keys as specified in 5.3.4.
///
/// # Fields
/// - `recipients`: One or more `RecipientInfo` entries
///   - May contain multiple types of `RecipientInfo`
///   - All entries must indicate/contain the same data encryption key
///
/// - `ciphertext`: Encrypted data
///   - Contains encrypted `Ieee1609Dot2Data` structure (per 5.3.4.2)
///
/// # Critical Information Fields
/// The `recipients` field is critical (per 5.2.6):
/// - Implementation must support specified number of `RecipientInfo` entries
/// - Must support at least eight entries
/// - Failure to support required number results in decryption failure
///
/// # Raw Data Example
/// For plaintext that isn't from previous SDS operation, it can be encapsulated
/// in `Ieee1609Dot2Data` of type `unsecuredData` (per 4.2.2.2.2):
/// ```text
/// Raw data:    01 23 45 67 89 AB CD EF
/// COER encoded: 03 80 08 01 23 45 67 89 AB CD EF
/// Where:
/// - 03: protocolVersion
/// - 80: choice unsecuredData
/// - 08: length of raw data
/// ```
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct EncryptedData {
    pub recipients: SequenceOfRecipientInfo,
    pub ciphertext: SymmetricCiphertext,
}

/// Transfers data encryption key to individual recipients of `EncryptedData`.
/// See Annex C.7 for guidance on appropriate use of each approach.
///
/// # Variants
/// ## `PskRecipInfo`
/// Data encrypted directly using pre-shared symmetric key
/// - Used with static encryption key approach (5.3.4)
///
/// ## `SymmRecipInfo`
/// Data encrypted with data encryption key, which was encrypted using symmetric key
/// - Used with ephemeral encryption key approach (5.3.4)
///
/// ## `CertRecipInfo`
/// Data encrypted with data encryption key, which was encrypted using public key from certificate
/// - Used with ephemeral encryption key approach (5.3.4)
/// - For ECIES: Parameter P1 (5.3.5) is certificate hash
///   - Using whole-certificate hash algorithm (6.4.3)
///   - Applied to COER-encoded, canonicalized certificate
/// - For SM2: No P1 parameter equivalent
///
/// ## `SignedDataRecipInfo`
/// Data encrypted with data encryption key, which was encrypted using public key from SignedData
/// - For ECIES: Parameter P1 (5.3.5) is SHA-256 hash of canonicalized `Ieee1609Dot2Data`
/// - For SM2: No P1 parameter equivalent
///
/// ## `RekRecipInfo`
/// Data encrypted with data encryption key, which was encrypted using public key from other source
/// - SDEE specification defines public key source
/// - For ECIES: Parameter P1 (5.3.5) is hash of empty string
/// - For SM2: No P1 parameter equivalent
///
/// # Implementation Note
/// Encryption key input is raw bytes without headers, encapsulation, or length indication
/// (unlike data encryption, where data is encapsulated in `Ieee1609Dot2Data`)
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
pub enum RecipientInfo {
    PskRecipInfo(PreSharedKeyRecipientInfo),
    SymmRecipInfo(SymmRecipientInfo),
    CertRecipInfo(PKRecipientInfo),
    SignedDataRecipInfo(PKRecipientInfo),
    RekRecipInfo(PKRecipientInfo),
}

/// This type is used for clarity of definitions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct SequenceOfRecipientInfo(pub SequenceOf<RecipientInfo>);

delegate!(SequenceOf<RecipientInfo>, SequenceOfRecipientInfo);

/// Indicates a symmetric key that may be used directly to decrypt a `SymmetricCiphertext`.
///
/// # Value Calculation
/// Contains the low-order 8 bytes of a hash calculated from:
/// - COER encoding of a `SymmetricEncryptionKey` structure containing the symmetric key
/// - Hash algorithm determined as specified in 5.3.9.3
///
/// # Note
/// The symmetric key may be established by any appropriate means agreed by the
/// two parties to the exchange.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct PreSharedKeyRecipientInfo(pub HashedId8);

delegate!(HashedId8, PreSharedKeyRecipientInfo);

/// Contains recipient identification and encrypted data encryption key information.
///
/// # Fields
/// ## `recipient_id`
/// Hash of the symmetric key encryption key for decrypting the data encryption key:
/// - Contains low-order 8 bytes of hash
/// - Calculated from COER encoding of `SymmetricEncryptionKey` structure
/// - Uses hash algorithm specified in 5.3.9.4
/// - Symmetric key may be established by any agreed means between parties
///
/// ## `enc_key`
/// Contains encrypted data encryption key in `SymmetricCiphertext`:
/// - Key is input to encryption process without headers, encapsulation,
///   or length indication
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct SymmRecipientInfo {
    #[rasn(identifier = "recipientId")]
    pub recipient_id: HashedId8,
    #[rasn(identifier = "encKey")]
    pub enc_key: SymmetricCiphertext,
}

/// Contains recipient information and encrypted data encryption key.
///
/// # Fields
/// ## `recipient_id`
/// Contains hash of the encryption public key container, calculated differently
/// based on the containing `RecipientInfo` structure:
///
/// - For `certRecipInfo`:
///   - Contains `HashedId8` of the certificate
///   - Calculated using whole-certificate hash algorithm (per 6.4.3)
///   - Applied to COER-encoded certificate, canonicalized per Certificate definition
///
/// - For `signedDataRecipInfo`:
///   - Contains `HashedId8` of the `Ieee1609Dot2Data` (type signedData)
///   - Data canonicalized per 6.3.4
///   - Hash algorithm determined per 5.3.9.5
///
/// - For `rekRecipInfo`:
///   - Contains `HashedId8` of COER-encoded `PublicEncryptionKey`
///   - Hash algorithm determined per 5.3.9.5
///
/// ## `enc_key`
/// Contains the encrypted data encryption key:
/// - Key is input to encryption process without headers, encapsulation,
///   or length indication
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct PKRecipientInfo {
    #[rasn(identifier = "recipientId")]
    pub recipient_id: HashedId8,
    #[rasn(identifier = "encKey")]
    pub enc_key: EncryptedDataEncryptionKey,
}

/// Contains encrypted data encryption key, input to encryption process without
/// headers, encapsulation, or length indication.
///
/// # Critical Information Field
/// If present and applicable to receiving SDEE, this is critical (per 5.2.6):
/// - If implementation receives encrypted SPDU and:
///   - Determines one or more `RecipientInfo` fields are relevant
///   - All relevant `RecipientInfos` contain unrecognized CHOICE in
///     `EncryptedDataEncryptionKey`
/// - Then implementation must indicate SPDU is not decryptable
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum EncryptedDataEncryptionKey {
    EciesNistP256(EciesP256EncryptedKey),
    EciesBrainpoolP256r1(EciesP256EncryptedKey),
    #[rasn(extension_addition)]
    EcencSm2256(EcencP256EncryptedKey),
}

/// Encapsulates a ciphertext generated with an approved symmetric algorithm.
///
/// # Critical Information Field
/// This is a critical information field as defined in 5.2.6:
/// - An implementation that does not recognize the indicated CHOICE value in an
///   encrypted SPDU shall indicate that the SPDU is invalid (per 4.2.2.3.2)
/// - Invalid in this context means its validity cannot be established
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum SymmetricCiphertext {
    Aes128ccm(One28BitCcmCiphertext),
    #[rasn(extension_addition)]
    Sm4Ccm(One28BitCcmCiphertext),
}

/// Encapsulates encrypted ciphertext for symmetric algorithms with 128-bit blocks
/// in CCM mode.
///
/// # Characteristics
/// - Ciphertext is 16 bytes longer than plaintext (includes MAC)
/// - Successful decryption yields either:
///   - COER-encoded `Ieee1609Dot2Data` structure (see 6.3.41)
///   - 16-byte symmetric key (see 6.3.44)
///
/// # Fields
/// - `nonce`: Contains nonce N as specified in 5.3.8
/// - `ccm_ciphertext`: Contains ciphertext C as specified in 5.3.8
///
/// # Name Clarification
/// The "One28" in the structure name refers to:
/// - The symmetric cipher block size (128 bits)
/// - Not the key length (though AES-128-CCM and SM4-CCM happen to use 128-bit keys)
///
/// Since the cipher operates in counter mode (stream cipher):
/// - Block size only affects MAC size
/// - Does not affect raw ciphertext size
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct One28BitCcmCiphertext {
    pub nonce: FixedOctetString<12>,
    #[rasn(identifier = "ccmCiphertext")]
    pub ccm_ciphertext: Opaque,
}

/// This type is defined only for backwards compatibility.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct Aes128CcmCiphertext(pub One28BitCcmCiphertext);

delegate!(One28BitCcmCiphertext, Aes128CcmCiphertext);

// ***************************************************************************
// **              Certificates and other Security Management               **
// ***************************************************************************

/// A profile of the `CertificateBase` structure specifying valid combinations
/// of fields for transmitting implicit and explicit certificates.
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2:
/// - Applies to the `CertificateBase`
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct Certificate(CertificateBase);

impl From<ImplicitCertificate> for Certificate {
    fn from(data: ImplicitCertificate) -> Self {
        Self(data.0)
    }
}
impl From<ExplicitCertificate> for Certificate {
    fn from(data: ExplicitCertificate) -> Self {
        Self(data.0)
    }
}

impl core::ops::Deref for Certificate {
    type Target = CertificateBase;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
    // We should not allow mutation of the inner data if they require validation!
}

#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct TestCertificate(pub Certificate);

delegate!(Certificate, TestCertificate);

/// This type is used for clarity of definitions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct SequenceOfCertificate(pub SequenceOf<Certificate>);

delegate!(SequenceOf<Certificate>, SequenceOfCertificate);

/// Certificate structure containing version, type, issuer, and content information.
///
/// # Fields
/// - `version`: Certificate format version (set to 3 in this version)
/// - `c_type`: Indicates explicit or implicit certificate
/// - `issuer`: Identifies the certificate issuer
/// - `to_be_signed`: Certificate contents, used in hash generation/verification
/// - `signature`: Present in `ExplicitCertificate`, calculated over `to_be_signed` hash
///
/// # Signature Calculation
/// Hash calculated as specified in 5.3.1:
/// - Data input: COER encoding of `to_be_signed`
/// - Signer identifier input:
///   - For self-signed (issuer is self): empty string
///   - Otherwise: Canonicalized COER encoding of issuer's certificate
///
/// # Canonicalization
/// Subject to canonicalization for operations in 6.1.2:
/// - Applies to `ToBeSignedCertificate` and `Signature`
///
/// # Whole-Certificate Hash
/// Used for calculating `HashedId3`, `HashedId8`, or `HashedId10`:
/// - Algorithm determined as specified in 5.3.9.2
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct CertificateBase {
    #[rasn(value("3"))]
    #[builder(default = CertificateBase::VERSION)]
    pub version: Uint8,
    #[rasn(identifier = "type")]
    pub r#type: CertificateType,
    pub issuer: IssuerIdentifier,
    #[rasn(identifier = "toBeSigned")]
    pub to_be_signed: ToBeSignedCertificate,
    pub signature: Option<Signature>,
}
impl CertificateBase {
    pub const VERSION: u8 = 3;
    #[must_use]
    pub const fn is_implicit(&self) -> bool {
        matches!(
            &self,
            CertificateBase {
                r#type: CertificateType::Implicit,
                to_be_signed: ToBeSignedCertificate {
                    verify_key_indicator: VerificationKeyIndicator::ReconstructionValue(_),
                    ..
                },
                signature: None,
                ..
            }
        )
    }
    #[must_use]
    pub const fn is_explicit(&self) -> bool {
        matches!(
            self,
            CertificateBase {
                r#type: CertificateType::Explicit,
                to_be_signed: ToBeSignedCertificate {
                    verify_key_indicator: VerificationKeyIndicator::VerificationKey(_),
                    ..
                },
                signature: Some(_),
                ..
            }
        )
    }
}

/// Indicates whether a certificate is explicit or implicit.
///
/// # Critical Information Field
/// This is a critical information field as defined in 5.2.5:
/// - An implementation that does not recognize the indicated CHOICE when verifying
///   a signed SPDU shall indicate that the SPDU is invalid (per 4.2.2.3.2)
/// - Invalid in this context means its validity cannot be established
#[derive(AsnType, Debug, Clone, Copy, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(enumerated)]
#[non_exhaustive]
pub enum CertificateType {
    Explicit = 0,
    Implicit = 1,
}

/// This is a profile of the CertificateBase structure providing all
///  the fields necessary for an implicit certificate, and no others.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct ImplicitCertificate(CertificateBase);

impl ImplicitCertificate {
    pub fn new(data: CertificateBase) -> Result<Self, InnerSubtypeConstraintError> {
        Self(data).validate_components()
    }
}
impl InnerSubtypeConstraint for ImplicitCertificate {
    fn validate_and_decode_containing(
        self,
        _: Option<rasn::Codec>,
    ) -> Result<Self, rasn::error::InnerSubtypeConstraintError> {
        if self.0.is_implicit() {
            Ok(self)
        } else {
            Err(InnerSubtypeConstraintError::SubtypeConstraintViolation {
                component_path: "ImplicitCertificate",
                details: "CertificateBase is not implicit certificate",
            })
        }
    }
}

impl core::ops::Deref for ImplicitCertificate {
    type Target = CertificateBase;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
    // We should not allow mutation of the inner data if they require validation!
}

/// This is a profile of the CertificateBase structure providing all the fields necessary for an explicit certificate, and no others.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct ExplicitCertificate(CertificateBase);

impl ExplicitCertificate {
    pub fn new(data: CertificateBase) -> Result<Self, InnerSubtypeConstraintError> {
        Self(data).validate_components()
    }
}

impl InnerSubtypeConstraint for ExplicitCertificate {
    fn validate_and_decode_containing(
        self,
        _: Option<rasn::Codec>,
    ) -> Result<Self, rasn::error::InnerSubtypeConstraintError> {
        if self.0.is_explicit() {
            Ok(self)
        } else {
            Err(InnerSubtypeConstraintError::SubtypeConstraintViolation {
                component_path: "ExplicitCertificate",
                details: "CertificateBase is not explicit certificate",
            })
        }
    }
}
impl core::ops::Deref for ExplicitCertificate {
    type Target = CertificateBase;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
    // We should not allow mutation of the inner data if they require validation!
}

/// Allows certificate recipients to determine which keying material to use for
/// certificate authentication.
///
/// # Variants
/// ## `Sha256AndDigest`, `Sha384AndDigest`, `Sm3AndDigest`
/// - Contains `HashedId8` of issuing certificate
///   - Calculated with whole-certificate hash algorithm (per 6.4.3)
///   - Applied to COER-encoded, canonicalized certificate
/// - Hash algorithm for certificate verification:
///   - `Sha256AndDigest`: SHA-256
///   - `Sha384AndDigest`: SHA-384
///   - `Sm3AndDigest`: SM3
/// - Certificate verified with public key of indicated issuing certificate
///
/// ## `VSelf`
/// - Indicates hash algorithm for certificate verification
/// - Certificate verified with public key from `verifyKeyIndicator` in `ToBeSignedCertificate`
///
/// # Critical Information Field
/// This is a critical information field as defined in 5.2.5:
/// - An implementation that does not recognize the indicated CHOICE when verifying
///   a signed SPDU shall indicate that the SPDU is invalid (per 4.2.2.3.2)
/// - Invalid in this context means its validity cannot be established
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum IssuerIdentifier {
    Sha256AndDigest(HashedId8),
    #[rasn(identifier = "self")]
    VSelf(HashAlgorithm),
    #[rasn(extension_addition)]
    Sha384AndDigest(HashedId8),
    #[rasn(extension_addition)]
    Sm3AndDigest(HashedId8),
}

/// Certificate data to be signed, containing identification and permissions information.
///
/// This is summary. For the most accurate information, consult the source ASN.1 definitions.
///
/// # Hash Calculation
/// For both implicit and explicit certificates, hash is calculated as:
/// `Hash(Data input) || Hash(Signer identifier input)` where:
/// - Data input: COER encoding of toBeSigned (canonicalized)
/// - Signer identifier input depends on verification type:
///   - For self-signed (issuer is self): empty string
///   - For certificate: COER encoding of canonicalized issuer certificate
///
/// For implicit certificates, H(CertU) from SEC 4 is:
/// `H[H(canonicalized ToBeSignedCertificate) || H(issuer Certificate)]`
/// See 5.3.2 for differences from SEC 4 regarding hash-to-integer conversion.
///
/// # Fields
/// - `id`: Certificate holder identification
/// - `craca_id`: Certificate Revocation Authorization CA identifier
///   - HashedId3 calculated with whole-certificate hash algorithm (6.4.3)
/// - `crl_series`: CRL series for CRACA
/// - `validity_period`: Certificate validity period
/// - `region`: Validity region (if omitted):
///   - Self-signed: Valid worldwide
///   - Otherwise: Same as issuing certificate
/// - `assurance_level`: Certificate holder's assurance level
/// - `app_permissions`: Application data signing permissions
///   - Each Psid can appear at most once
/// - `cert_issue_permissions`: Certificate signing permissions
///   - At most one entry with "all" permissions
/// - `cert_request_permissions`: Certificate request permissions
///   - At most one entry with "all" permissions
/// - `can_request_rollover`: Permission to request same-permission certificate
///   - Reserved for future use
/// - `encryption_key`: Public encryption key
/// - `verify_key_indicator`: Public key recovery material
/// - `flags`: Additional properties
///   - `usesCubk`: Supports compact unified butterfly key response
///     - Only relevant for CA certificates
///     - Used only for certificate response consistency checks
/// - `app_extensions`: Additional application activity permissions
/// - `cert_issue_extensions`: Additional certificate issuing permissions
/// - `cert_request_extensions`: Additional certificate request permissions
///
/// # Canonicalization
/// Subject to canonicalization (6.1.2):
/// - Applies to `PublicEncryptionKey` and `VerificationKeyIndicator`
/// - Elliptic curve points must use compressed form (`compressed-y-0`/`compressed-y-1`)
///
/// # Critical Information Fields
/// ## App Permissions
/// - Critical field per 5.2.6
/// - Must support at least 8 entries
/// - Invalid SPDU if verification fails
///
/// ## Cert Issue Permissions
/// - Critical field per 5.2.6
/// - Must support at least 8 entries
/// - Invalid SPDU if CA certificate chain verification fails
///
/// ## Cert Request Permissions
/// - Critical field per 5.2.6
/// - Must support at least 8 entries
/// - Invalid SPDU if request verification fails
///
/// Implementation-specific behavior when non-relevant fields exceed supported size.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
#[non_exhaustive]
pub struct ToBeSignedCertificate {
    pub id: CertificateId,
    #[rasn(identifier = "cracaId")]
    pub craca_id: HashedId3,
    #[rasn(identifier = "crlSeries")]
    pub crl_series: CrlSeries,
    #[rasn(identifier = "validityPeriod")]
    pub validity_period: ValidityPeriod,
    pub region: Option<GeographicRegion>,
    #[rasn(identifier = "assuranceLevel")]
    pub assurance_level: Option<SubjectAssurance>,
    #[rasn(identifier = "appPermissions")]
    pub app_permissions: Option<SequenceOfPsidSsp>,
    #[rasn(identifier = "certIssuePermissions")]
    pub cert_issue_permissions: Option<SequenceOfPsidGroupPermissions>,
    #[rasn(identifier = "certRequestPermissions")]
    pub cert_request_permissions: Option<SequenceOfPsidGroupPermissions>,
    #[rasn(identifier = "canRequestRollover")]
    pub can_request_rollover: Option<()>,
    #[rasn(identifier = "encryptionKey")]
    pub encryption_key: Option<PublicEncryptionKey>,
    #[rasn(identifier = "verifyKeyIndicator")]
    pub verify_key_indicator: VerificationKeyIndicator,
    #[rasn(extension_addition)]
    pub flags: Option<FixedBitString<8>>,
    #[rasn(extension_addition, identifier = "appExtensions")]
    pub app_extensions: Option<SequenceOfAppExtensions>,
    #[rasn(extension_addition, identifier = "certIssueExtensions")]
    pub cert_issue_extensions: Option<SequenceOfCertIssueExtensions>,
    #[rasn(extension_addition, identifier = "certRequestExtension")]
    pub cert_request_extension: Option<SequenceOfCertRequestExtensions>,
}
#[bon::bon]
impl ToBeSignedCertificate {
    #[builder]
    pub fn new(
        id: CertificateId,
        craca_id: HashedId3,
        crl_series: CrlSeries,
        validity_period: ValidityPeriod,
        region: Option<GeographicRegion>,
        assurance_level: Option<SubjectAssurance>,
        app_permissions: Option<SequenceOfPsidSsp>,
        cert_issue_permissions: Option<SequenceOfPsidGroupPermissions>,
        cert_request_permissions: Option<SequenceOfPsidGroupPermissions>,
        can_request_rollover: Option<()>,
        encryption_key: Option<PublicEncryptionKey>,
        verify_key_indicator: VerificationKeyIndicator,
        flags: Option<FixedBitString<8>>,
        app_extensions: Option<SequenceOfAppExtensions>,
        cert_issue_extensions: Option<SequenceOfCertIssueExtensions>,
        cert_request_extension: Option<SequenceOfCertRequestExtensions>,
    ) -> Result<Self, InnerSubtypeConstraintError> {
        let cert = Self {
            id,
            craca_id,
            crl_series,
            validity_period,
            region,
            assurance_level,
            app_permissions,
            cert_issue_permissions,
            cert_request_permissions,
            can_request_rollover,
            encryption_key,
            verify_key_indicator,
            flags,
            app_extensions,
            cert_issue_extensions,
            cert_request_extension,
        };
        cert.validate_components()
    }
}

impl InnerSubtypeConstraint for ToBeSignedCertificate {
    fn validate_and_decode_containing(
        self,
        _: Option<rasn::Codec>,
    ) -> Result<Self, rasn::error::InnerSubtypeConstraintError> {
        if self.app_permissions.is_none()
            && self.cert_issue_permissions.is_none()
            && self.cert_request_permissions.is_none()
        {
            return Err(InnerSubtypeConstraintError::MissingRequiredComponent {
                component_path: "ToBeSignedCertificate",
                components: &[
                    "app_permissions",
                    "cert_issue_permissions",
                    "cert_request_permissions",
                ],
            });
        }
        Ok(self)
    }
}

/// Contains information to identify the certificate holder when necessary.
///
/// # Variants
/// - `LinkageData`: Identifies certificate for revocation in linked certificate CRLs
///   (See sections 5.1.3 and 7.3 for details)
///
/// - `Name`: Identifies non-anonymous certificate holders
///   - Contents are policy-dependent and expected to be human-readable
///
/// - `BinaryId`: Supports non-human-readable identifiers
///
/// - `None`: Indicates certificate does not include an identifier
///
/// # Critical Information Field
/// This is a critical information field as defined in 5.2.6:
/// - An implementation that does not recognize the indicated CHOICE shall
///   reject the signed SPDU as invalid
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum CertificateId {
    LinkageData(LinkageData),
    Name(Hostname),
    #[rasn(size("1..=64"))]
    BinaryId(OctetString),
    None(()),
}

/// Contains information for matching against linkage ID-based CRLs to determine
/// certificate revocation status.
///
/// See sections 5.1.3.4 and 7.3 for detailed usage information.
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct LinkageData {
    #[rasn(identifier = "iCert")]
    pub i_cert: IValue,
    #[rasn(identifier = "linkage-value")]
    pub linkage_value: LinkageValue,
    #[rasn(identifier = "group-linkage-value")]
    pub group_linkage_value: Option<GroupLinkageValue>,
}

/// Indicates permitted permission types in end-entity certificates whose permission
/// chain passes through this `PsidGroupPermissions` field.
///
/// # Variants
/// - `App`: End-entity certificate may contain `appPermissions` field
/// - `Enroll`: End-entity certificate may contain `certRequestPermissions` field
/// # Note
/// BIT STRING {app (0), enrol (1) } (SIZE (8)) (ALL EXCEPT {})
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate, size(8))]
pub struct EndEntityType(pub FixedBitString<8usize>);

/// When initializing `EndEntityType`, use the following constants as the first byte for `FixedBitString<8>`.
impl EndEntityType {
    pub const APP: u8 = 0b1000_0000;
    pub const ENROLL: u8 = 0b0100_0000;
    pub const BOTH: u8 = 0b1100_0000;
}

delegate!(FixedBitString<8>, EndEntityType);

/// Specifies permissions for certificate issuance and requests for a set of PSIDs.
/// See examples in D.5.3 and D.5.4.
///
/// # Fields
/// - `subject_permissions`: PSIDs and SSP Ranges covered
///
/// - `min_chain_length` and `chain_length_range`: Permitted certificate chain length
///   - Chain length: Number of certificates below this one, including end-entity
///   - Permitted length: `min_chain_length` to `min_chain_length + chain_length_range`
///   - Special cases:
///     - `min_chain_length` of 0 not allowed in `certIssuePermissions`
///     - `chain_length_range` of -1 allows any length ≥ `min_chain_length`
///
/// - `ee_type`: Types of certificates/requests this permission authorizes
///   - `app`: Allows chain to end in authorization certificate
///   - `enroll`: Allows chain to end in enrollment certificate
///   - Different `PsidGroupPermissions` instances may have different `ee_type` values
///
/// # Validation Rules
/// - Chain ending in authorization certificate requires `app` in `ee_type`
/// - Chain ending in enrollment certificate requires `enroll` in `ee_type`
/// - Invalid chain if end certificate type doesn't match `ee_type`
#[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct PsidGroupPermissions {
    #[rasn(identifier = "subjectPermissions")]
    pub subject_permissions: SubjectPermissions,
    #[rasn(
        default = "psid_group_permissions_min_chain_length_default",
        identifier = "minChainLength"
    )]
    #[builder(default = psid_group_permissions_min_chain_length_default())]
    pub min_chain_length: Integer,
    #[rasn(
        default = "psid_group_permissions_chain_length_range_default",
        identifier = "chainLengthRange"
    )]
    #[builder(default = psid_group_permissions_chain_length_range_default())]
    pub chain_length_range: Integer,
    #[rasn(
        default = "psid_group_permissions_ee_type_default",
        identifier = "eeType"
    )]
    #[builder(default = psid_group_permissions_ee_type_default())]
    pub ee_type: EndEntityType,
}

fn psid_group_permissions_min_chain_length_default() -> Integer {
    Integer::from(1)
}
fn psid_group_permissions_chain_length_range_default() -> Integer {
    Integer::from(0)
}
fn psid_group_permissions_ee_type_default() -> EndEntityType {
    // First byte holds the bits, container is larger than needed
    EndEntityType(FixedBitString::new([
        EndEntityType::APP,
        0,
        0,
        0,
        0,
        0,
        0,
        0,
    ]))
}

/// This type is used for clarity of definitions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct SequenceOfPsidGroupPermissions(pub SequenceOf<PsidGroupPermissions>);

delegate!(
    SequenceOf<PsidGroupPermissions>,
    SequenceOfPsidGroupPermissions
);

/// Indicates PSIDs and associated SSPs for certificate issuance or request
/// permissions granted by a `PsidGroupPermissions` structure.
///
/// # Variants
/// - `Explicit`: Grants permissions for specific PSIDs and SSP Ranges
/// - `All`: Grants permissions for all PSIDs not covered by other
///   `PsidGroupPermissions` in the same `certIssuePermissions` or
///   `certRequestPermissions` field
///
/// # Critical Information Fields
/// This is a critical information field as defined in 5.2.6:
/// - Implementation must recognize the indicated CHOICE when verifying SPDU
/// - For `Explicit` variant:
///   - Must support at least 8 entries in `PsidSspRange`
///   - Implementation must support specified number of entries
/// - Invalid SPDU (per 4.2.2.3.2) if:
///   - CHOICE is not recognized
///   - Number of entries in `Explicit` variant exceeds implementation support
///
/// Invalid in this context means validity cannot be established.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum SubjectPermissions {
    Explicit(SequenceOfPsidSspRange),
    All(()),
}

/// Contains either verification key or reconstruction value depending on certificate type.
///
/// # Variants
/// - `VerificationKey`: For explicit certificates
///   - Contains public key for verifying holder's signatures
///
/// - `ReconstructionValue`: For implicit certificates
///   - Contains value for recovering public key (per SEC 4 and 5.3.2)
///
/// # Critical Information Field
/// This is a critical information field as defined in 5.2.5:
/// - An implementation that does not recognize the indicated CHOICE when verifying
///   a signed SPDU shall indicate that the SPDU is invalid (per 4.2.2.3.2)
/// - Invalid in this context means its validity cannot be established
///
/// # Canonicalization
/// Subject to canonicalization for operations specified in 6.1.2:
/// - Applies to `PublicVerificationKey` and `EccP256CurvePoint`
/// - `EccP256CurvePoint` must be in compressed form:
///   - Choice must be either `compressed-y-0` or `compressed-y-1`
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
#[non_exhaustive]
pub enum VerificationKeyIndicator {
    VerificationKey(PublicVerificationKey),
    ReconstructionValue(EccP256CurvePoint),
}

/// Represents an individual `AppExtension`.
///
/// Extensions are drawn from the ASN.1 Information Object Set `SetCertExtensions`.
/// Each `AppExtension` is associated with a `CertIssueExtension` and a
/// `CertRequestExtension`, all identified by the same `id` value.
///
/// # Fields
/// - `id`: Identifies the extension type
/// - `content`: Provides the content of the extension
#[derive(AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct AppExtension<T: CertExtType> {
    pub id: ExtId,
    pub content: T::App,
}

/// Contains `CertRequestExtensions` that apply to the certificate holder.
///
/// # Consistency Requirements
/// As specified in 5.2.4.2.3, each `CertRequestExtension` type has specific
/// consistency conditions governing:
/// - Consistency with `AppExtensions` in certificates issued by the holder
/// - Consistency with `CertRequestExtensions` in CA certificates in the holder's chain
///
/// See individual `CertRequestExtension` definitions for their specific
/// consistency conditions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate, size("1.."))]
pub struct SequenceOfCertIssueExtensions(pub SequenceOf<OperatingOrganizationIssueExtension>);

delegate!(
    SequenceOf<OperatingOrganizationIssueExtension>,
    SequenceOfCertIssueExtensions
);

#[derive(AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
pub enum IssuePermissions<T: CertExtType> {
    #[rasn(identifier = "specific")]
    Specific(T::Issue),
    #[rasn(identifier = "all")]
    All(()),
}

/// Represents an individual `CertIssueExtension`.
///
/// Extensions are drawn from the ASN.1 Information Object Set `SetCertExtensions`.
/// Each `CertIssueExtension` is associated with an `AppExtension` and a
/// `CertRequestExtension`, all identified by the same `id` value.
///
/// # Fields
/// - `id`: Identifies the extension type
///
/// - `permissions`: Indicates the permissions
///   - `All`: Certificate is entitled to issue all values of the extension
///   - `Specific`: Specifies which extension values may be issued when `All` doesn't apply
#[derive(Builder, AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct CertIssueExtension<T: CertExtType> {
    pub id: ExtId,
    pub permissions: IssuePermissions<T>,
}
impl<T: CertExtType> CertIssueExtension<T> {
    pub fn new_specific(permissions: T::Issue) -> Self {
        Self {
            id: T::ID,
            permissions: IssuePermissions::Specific(permissions),
        }
    }
    pub fn new_all() -> Self {
        Self {
            id: T::ID,
            permissions: IssuePermissions::All(()),
        }
    }
}

/// Contains `CertRequestExtensions` that apply to the certificate holder.
///
/// # Consistency Requirements
/// As specified in 5.2.4.2.3, each `CertRequestExtension` type has specific
/// consistency conditions governing:
/// - Consistency with `AppExtensions` in certificates issued by the holder
/// - Consistency with `CertRequestExtensions` in CA certificates in the holder's chain
///
/// See individual `CertRequestExtension` definitions for their specific
/// consistency conditions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate, size("1.."))]
pub struct SequenceOfCertRequestExtensions(pub SequenceOf<OperatingOrganizationRequestExtension>);

delegate!(
    SequenceOf<OperatingOrganizationRequestExtension>,
    SequenceOfCertRequestExtensions
);

#[derive(AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
#[rasn(choice, automatic_tags)]
pub enum RequestPermissions<T: CertExtType> {
    #[rasn(identifier = "content")]
    Content(T::Req),
    #[rasn(identifier = "all")]
    All(()),
}

/// Represents an individual `CertRequestExtension`.
///
/// Extensions are drawn from the ASN.1 Information Object Set `SetCertExtensions`.
/// Each `CertRequestExtension` is associated with an `AppExtension` and a
/// `CertRequestExtension`, all identified by the same `id` value.
///
/// # Fields
/// - `id`: Identifies the extension type
///
/// - `permissions`: Indicates the permissions
///   - `All`: Certificate is entitled to issue all values of the extension
///   - `Specific`: Specifies which extension values may be issued when `All` doesn't apply
#[derive(Builder, AsnType, Debug, Encode, Decode, Clone, PartialEq, Eq, Hash)]
#[rasn(automatic_tags)]
pub struct CertRequestExtension<T: CertExtType> {
    pub id: ExtId,
    pub permissions: RequestPermissions<T>,
}

/// AppExtension used to identify an operating organization. Both associated
/// `CertIssueExtension` and `CertRequestExtension` are of type `OperatingOrganizationId`.
///
/// # SPDU Consistency
/// SDEE specification for the SPDU must specify how to determine an OBJECT
/// IDENTIFIER, either by:
/// - Including the full OBJECT IDENTIFIER in the SPDU
/// - Including a RELATIVE-OID with instructions for obtaining full OBJECT IDENTIFIER
///
/// SPDU is consistent if its determined OBJECT IDENTIFIER matches this field's value.
///
/// # Extension Properties
/// - No consistency conditions with corresponding `CertIssueExtension`
/// - Can appear in certificates issued by any CA
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate)]
pub struct OperatingOrganizationId(pub ObjectIdentifier);

delegate!(ObjectIdentifier, OperatingOrganizationId);

#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
pub struct OperatingOrganizationExtension;

impl CertExtType for OperatingOrganizationExtension {
    type App = OperatingOrganizationId;
    type Issue = (); // NULL in ASN.1
    type Req = (); // NULL in ASN.1
    const ID: ExtId = CERT_EXT_ID_OPERATING_ORGANIZATION;
}

pub type OperatingOrganizationAppExtension = AppExtension<OperatingOrganizationExtension>;
pub type OperatingOrganizationIssueExtension = CertIssueExtension<OperatingOrganizationExtension>;
pub type OperatingOrganizationRequestExtension =
    CertRequestExtension<OperatingOrganizationExtension>;

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SetCertExtensionsType {
    OperatingOrganization(OperatingOrganizationExtension),
}

/// Contains `AppExtensions` that apply to the certificate holder.
///
/// # Consistency Requirements
/// As specified in 5.2.4.2.3, each `AppExtension` type has specific
/// consistency conditions governing:
/// - Consistency with SPDUs signed by the holder
/// - Consistency with `CertIssueExtensions` in CA certificates in the holder's chain
/// # Note
/// See individual `AppExtension` definitions for their specific
/// consistency conditions.
#[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
#[rasn(delegate, size("1.."))]
pub struct SequenceOfAppExtensions(pub SequenceOf<OperatingOrganizationAppExtension>);

delegate!(
    SequenceOf<OperatingOrganizationAppExtension>,
    SequenceOfAppExtensions
);

/// --                     IEEE Std 1609.2: CRL Data Types                       --
pub mod crl {
    extern crate alloc;
    use super::base_types::{Psid, Uint8};
    use super::crl_base_types::CrlContents;
    use super::{
        CrlSeries, HeaderInfo, Ieee1609Dot2Content, Ieee1609Dot2Data, SignedData,
        SignedDataPayload, ToBeSignedData,
    };
    use crate::delegate;
    use bon::Builder;
    use rasn::error::InnerSubtypeConstraintError;
    use rasn::prelude::*;

    /// This is the PSID for the CRL application.
    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
    #[rasn(delegate, value("256"))]
    pub struct CrlPsid(Psid);

    impl CrlPsid {
        pub const CRL_PSID: u16 = 256;
        pub fn new() -> Self {
            Self(Psid(Integer::from(Self::CRL_PSID)))
        }
    }
    impl Default for CrlPsid {
        fn default() -> Self {
            Self::new()
        }
    }
    delegate!(Psid, CrlPsid);

    /// This structure is the SPDU used to contain a signed CRL. A valid signed CRL meets the validity criteria of 7.4."]
    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
    #[rasn(delegate)]
    pub struct SecuredCrl(Ieee1609Dot2Data);

    impl InnerSubtypeConstraint for SecuredCrl {
        /// Validates that the `Ieee1609Dot2Data` contains a valid CRL SPDU. Optionally checks interal bytes for `CrlContents` based on the given codec.
        fn validate_and_decode_containing(
            self,
            decode_containing_with: Option<rasn::Codec>,
        ) -> Result<Self, rasn::error::InnerSubtypeConstraintError> {
            let signed_data_content;
            if let Ieee1609Dot2Data {
                content: Ieee1609Dot2Content::SignedData(signed_data),
                ..
            } = &self.0
            {
                signed_data_content = &**signed_data;
            } else {
                return Err(InnerSubtypeConstraintError::MissingRequiredComponent {
                    component_path: "Ieee1609Dot2Data.content",
                    components: &["Ieee1609Dot2Content::SignedData"],
                });
            }
            let crl_psid = CrlPsid::default();
            if matches!(
                signed_data_content,
                SignedData {
                    tbs_data: ToBeSignedData {
                        payload: SignedDataPayload {
                            data: Some(Ieee1609Dot2Data {
                                protocol_version: _,
                                content: Ieee1609Dot2Content::UnsecuredData(_)
                            }),
                            ..
                        },
                        header_info: HeaderInfo {
                            psid: _,
                            generation_time: None,
                            expiry_time: None,
                            generation_location: None,
                            p2pcd_learning_request: None,
                            missing_crl_identifier: None,
                            encryption_key: None,
                            ..
                        },
                    },
                    ..
                }
            ) {
                if let Some(codec) = decode_containing_with {
                    let inner_unsecured_data = signed_data_content
                        .tbs_data
                        .payload
                        .data
                        .as_ref()
                        .and_then(|data| {
                            if let Ieee1609Dot2Data {
                                content: Ieee1609Dot2Content::UnsecuredData(inner_data),
                                ..
                            } = data
                            {
                                Some(inner_data)
                            } else {
                                None
                            }
                        });
                    if let Some(inner_unsecured_data) = inner_unsecured_data {
                        let decoded = codec.decode_from_binary::<CrlContents>(inner_unsecured_data);
                        match decoded {
                            Ok(_) => return Ok(self),
                            Err(err) => {
                                return Err(InnerSubtypeConstraintError::InvalidInnerContaining {
                                    expected: "CrlContents",
                                    err,
                                });
                            }
                        }
                    }
                    // Should be unreachable (UnsecuredData presence already checked)
                    debug_assert!(false);
                }
                Ok(self)
            } else if signed_data_content.tbs_data.header_info.psid == *crl_psid {
                Err(InnerSubtypeConstraintError::InvalidComponentValue {
                    component_path: "Ieee1609Dot2Data.content.signedData.tbsData.headerInfo",
                    component_name: "psid",
                    details: alloc::format!(
                        "Expecting Psid value {} for SecuredCrl",
                        CrlPsid::CRL_PSID
                    ),
                })
            } else {
                Err(InnerSubtypeConstraintError::SubtypeConstraintViolation {
                    component_path: "Ieee1609Dot2Data.content.signedData",
                    details: "SignedData does not contain a valid CRL SPDU",
                })
            }
        }
    }
    /// Service Specific Permissions (SSP) structure for Certificate Revocation List (CRL) signing.
    ///
    /// # Fields
    ///
    /// * `version` - The version number of the SSP. Must be 1 for this version.
    ///
    /// * `associated_craca` - Identifies the relationship between this certificate and
    ///   the Certificate Revocation Authorization CA (CRACA):
    ///   - If `IsCraca`: This certificate is the CRACA certificate and signs CRLs for
    ///     certificates which chain back to this certificate
    ///   - If `IssuerIsCraca`: The issuer of this certificate is the CRACA and this
    ///     certificate may sign CRLs for certificates which chain back to its issuer
    ///
    /// * `crls` - Identifies what type of CRLs may be issued by the certificate holder.
    #[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq)]
    #[rasn(automatic_tags)]
    #[non_exhaustive]
    pub struct CrlSsp {
        #[rasn(value("1"))]
        #[builder(default = CrlSsp::VERSION)]
        #[rasn(identifier = "version")]
        pub version: Uint8,
        #[rasn(identifier = "associatedCraca")]
        pub associated_craca: CracaType,
        #[rasn(identifier = "crls")]
        pub crls: PermissibleCrls,
    }
    impl CrlSsp {
        pub const VERSION: u8 = 1;
    }

    /// Type used to determine the validity of the `crl_craca` field in the `CrlContents` structure.
    ///
    /// # Values
    ///
    /// * `IsCraca` - The `crl_craca` field in `CrlContents` is only valid if it indicates
    ///   the certificate that signs the CRL.
    ///
    /// * `IssuerIsCraca` - The `crl_craca` field in `CrlContents` is only valid if it indicates
    ///   the certificate that issued the certificate that signs the CRL.
    #[derive(AsnType, Debug, Clone, Copy, Decode, Encode, PartialEq, Eq)]
    #[rasn(enumerated)]
    pub enum CracaType {
        IsCraca,
        IssuerIsCraca,
    }

    /// This type is used to determine the validity of the crlSeries field
    /// in the CrlContents structure.
    ///
    /// The crlSeries field in the CrlContents structure is invalid unless that value appears as an entry in the SEQUENCE contained in this field.
    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
    #[rasn(delegate)]
    pub struct PermissibleCrls(pub SequenceOf<CrlSeries>);

    delegate!(SequenceOf<CrlSeries>, PermissibleCrls);
}
/// --           IEEE Std 1609.2: Peer-to-Peer Distribution Data Types           --
pub mod peer2peer {
    use super::Certificate;
    use super::base_types::Uint8;
    use crate::delegate;
    use bon::Builder;
    use rasn::prelude::*;
    /// A Peer-to-Peer PDU structure for IEEE 1609.2 certificate chain responses.
    ///
    /// # Fields
    ///
    /// * `version` - The version number of this structure. Must be 1 for this version
    ///   of the standard.
    ///
    /// * `content` - Contains the certificate chain response:
    ///   - When `CaCerts` variant is used, it contains an array of certificates where:
    ///     - Each certificate is issued by the next certificate in the array
    ///     - The first certificate matches the one indicated by the `p2pcd_learning_request`
    ///       MCI value in the request message (see 8.4.2)
    ///     - The final certificate in the array was issued by a root CA
    #[derive(Builder, AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq)]
    #[rasn(automatic_tags)]
    #[non_exhaustive]
    pub struct Ieee1609Dot2Peer2PeerPDU {
        #[rasn(value("1"))]
        #[builder(default = Ieee1609Dot2Peer2PeerPDU::VERSION)]
        #[rasn(identifier = "version")]
        pub version: Uint8,
        #[rasn(identifier = "content")]
        pub content: Ieee1609Dot2Peer2PeerPduContent,
    }
    impl Ieee1609Dot2Peer2PeerPDU {
        pub const VERSION: u8 = 1;
    }

    /// Content types for Peer-to-Peer PDU.
    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq)]
    #[rasn(choice, automatic_tags)]
    #[non_exhaustive]
    pub enum Ieee1609Dot2Peer2PeerPduContent {
        #[rasn(identifier = "caCerts")]
        CaCerts(CaCertP2pPDU),
    }

    /// This type is used for clarity of definitions.
    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
    #[rasn(delegate)]
    pub struct CaCertP2pPDU(pub SequenceOf<Certificate>);

    delegate!(SequenceOf<Certificate>, CaCertP2pPDU);
}

#[cfg(test)]
mod tests {
    use super::*;
    macro_rules! round_trip {
        ($codec:ident, $typ:ty, $value:expr, $expected:expr) => {{
            let value: $typ = $value;
            let expected: &[u8] = $expected;
            let actual_encoding = rasn::$codec::encode(&value).unwrap();
            // dbg!(&actual_encoding);

            pretty_assertions::assert_eq!(&*actual_encoding, expected);

            let decoded_value = rasn::$codec::decode::<$typ>(&actual_encoding);
            match decoded_value {
                Ok(decoded) => {
                    pretty_assertions::assert_eq!(value, decoded);
                }
                Err(err) => {
                    panic!("{:?}", err);
                }
            }
        }};
    }

    #[test]
    fn test_signed_data_payload() {
        let payload_data = SignedDataPayload::builder()
            .data(
                Ieee1609Dot2Data::builder()
                    .protocol_version(3)
                    .content(Ieee1609Dot2Content::UnsecuredData(
                        OctetString::from("This is a BSM\r\n".as_bytes()).into(),
                    ))
                    .build(),
            )
            .build()
            .unwrap();
        round_trip!(
            coer,
            SignedDataPayload,
            payload_data,
            // 0x40, 0x03, 0x80, 0x0F, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x42, 0x53, 0x4D, 0x0D, 0x0A
            &[
                64, 3, 128, 15, 84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 66, 83, 77, 13, 10
            ]
        );
    }
    #[test]
    fn test_ieee_basic_safety_message() {
        let ieee1609dot2data: Ieee1609Dot2Data = Ieee1609Dot2Data::builder()
            .protocol_version(3)
            .content(Ieee1609Dot2Content::SignedData(Box::new(
                SignedData::builder()
                    .hash_id(HashAlgorithm::Sha256)
                    .tbs_data(
                        ToBeSignedData::builder()
                            .payload(
                                SignedDataPayload::builder()
                                    .data(
                                        Ieee1609Dot2Data::builder()
                                            .protocol_version(3)
                                            .content(Ieee1609Dot2Content::UnsecuredData(
                                                OctetString::from("This is a BSM\r\n".as_bytes())
                                                    .into(),
                                            ))
                                            .build(),
                                    )
                                    .build()
                                    .unwrap(),
                            )
                            .header_info(
                                HeaderInfo::builder()
                                    .psid(Integer::from(32).into())
                                    .generation_time(1_230_066_625_199_609_624.into())
                                    .build(),
                            )
                            .build(),
                    )
                    .signer(SignerIdentifier::Digest(HashedId8(
                        "!\"#$%&'(".as_bytes().try_into().unwrap(),
                    )))
                    .signature(Signature::EcdsaNistP256(
                        EcdsaP256Signature::builder()
                            .r_sig(EccP256CurvePoint::CompressedY0(
                                b"12345678123456781234567812345678"
                                    .to_vec()
                                    .try_into()
                                    .unwrap(),
                            ))
                            .s_sig(
                                b"ABCDEFGHABCDEFGHABCDEFGHABCDEFGH"
                                    .to_vec()
                                    .try_into()
                                    .unwrap(),
                            )
                            .build(),
                    ))
                    .build(),
            )))
            .build();

        round_trip!(
            coer,
            Ieee1609Dot2Data,
            ieee1609dot2data,
            &[
                0x03, 0x81, 0x00, 0x40, 0x03, 0x80, 0x0F, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
                0x20, 0x61, 0x20, 0x42, 0x53, 0x4D, 0x0D, 0x0A, 0x40, 0x01, 0x20, 0x11, 0x12, 0x13,
                0x14, 0x15, 0x16, 0x17, 0x18, 0x80, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
                0x80, 0x82, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34,
                0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32,
                0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
                0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
                0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
            ]
        );
    }
    #[test]
    fn test_bsm_with_cert() {
        round_trip!(
            coer,
            Ieee1609Dot2Data,
            Ieee1609Dot2Data::builder()
                .protocol_version(3)
                .content(Ieee1609Dot2Content::SignedData(Box::new(
                    SignedData::builder()
                        .hash_id(HashAlgorithm::Sha256)
                        .tbs_data(
                            ToBeSignedData::builder()
                                .payload(
                                    SignedDataPayload::builder()
                                        .data(
                                            Ieee1609Dot2Data::builder()
                                                .protocol_version(3)
                                                .content(Ieee1609Dot2Content::UnsecuredData(
                                                    Opaque("This is a BSM\r\n".as_bytes().into())
                                                ))
                                                .build(),
                                        )
                                        .build()
                                        .unwrap(),
                                )
                                .header_info(
                                    HeaderInfo::builder()
                                        .psid(Integer::from(32).into())
                                        .generation_time(1_230_066_625_199_609_624.into())
                                        .build(),
                                )
                                .build()
                        )
                        .signer(SignerIdentifier::Certificate(
                            vec![Certificate::from(
                                ImplicitCertificate::new(
                                    CertificateBase::builder()
                                        .version(3)
                                        .r#type(CertificateType::Implicit)
                                        .issuer(IssuerIdentifier::Sha256AndDigest(HashedId8(
                                            "!\"#$%&'(".as_bytes().try_into().unwrap()
                                        )))
                                        .to_be_signed(
                                            ToBeSignedCertificate::builder()
                                                .id(CertificateId::LinkageData(
                                                    LinkageData::builder()
                                                        .i_cert(IValue::from(100))
                                                        .linkage_value(LinkageValue(
                                                            FixedOctetString::try_from(
                                                                b"123456789".as_slice()
                                                            )
                                                            .unwrap()
                                                        ))
                                                        .group_linkage_value(
                                                            GroupLinkageValue::builder()
                                                                .j_value(
                                                                    b"ABCD"
                                                                        .as_slice()
                                                                        .try_into()
                                                                        .unwrap()
                                                                )
                                                                .value(
                                                                    b"QRSTUVWXY"
                                                                        .as_slice()
                                                                        .try_into()
                                                                        .unwrap()
                                                                )
                                                                .build()
                                                        )
                                                        .build()
                                                ))
                                                .craca_id(HashedId3(
                                                    b"abc".as_slice().try_into().unwrap()
                                                ))
                                                .crl_series(CrlSeries::from(70))
                                                .validity_period(
                                                    ValidityPeriod::builder()
                                                        .start(81_828_384.into())
                                                        .duration(Duration::Hours(169))
                                                        .build()
                                                )
                                                .region(GeographicRegion::IdentifiedRegion(
                                                    vec![
                                                        IdentifiedRegion::CountryOnly(
                                                            UnCountryId::from(124)
                                                        ),
                                                        IdentifiedRegion::CountryOnly(
                                                            UnCountryId::from(484)
                                                        ),
                                                        IdentifiedRegion::CountryOnly(
                                                            UnCountryId::from(840)
                                                        )
                                                    ]
                                                    .into()
                                                ))
                                                .app_permissions(
                                                    vec![
                                                        PsidSsp {
                                                            psid: Integer::from(32).into(),
                                                            ssp: None
                                                        },
                                                        PsidSsp {
                                                            psid: Integer::from(38).into(),
                                                            ssp: None
                                                        }
                                                    ]
                                                    .into()
                                                )
                                                .verify_key_indicator(
                                                    VerificationKeyIndicator::ReconstructionValue(
                                                        EccP256CurvePoint::CompressedY0(
                                                            FixedOctetString::from([
                                                                0x91u8, 0x92, 0x93, 0x94, 0x95,
                                                                0x96, 0x97, 0x98, 0x91, 0x92, 0x93,
                                                                0x94, 0x95, 0x96, 0x97, 0x98, 0x91,
                                                                0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
                                                                0x98, 0x91, 0x92, 0x93, 0x94, 0x95,
                                                                0x96, 0x97, 0x98
                                                            ])
                                                        )
                                                    )
                                                )
                                                .build()
                                                .unwrap()
                                        )
                                        .build()
                                )
                                .unwrap()
                            )]
                            .into()
                        ))
                        .signature(Signature::EcdsaNistP256(
                            EcdsaP256Signature::builder()
                                .r_sig(EccP256CurvePoint::CompressedY0(
                                    b"12345678123456781234567812345678"
                                        .as_slice()
                                        .try_into()
                                        .unwrap()
                                ))
                                .s_sig(
                                    b"ABCDEFGHABCDEFGHABCDEFGHABCDEFGH"
                                        .as_slice()
                                        .try_into()
                                        .unwrap()
                                )
                                .build()
                        ))
                        .build()
                )))
                .build(),
            // Standard-provided verification sample
            // 03 81 00 40 03 80 0F 54 68 69 73 20 69 73 20 61
            // 20 42 53 4D 0D 0A 40 01 20 11 12 13 14 15 16 17
            // 18 81 01 01 00 03 01 80 21 22 23 24 25 26 27 28
            // 50 80 80 00 64 31 32 33 34 35 36 37 38 39 41 42
            // 43 44 51 52 53 54 55 56 57 58 59 61 62 63 00 46
            // 04 E0 9A 20 84 00 A9 83 01 03 80 00 7C 80 01 E4
            // 80 03 48 01 02 00 01 20 00 01 26 81 82 91 92 93
            // 94 95 96 97 98 91 92 93 94 95 96 97 98 91 92 93
            // 94 95 96 97 98 91 92 93 94 95 96 97 98 80 82 31
            // 32 33 34 35 36 37 38 31 32 33 34 35 36 37 38 31
            // 32 33 34 35 36 37 38 31 32 33 34 35 36 37 38 41
            // 42 43 44 45 46 47 48 41 42 43 44 45 46 47 48 41
            // 42 43 44 45 46 47 48 41 42 43 44 45 46 47 48
            //
            // asnc1 output, compiled from standard:
            // 0x03, 0x81, 0x00, 0x40, 0x03, 0x80, 0x0f, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
            // 0x20, 0x61, 0x20, 0x42, 0x53, 0x4d, 0x0d, 0x0a, 0x40, 0x01, 0x20, 0x11, 0x12, 0x13,
            // 0x14, 0x15, 0x16, 0x17, 0x18, 0x81, 0x01, 0x01, 0x00, 0x03, 0x01, 0x80, 0x21, 0x22,
            // 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x50, 0x80, 0x80, 0x00, 0x64, 0x31, 0x32, 0x33,
            // 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x51, 0x52, 0x53, 0x54,
            // 0x55, 0x56, 0x57, 0x58, 0x59, 0x61, 0x62, 0x63, 0x00, 0x46, 0x04, 0xe0, 0x9a, 0x20,
            // 0x84, 0x00, 0xa9, 0x83, 0x01, 0x03, 0x80, 0x00, 0x7c, 0x80, 0x01, 0xe4, 0x80, 0x03,
            // 0x48, 0x01, 0x02, 0x00, 0x01, 0x20, 0x00, 0x01, 0x26, 0x81, 0x82, 0x91, 0x92, 0x93,
            // 0x94, 0x95, 0x96, 0x97, 0x98, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x91,
            // 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
            // 0x98, 0x80, 0x82, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33,
            // 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31,
            // 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
            // 0x48, 0x41, 0x42, 0x43, 0x44,0x45, 0x46, 0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45,
            // 0x46, 0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48
            //
            // NOTE below output is modified to be encoded as the extension version is being used (ToBeSignedCertificate extensions not optional)
            // &[
            //     0x03, 0x81, 0x00, 0x40, 0x03, 0x80, 0x0F, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
            //     0x20, 0x61, 0x20, 0x42, 0x53, 0x4D, 0x0D, 0x0A, 0x40, 0x01, 0x20, 0x11, 0x12, 0x13,
            //     0x14, 0x15, 0x16, 0x17, 0x18, 0x81, 0x01, 0x01, 0x00, 0x03, 0x01, 0x80, 0x21, 0x22,
            //     0x23, 0x24, 0x25, 0x26, 0x27, 0x28, // 0x50, - no extension present version
            //     0xd0, // preamble ends
            //     0x80, 0x80, 0x00, 0x64, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41,
            //     0x42, 0x43, 0x44, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x61, 0x62,
            //     0x63, 0x00, 0x46, 0x04, 0xE0, 0x9A, 0x20, 0x84, 0x00, 0xA9, 0x83, 0x01, 0x03, 0x80,
            //     0x00, 0x7C, 0x80, 0x01, 0xE4, 0x80, 0x03, 0x48, 0x01, 0x02, 0x00, 0x01, 0x20, 0x00,
            //     0x01, 0x26, 0x81, 0x82, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x91, 0x92,
            //     0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
            //     0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
            //     0x98, // extension bitmap starts for TBS cert
            //     0x02, 0x04, 0x70, 0x02, 0x01, 0x00, 0x02, 0x01, 0x00, 0x02, 0x01,
            //     0x00, // ends
            //     0x80, 0x82, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34,
            //     0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32,
            //     0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
            //     0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
            //     0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48
            // ]
            &[
                0x03, 0x81, 0x00, 0x40, 0x03, 0x80, 0x0F, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
                0x20, 0x61, 0x20, 0x42, 0x53, 0x4D, 0x0D, 0x0A, 0x40, 0x01, 0x20, 0x11, 0x12, 0x13,
                0x14, 0x15, 0x16, 0x17, 0x18, 0x81, 0x01, 0x01, 0x00, 0x03, 0x01, 0x80, 0x21, 0x22,
                0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x50, 0x80, 0x80, 0x00, 0x64, 0x31, 0x32, 0x33,
                0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x51, 0x52, 0x53, 0x54,
                0x55, 0x56, 0x57, 0x58, 0x59, 0x61, 0x62, 0x63, 0x00, 0x46, 0x04, 0xE0, 0x9A, 0x20,
                0x84, 0x00, 0xA9, 0x83, 0x01, 0x03, 0x80, 0x00, 0x7C, 0x80, 0x01, 0xE4, 0x80, 0x03,
                0x48, 0x01, 0x02, 0x00, 0x01, 0x20, 0x00, 0x01, 0x26, 0x81, 0x82, 0x91, 0x92, 0x93,
                0x94, 0x95, 0x96, 0x97, 0x98, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x91,
                0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
                0x98, 0x80, 0x82, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33,
                0x34, 0x35, 0x36, 0x37, 0x38, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x31,
                0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
                0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45,
                0x46, 0x47, 0x48, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48
            ]
        );
    }
    #[test]
    fn sample_choice() {
        pub type Uint16 = u16;
        #[derive(AsnType, Debug, Clone, Copy, Decode, Encode, PartialEq, Eq)]
        #[rasn(choice, automatic_tags)]
        pub enum Duration {
            Microseconds(Uint16),
            Milliseconds(Uint16),
            Seconds(Uint16),
            Minutes(Uint16),
            Hours(Uint16),
            SixtyHours(Uint16),
            Years(Uint16),
        }
        let duration = Duration::Hours(10);
        let output = rasn::coer::encode(&duration).unwrap();
        assert_eq!(
            rasn::coer::decode::<Duration>(output.as_slice()).unwrap(),
            duration
        );
    }
}