libkeri 0.1.0

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

pub mod bexter;
pub mod cigar;
pub mod counting;
pub mod dater;
pub mod diger;
pub mod ilker;
pub mod indexing;
pub mod labeler;
pub mod number;
pub mod pather;
pub mod prefixer;
pub mod saider;
pub mod seqner;
pub mod signing;
pub mod tagger;
pub mod texter;
pub mod tholder;
pub mod verfer;

#[derive(Debug, Clone, PartialEq)]
pub struct Versionage {
    pub major: u32,
    pub minor: u32,
}
pub const VERSION: Versionage = Versionage { major: 1, minor: 0 };
#[allow(dead_code)]
pub const VRSN_1_0: Versionage = Versionage { major: 1, minor: 0 };
#[allow(dead_code)]
pub const VRSN_2_0: Versionage = Versionage { major: 2, minor: 0 };

pub const PAD: &str = "_";

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

impl From<String> for Versionage {
    fn from(version_str: String) -> Self {
        // Try to extract version information from the string
        if let Ok(versionage) = Self::parse_version_string(&version_str) {
            return versionage;
        }

        // Default to version 1.0 if string can't be parsed
        Versionage { major: 1, minor: 0 }
    }
}

impl From<&str> for Versionage {
    fn from(version_str: &str) -> Self {
        Self::from(version_str.to_string())
    }
}

impl Versionage {
    pub fn to_vec(&self) -> Vec<u8> {
        let mut vec = Vec::new();
        vec.push(self.major as u8);
        vec.push(self.minor as u8);
        vec
    }

    /// Extracts version information from a KERI version string
    /// Expects string in format like "KERI10JSON000000_" where
    /// the first digit after KERI is the major version and the second is minor
    fn parse_version_string(version_str: &str) -> Result<Self, KERIError> {
        // Ensure the string is long enough to contain version info
        if version_str.len() < 6 {
            return Err(KERIError::VersionError(format!(
                "Version string too short: {}",
                version_str
            )));
        }

        // Check for "KERI" prefix
        if !version_str.starts_with("KERI") {
            return Err(KERIError::VersionError(format!(
                "Invalid version string prefix: {}",
                version_str
            )));
        }

        // Extract the major and minor version numbers (at positions 4 and 5)
        let major_char = version_str.chars().nth(4).unwrap();
        let minor_char = version_str.chars().nth(5).unwrap();

        // Convert from hex character to integer
        let major = u32::from_str_radix(&major_char.to_string(), 16).map_err(|_| {
            KERIError::VersionError(format!("Invalid major version: {}", major_char))
        })?;

        let minor = u32::from_str_radix(&minor_char.to_string(), 16).map_err(|_| {
            KERIError::VersionError(format!("Invalid minor version: {}", minor_char))
        })?;

        Ok(Versionage { major, minor })
    }
}

/// Maps Base64 index to corresponding character
pub static B64_CHR_BY_IDX: Lazy<HashMap<u8, char>> = Lazy::new(|| {
    let mut map = HashMap::new();

    // A-Z: ASCII 65-90, indices 0-25
    for (idx, c) in (65u8..91u8).enumerate() {
        map.insert(idx as u8, c as char);
    }

    // a-z: ASCII 97-122, indices 26-51
    for (idx, c) in (97u8..123u8).enumerate() {
        map.insert((idx + 26) as u8, c as char);
    }

    // 0-9: ASCII 48-57, indices 52-61
    for (idx, c) in (48u8..58u8).enumerate() {
        map.insert((idx + 52) as u8, c as char);
    }

    // Special characters
    map.insert(62, '-');
    map.insert(63, '_');

    map
});

/// Security tiers for secret derivation
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Tiers {
    /// Low security tier
    LOW,
    /// Medium security tier
    MED,
    /// High security tier
    HIGH,
}

impl Tiers {
    /// String value for the tier
    pub const LOW: &'static str = "low";
    /// String value for the tier
    pub const MED: &'static str = "med";
    /// String value for the tier
    pub const HIGH: &'static str = "high";
}

impl From<&str> for Tiers {
    fn from(s: &str) -> Self {
        match s {
            "low" => Tiers::LOW,
            "med" => Tiers::MED,
            "high" => Tiers::HIGH,
            _ => Tiers::LOW, // Default to LOW for unrecognized values
        }
    }
}

impl Display for Tiers {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let str = match self {
            Tiers::LOW => "low",
            Tiers::MED => "med",
            Tiers::HIGH => "high",
        };
        write!(f, "{}", str)
    }
}

/// Maps Base64 character to corresponding index
#[allow(dead_code)]
pub static B64_IDX_BY_CHR: Lazy<HashMap<char, u8>> = Lazy::new(|| {
    let mut map = HashMap::new();

    // Invert the B64_CHR_BY_IDX mapping
    for (&idx, &c) in B64_CHR_BY_IDX.iter() {
        map.insert(c, idx);
    }

    map
});

#[allow(dead_code)]
pub mod cold_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    // Constants for code type values
    pub const ANB64: u8 = 0o0; // Annotated CESR B64
    pub const CTB64: u8 = 0o1; // CountCode Base64
    pub const OPB64: u8 = 0o2; // OpCode Base64
    pub const JSON: u8 = 0o3; // JSON Map Event Start
    pub const MGPK1: u8 = 0o4; // MGPK Fixed Map Event Start
    pub const CBOR: u8 = 0o5; // CBOR Map Event Start
    pub const MGPK2: u8 = 0o6; // MGPK Big 16 or 32 Map Event Start
    pub const CTOPB2: u8 = 0o7; // CountCode or OpCode Base2

    // Map of code types by value
    pub static MAP: Lazy<HashMap<&'static str, u8>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("ANB64", ANB64);
        map.insert("CTB64", CTB64);
        map.insert("OPB64", OPB64);
        map.insert("JSON,", JSON);
        map.insert("MGPK1", MGPK1);
        map.insert("CBOR,", CBOR);
        map.insert("MGPK2", MGPK2);
        map.insert("CTOPB2", CTOPB2);
        map
    });

    // Tuple of code values only
    pub static TUPLE: Lazy<Vec<u8>> =
        Lazy::new(|| vec![ANB64, CTB64, OPB64, JSON, MGPK1, CBOR, MGPK2, CTOPB2]);
}

#[derive(Debug, Clone, PartialEq)]
pub struct Coldage {
    pub msg: &'static str,
    pub txt: &'static str,
    pub bny: &'static str,
    pub ano: &'static str,
}

impl Coldage {
    pub fn new(msg: &'static str, txt: &'static str, bny: &'static str, ano: &'static str) -> Self {
        Self { msg, txt, bny, ano }
    }
}

impl Default for Coldage {
    fn default() -> Self {
        Self {
            msg: "msg",
            txt: "txt",
            bny: "bny",
            ano: "ano",
        }
    }
}

impl Display for Coldage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Coldage(msg='{}', txt='{}', bny='{}', ano='{}')",
            self.msg, self.txt, self.bny, self.ano
        )
    }
}

// Define a constant similar to Colds in Python
pub const COLDS: Coldage = Coldage {
    msg: "msg",
    txt: "txt",
    bny: "bny",
    ano: "ano",
};

/// Returns status string of cold start of stream ims bytearray by looking
/// at first triplet of first byte to determine if message or counter code
/// and if counter code whether Base64 or Base2 representation
///
/// First three bits:
/// 0o0 = 000 annotated cesr
/// 0o1 = 001 cntcode B64
/// 0o2 = 010 opcode B64
/// 0o3 = 011 json
/// 0o4 = 100 mgpk
/// 0o5 = 101 cbor
/// 0o6 = 110 mgpk
/// 0o7 = 111 cntcode B2 or opcode B2
///
/// counter B64 in (0o1, 0o2) return 'txt'
/// counter B2 in (0o7)  return 'bny'
/// event in (0o3, 0o4, 0o5, 0o6)  return 'msg'
/// annotated in (0o0)  return 'ano'
pub fn sniff(ims: &[u8]) -> Result<&'static str, MatterError> {
    if ims.is_empty() {
        return Err(MatterError::ShortageError("Need more bytes.".to_string()));
    }

    // Extract the first 3 bits (tritet) by shifting right 5 bits
    let tritet = ims[0] >> 5;

    if tritet == cold_dex::JSON
        || tritet == cold_dex::MGPK1
        || tritet == cold_dex::CBOR
        || tritet == cold_dex::MGPK2
    {
        return Ok(COLDS.msg);
    }

    if tritet == cold_dex::CTB64 || tritet == cold_dex::OPB64 {
        return Ok(COLDS.txt);
    }

    if tritet == cold_dex::CTOPB2 {
        return Ok(COLDS.bny);
    }

    if tritet == cold_dex::ANB64 {
        return Ok(COLDS.ano);
    }

    Err(MatterError::ColdStartError(format!(
        "Unexpected tritet={} at stream start.",
        tritet
    )))
}

#[allow(dead_code)]
pub mod trait_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// EstOnly - Only allow establishment events. Inception only.
    pub const EST_ONLY: &str = "EO";

    /// DoNotDelegate - Do not allow delegated identifiers. Inception only.
    pub const DO_NOT_DELEGATE: &str = "DND";

    /// RegistrarBackers - Registrar backer provided in Registrar seal in this event
    pub const REGISTRAR_BACKERS: &str = "RB";

    /// NoBackers - Do not allow any (registrar backers). Inception and Rotation in v2.
    pub const NO_BACKERS: &str = "NB";

    /// NoRegistrarBackers - Do not allow any registrar backers. Inception and Rotation.
    pub const NO_REGISTRAR_BACKERS: &str = "NRB";

    /// DelegateIsDelegator - Treat delegate AIDs same as their delegator. Inception only
    pub const DELEGATE_IS_DELEGATOR: &str = "DID";

    // Create a HashMap from name to value
    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("EST_ONLY", EST_ONLY);
        map.insert("DO_NOT_DELEGATE", DO_NOT_DELEGATE);
        map.insert("REGISTRAR_BACKERS", REGISTRAR_BACKERS);
        map.insert("NO_BACKERS", NO_BACKERS);
        map.insert("NO_REGISTRAR_BACKERS", NO_REGISTRAR_BACKERS);
        map.insert("DELEGATE_IS_DELEGATOR", DELEGATE_IS_DELEGATOR);

        map
    });

    pub static TUPLE: [&'static str; 6] = [
        EST_ONLY,
        DO_NOT_DELEGATE,
        REGISTRAR_BACKERS,
        NO_BACKERS,
        NO_REGISTRAR_BACKERS,
        DELEGATE_IS_DELEGATOR,
    ];
}

/// Various derivation codes for Matter types
#[allow(dead_code)]
pub mod mtr_dex {
    pub const ED25519_SEED: &str = "A"; // Ed25519 256 bit random seed for private key
    pub const ED25519N: &str = "B"; // Ed25519 verification key non-transferable, basic derivation
    pub const X25519: &str = "C"; // X25519 public encryption key, may be converted from Ed25519 or Ed25519N
    pub const ED25519: &str = "D"; // Ed25519 verification key basic derivation
    pub const BLAKE3_256: &str = "E"; // Blake3 256 bit digest self-addressing derivation
    pub const BLAKE2B_256: &str = "F"; // Blake2b 256 bit digest self-addressing derivation
    pub const BLAKE2S_256: &str = "G"; // Blake2s 256 bit digest self-addressing derivation
    pub const SHA3_256: &str = "H"; // SHA3 256 bit digest self-addressing derivation
    pub const SHA2_256: &str = "I"; // SHA2 256 bit digest self-addressing derivation
    pub const ECDSA_256K1_SEED: &str = "J"; // ECDSA secp256k1 256 bit random Seed for private key
    pub const ED448_SEED: &str = "K"; // Ed448 448 bit random Seed for private key
    pub const X448: &str = "L"; // X448 public encryption key, converted from Ed448
    pub const SHORT: &str = "M"; // Short 2 byte b2 number
    pub const BIG: &str = "N"; // Big 8 byte b2 number
    pub const X25519_PRIVATE: &str = "O"; // X25519 private decryption key/seed, may be converted from Ed25519
    pub const X25519_CIPHER_SEED: &str = "P"; // X25519 sealed box 124 char qb64 Cipher of 44 char qb64 Seed
    pub const ECDSA_256R1_SEED: &str = "Q"; // ECDSA secp256r1 256 bit random Seed for private key
    pub const TALL: &str = "R"; // Tall 5 byte b2 number
    pub const LARGE: &str = "S"; // Large 11 byte b2 number
    pub const GREAT: &str = "T"; // Great 14 byte b2 number
    pub const VAST: &str = "U"; // Vast 17 byte b2 number
    pub const LABEL1: &str = "V"; // Label1 1 bytes for label lead size 1
    pub const LABEL2: &str = "W"; // Label2 2 bytes for label lead size 0
    pub const TAG3: &str = "X"; // Tag3  3 B64 encoded chars for special values
    pub const TAG7: &str = "Y"; // Tag7  7 B64 encoded chars for special values
    pub const BLIND: &str = "Z"; // Blinding factor 256 bits, Cryptographic strength deterministically generated from random salt
    pub const SALT_128: &str = "0A"; // random salt/seed/nonce/private key or number of length 128 bits (Huge)
    pub const ED25519_SIG: &str = "0B"; // Ed25519 signature
    pub const ECDSA_256K1_SIG: &str = "0C"; // ECDSA secp256k1 signature
    pub const BLAKE3_512: &str = "0D"; // Blake3 512 bit digest self-addressing derivation
    pub const BLAKE2B_512: &str = "0E"; // Blake2b 512 bit digest self-addressing derivation
    pub const SHA3_512: &str = "0F"; // SHA3 512 bit digest self-addressing derivation
    pub const SHA2_512: &str = "0G"; // SHA2 512 bit digest self-addressing derivation
    pub const LONG: &str = "0H"; // Long 4 byte b2 number
    pub const ECDSA_256R1_SIG: &str = "0I"; // ECDSA secp256r1 signature
    pub const TAG1: &str = "0J"; // Tag1 1 B64 encoded char + 1 prepad for special values
    pub const TAG2: &str = "0K"; // Tag2 2 B64 encoded chars for for special values
    pub const TAG5: &str = "0L"; // Tag5 5 B64 encoded chars + 1 prepad for special values
    pub const TAG6: &str = "0M"; // Tag6 6 B64 encoded chars for special values
    pub const TAG9: &str = "0N"; // Tag9 9 B64 encoded chars + 1 prepad for special values
    pub const TAG10: &str = "0O"; // Tag10 10 B64 encoded chars for special values
    pub const GRAM_HEAD_NECK: &str = "0P"; // GramHeadNeck 32 B64 chars memogram head with neck
    pub const GRAM_HEAD: &str = "0Q"; // GramHead 28 B64 chars memogram head only
    pub const GRAM_HEAD_AID_NECK: &str = "0R"; // GramHeadAIDNeck 76 B64 chars memogram head with AID and neck
    pub const GRAM_HEAD_AID: &str = "0S"; // GramHeadAID 72 B64 chars memogram head with AID only
    pub const ECDSA_256K1N: &str = "1AAA"; // ECDSA secp256k1 verification key non-transferable, basic derivation
    pub const ECDSA_256K1: &str = "1AAB"; // ECDSA public verification or encryption key, basic derivation
    pub const ED448N: &str = "1AAC"; // Ed448 non-transferable prefix public signing verification key. Basic derivation
    pub const ED448: &str = "1AAD"; // Ed448 public signing verification key. Basic derivation
    pub const ED448_SIG: &str = "1AAE"; // Ed448 signature. Self-signing derivation
    pub const TAG4: &str = "1AAF"; // Tag4 4 B64 encoded chars for special values
    pub const DATE_TIME: &str = "1AAG"; // Base64 custom encoded 32 char ISO-8601 DateTime
    pub const X25519_CIPHER_SALT: &str = "1AAH"; // X25519 sealed box 100 char qb64 Cipher of 24 char qb64 Salt
    pub const ECDSA_256R1N: &str = "1AAI"; // ECDSA secp256r1 verification key non-transferable, basic derivation
    pub const ECDSA_256R1: &str = "1AAJ"; // ECDSA secp256r1 verification or encryption key, basic derivation
    pub const NULL: &str = "1AAK"; // Null None or empty value
    pub const NO: &str = "1AAL"; // No Falsey Boolean value
    pub const YES: &str = "1AAM"; // Yes Truthy Boolean value
    pub const TAG8: &str = "1AAN"; // Tag8 8 B64 encoded chars for special values
    pub const TBD0S: &str = "1__-"; // Testing purposes only, fixed special values with non-empty raw lead size 0
    pub const TBD0: &str = "1___"; // Testing purposes only, fixed with lead size 0
    pub const TBD1S: &str = "2__-"; // Testing purposes only, fixed special values with non-empty raw lead size 1
    pub const TBD1: &str = "2___"; // Testing purposes only, fixed with lead size 1
    pub const TBD2S: &str = "3__-"; // Testing purposes only, fixed special values with non-empty raw lead size 2
    pub const TBD2: &str = "3___"; // Testing purposes only, fixed with lead size 2
    pub const STR_B64_L0: &str = "4A"; // String Base64 only lead size 0
    pub const STR_B64_L1: &str = "5A"; // String Base64 only lead size 1
    pub const STR_B64_L2: &str = "6A"; // String Base64 only lead size 2
    pub const STR_B64_BIG_L0: &str = "7AAA"; // String Base64 only big lead size 0
    pub const STR_B64_BIG_L1: &str = "8AAA"; // String Base64 only big lead size 1
    pub const STR_B64_BIG_L2: &str = "9AAA"; // String Base64 only big lead size 2
    pub const BYTES_L0: &str = "4B"; // Byte String lead size 0
    pub const BYTES_L1: &str = "5B"; // Byte String lead size 1
    pub const BYTES_L2: &str = "6B"; // Byte String lead size 2
    pub const BYTES_BIG_L0: &str = "7AAB"; // Byte String big lead size 0
    pub const BYTES_BIG_L1: &str = "8AAB"; // Byte String big lead size 1
    pub const BYTES_BIG_L2: &str = "9AAB"; // Byte String big lead size 2
    pub const X25519_CIPHER_L0: &str = "4C"; // X25519 sealed box cipher bytes of sniffable stream plaintext lead size 0
    pub const X25519_CIPHER_L1: &str = "5C"; // X25519 sealed box cipher bytes of sniffable stream plaintext lead size 1
    pub const X25519_CIPHER_L2: &str = "6C"; // X25519 sealed box cipher bytes of sniffable stream plaintext lead size 2
    pub const X25519_CIPHER_BIG_L0: &str = "7AAC"; // X25519 sealed box cipher bytes of sniffable stream plaintext big lead size 0
    pub const X25519_CIPHER_BIG_L1: &str = "8AAC"; // X25519 sealed box cipher bytes of sniffable stream plaintext big lead size 1
    pub const X25519_CIPHER_BIG_L2: &str = "9AAC"; // X25519 sealed box cipher bytes of sniffable stream plaintext big lead size 2
    pub const X25519_CIPHER_QB64_L0: &str = "4D"; // X25519 sealed box cipher bytes of QB64 plaintext lead size 0
    pub const X25519_CIPHER_QB64_L1: &str = "5D"; // X25519 sealed box cipher bytes of QB64 plaintext lead size 1
    pub const X25519_CIPHER_QB64_L2: &str = "6D"; // X25519 sealed box cipher bytes of QB64 plaintext lead size 2
    pub const X25519_CIPHER_QB64_BIG_L0: &str = "7AAD"; // X25519 sealed box cipher bytes of QB64 plaintext big lead size 0
    pub const X25519_CIPHER_QB64_BIG_L1: &str = "8AAD"; // X25519 sealed box cipher bytes of QB64 plaintext big lead size 1
    pub const X25519_CIPHER_QB64_BIG_L2: &str = "9AAD"; // X25519 sealed box cipher bytes of QB64 plaintext big lead size 2
    pub const X25519_CIPHER_QB2_L0: &str = "4E"; // X25519 sealed box cipher bytes of QB2 plaintext lead size 0
    pub const X25519_CIPHER_QB2_L1: &str = "5E"; // X25519 sealed box cipher bytes of QB2 plaintext lead size 1
    pub const X25519_CIPHER_QB2_L2: &str = "6E"; // X25519 sealed box cipher bytes of QB2 plaintext lead size 2
    pub const X25519_CIPHER_QB2_BIG_L0: &str = "7AAE"; // X25519 sealed box cipher bytes of QB2 plaintext big lead size 0
    pub const X25519_CIPHER_QB2_BIG_L1: &str = "8AAE"; // X25519 sealed box cipher bytes of QB2 plaintext big lead size 1
    pub const X25519_CIPHER_QB2_BIG_L2: &str = "9AAE"; // X25519 sealed box cipher bytes of QB2 plaintext big lead size 2
}

// Create a HashMap from name to value
#[allow(dead_code)]
pub static MTR_DEX_MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
    let mut map = HashMap::new();
    map.insert("ED25519_SEED", mtr_dex::ED25519_SEED);
    map.insert("ED25519N", mtr_dex::ED25519N);
    map.insert("X25519", mtr_dex::X25519);
    map.insert("ED25519", mtr_dex::ED25519);
    map.insert("BLAKE3_256", mtr_dex::BLAKE3_256);
    map.insert("BLAKE2B_256", mtr_dex::BLAKE2B_256);
    map.insert("BLAKE2S_256", mtr_dex::BLAKE2S_256);
    map.insert("SHA3_256", mtr_dex::SHA3_256);
    map.insert("SHA2_256", mtr_dex::SHA2_256);
    map.insert("ECDSA_256K1_SEED", mtr_dex::ECDSA_256K1_SEED);
    map.insert("ED448_SEED", mtr_dex::ED448_SEED);
    map.insert("X448", mtr_dex::X448);
    map.insert("SHORT", mtr_dex::SHORT);
    map.insert("BIG", mtr_dex::BIG);
    map.insert("X25519_PRIVATE", mtr_dex::X25519_PRIVATE);
    map.insert("X25519_CIPHER_SEED", mtr_dex::X25519_CIPHER_SEED);
    map.insert("ECDSA_256R1_SEED", mtr_dex::ECDSA_256R1_SEED);
    map.insert("TALL", mtr_dex::TALL);
    map.insert("LARGE", mtr_dex::LARGE);
    map.insert("GREAT", mtr_dex::GREAT);
    map.insert("VAST", mtr_dex::VAST);
    map.insert("LABEL1", mtr_dex::LABEL1);
    map.insert("LABEL2", mtr_dex::LABEL2);
    map.insert("TAG3", mtr_dex::TAG3);
    map.insert("TAG7", mtr_dex::TAG7);
    map.insert("BLIND", mtr_dex::BLIND);
    map.insert("SALT_128", mtr_dex::SALT_128);
    map.insert("ED25519_SIG", mtr_dex::ED25519_SIG);
    map.insert("ECDSA_256K1_SIG", mtr_dex::ECDSA_256K1_SIG);
    map.insert("BLAKE3_512", mtr_dex::BLAKE3_512);
    map.insert("BLAKE2B_512", mtr_dex::BLAKE2B_512);
    map.insert("SHA3_512", mtr_dex::SHA3_512);
    map.insert("SHA2_512", mtr_dex::SHA2_512);
    map.insert("LONG", mtr_dex::LONG);
    map.insert("ECDSA_256R1_SIG", mtr_dex::ECDSA_256R1_SIG);
    map.insert("TAG1", mtr_dex::TAG1);
    map.insert("TAG2", mtr_dex::TAG2);
    map.insert("TAG5", mtr_dex::TAG5);
    map.insert("TAG6", mtr_dex::TAG6);
    map.insert("TAG9", mtr_dex::TAG9);
    map.insert("TAG10", mtr_dex::TAG10);
    map.insert("GRAM_HEAD_NECK", mtr_dex::GRAM_HEAD_NECK);
    map.insert("GRAM_HEAD", mtr_dex::GRAM_HEAD);
    map.insert("GRAM_HEAD_AID_NECK", mtr_dex::GRAM_HEAD_AID_NECK);
    map.insert("GRAM_HEAD_AID", mtr_dex::GRAM_HEAD_AID);
    map.insert("ECDSA_256K1N", mtr_dex::ECDSA_256K1N);
    map.insert("ECDSA_256K1", mtr_dex::ECDSA_256K1);
    map.insert("ED448N", mtr_dex::ED448N);
    map.insert("ED448", mtr_dex::ED448);
    map.insert("ED448_SIG", mtr_dex::ED448_SIG);
    map.insert("TAG4", mtr_dex::TAG4);
    map.insert("DATE_TIME", mtr_dex::DATE_TIME);
    map.insert("X25519_CIPHER_SALT", mtr_dex::X25519_CIPHER_SALT);
    map.insert("ECDSA_256R1N", mtr_dex::ECDSA_256R1N);
    map.insert("ECDSA_256R1", mtr_dex::ECDSA_256R1);
    map.insert("NULL", mtr_dex::NULL);
    map.insert("NO", mtr_dex::NO);
    map.insert("YES", mtr_dex::YES);
    map.insert("TAG8", mtr_dex::TAG8);
    map.insert("TBD0S", mtr_dex::TBD0S);
    map.insert("TBD0", mtr_dex::TBD0);
    map.insert("TBD1S", mtr_dex::TBD1S);
    map.insert("TBD1", mtr_dex::TBD1);
    map.insert("TBD2S", mtr_dex::TBD2S);
    map.insert("TBD2", mtr_dex::TBD2);
    map.insert("STR_B64_L0", mtr_dex::STR_B64_L0);
    map.insert("STR_B64_L1", mtr_dex::STR_B64_L1);
    map.insert("STR_B64_L2", mtr_dex::STR_B64_L2);
    map.insert("STR_B64_BIG_L0", mtr_dex::STR_B64_BIG_L0);
    map.insert("STR_B64_BIG_L1", mtr_dex::STR_B64_BIG_L1);
    map.insert("STR_B64_BIG_L2", mtr_dex::STR_B64_BIG_L2);
    map.insert("BYTES_L0", mtr_dex::BYTES_L0);
    map.insert("BYTES_L1", mtr_dex::BYTES_L1);
    map.insert("BYTES_L2", mtr_dex::BYTES_L2);
    map.insert("BYTES_BIG_L0", mtr_dex::BYTES_BIG_L0);
    map.insert("BYTES_BIG_L1", mtr_dex::BYTES_BIG_L1);
    map.insert("BYTES_BIG_L2", mtr_dex::BYTES_BIG_L2);
    map.insert("X25519_CIPHER_L0", mtr_dex::X25519_CIPHER_L0);
    map.insert("X25519_CIPHER_L1", mtr_dex::X25519_CIPHER_L1);
    map.insert("X25519_CIPHER_L2", mtr_dex::X25519_CIPHER_L2);
    map.insert("X25519_CIPHER_BIG_L0", mtr_dex::X25519_CIPHER_BIG_L0);
    map.insert("X25519_CIPHER_BIG_L1", mtr_dex::X25519_CIPHER_BIG_L1);
    map.insert("X25519_CIPHER_BIG_L2", mtr_dex::X25519_CIPHER_BIG_L2);
    map.insert("X25519_CIPHER_QB64_L0", mtr_dex::X25519_CIPHER_QB64_L0);
    map.insert("X25519_CIPHER_QB64_L1", mtr_dex::X25519_CIPHER_QB64_L1);
    map.insert("X25519_CIPHER_QB64_L2", mtr_dex::X25519_CIPHER_QB64_L2);
    map.insert(
        "X25519_CIPHER_QB64_BIG_L0",
        mtr_dex::X25519_CIPHER_QB64_BIG_L0,
    );
    map.insert(
        "X25519_CIPHER_QB64_BIG_L1",
        mtr_dex::X25519_CIPHER_QB64_BIG_L1,
    );
    map.insert(
        "X25519_CIPHER_QB64_BIG_L2",
        mtr_dex::X25519_CIPHER_QB64_BIG_L2,
    );
    map.insert("X25519_CIPHER_QB2_L0", mtr_dex::X25519_CIPHER_QB2_L0);
    map.insert("X25519_CIPHER_QB2_L1", mtr_dex::X25519_CIPHER_QB2_L1);
    map.insert("X25519_CIPHER_QB2_L2", mtr_dex::X25519_CIPHER_QB2_L2);
    map.insert(
        "X25519_CIPHER_QB2_BIG_L0",
        mtr_dex::X25519_CIPHER_QB2_BIG_L0,
    );
    map.insert(
        "X25519_CIPHER_QB2_BIG_L1",
        mtr_dex::X25519_CIPHER_QB2_BIG_L1,
    );
    map.insert(
        "X25519_CIPHER_QB2_BIG_L2",
        mtr_dex::X25519_CIPHER_QB2_BIG_L2,
    );
    map
});

#[allow(dead_code)]
pub mod small_vrz_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    pub const LEAD0: &str = "4"; // First Selector Character for all ls == 0 codes
    pub const LEAD1: &str = "5"; // First Selector Character for all ls == 1 codes
    pub const LEAD2: &str = "6"; // First Selector Character for all ls == 2 codes

    // Create a HashMap from name to value
    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("LEAD0", LEAD0);
        map.insert("LEAD1", LEAD1);
        map.insert("LEAD2", LEAD2);
        map
    });

    pub static TUPLE: [&'static str; 3] = [LEAD0, LEAD1, LEAD2];
}

#[allow(dead_code)]
pub mod large_vrz_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    pub const LEAD0_BIG: &str = "7"; // First Selector Character for all ls == 0 codes
    pub const LEAD1_BIG: &str = "8"; // First Selector Character for all ls == 1 codes
    pub const LEAD2_BIG: &str = "9"; // First Selector Character for all ls == 2 codes

    // Create a HashMap from name to value for large_vrz_dex
    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("LEAD0_BIG", LEAD0_BIG);
        map.insert("LEAD1_BIG", LEAD1_BIG);
        map.insert("LEAD2_BIG", LEAD2_BIG);
        map
    });

    pub static TUPLE: [&'static str; 3] = [LEAD0_BIG, LEAD1_BIG, LEAD2_BIG];
}

/// BextCodex is codex of all variable sized Base64 Text (Bext) derivation codes.
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod bex_dex {
    /// String Base64 Only Leader Size 0
    pub const STR_B64_L0: &str = "4A";

    /// String Base64 Only Leader Size 1
    pub const STR_B64_L1: &str = "5A";

    /// String Base64 Only Leader Size 2
    pub const STR_B64_L2: &str = "6A";

    /// String Base64 Only Big Leader Size 0
    pub const STR_B64_BIG_L0: &str = "7AAA";

    /// String Base64 Only Big Leader Size 1
    pub const STR_B64_BIG_L1: &str = "8AAA";

    /// String Base64 Only Big Leader Size 2
    pub const STR_B64_BIG_L2: &str = "9AAA";

    /// Map of code to size of code (in characters) in Base64
    pub const MAP: once_cell::sync::Lazy<std::collections::HashMap<&'static str, usize>> =
        once_cell::sync::Lazy::new(|| {
            let mut map = std::collections::HashMap::new();
            map.insert(STR_B64_L0, 2);
            map.insert(STR_B64_L1, 2);
            map.insert(STR_B64_L2, 2);
            map.insert(STR_B64_BIG_L0, 4);
            map.insert(STR_B64_BIG_L1, 4);
            map.insert(STR_B64_BIG_L2, 4);
            map
        });

    /// Tuple of string constants in order of definition
    pub const TUPLE: &[&str] = &[
        STR_B64_L0,
        STR_B64_L1,
        STR_B64_L2,
        STR_B64_BIG_L0,
        STR_B64_BIG_L1,
        STR_B64_BIG_L2,
    ];
}

/// TextCodex is codex of all variable sized byte string (Text) derivation codes.
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod tex_dex {
    /// Byte String lead size 0
    pub const BYTES_L0: &str = "4B";

    /// Byte String lead size 1
    pub const BYTES_L1: &str = "5B";

    /// Byte String lead size 2
    pub const BYTES_L2: &str = "6B";

    /// Byte String big lead size 0
    pub const BYTES_BIG_L0: &str = "7AAB";

    /// Byte String big lead size 1
    pub const BYTES_BIG_L1: &str = "8AAB";

    /// Byte String big lead size 2
    pub const BYTES_BIG_L2: &str = "9AAB";

    /// Map of code to size of code (in characters) in Base64
    pub const MAP: once_cell::sync::Lazy<std::collections::HashMap<&'static str, usize>> =
        once_cell::sync::Lazy::new(|| {
            let mut map = std::collections::HashMap::new();
            map.insert(BYTES_L0, 2);
            map.insert(BYTES_L1, 2);
            map.insert(BYTES_L2, 2);
            map.insert(BYTES_BIG_L0, 4);
            map.insert(BYTES_BIG_L1, 4);
            map.insert(BYTES_BIG_L2, 4);
            map
        });

    /// Tuple of string constants in order of definition
    pub const TUPLE: &[&str] = &[
        BYTES_L0,
        BYTES_L1,
        BYTES_L2,
        BYTES_BIG_L0,
        BYTES_BIG_L1,
        BYTES_BIG_L2,
    ];
}

/// DigCodex is codex of all digest derivation codes. This is needed to ensure
/// delegated inception using a self-addressing derivation i.e. digest derivation
/// code.
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod dig_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// Blake3 256 bit digest self-addressing derivation
    pub const BLAKE3_256: &str = "E";

    /// Blake2b 256 bit digest self-addressing derivation
    pub const BLAKE2B_256: &str = "F";

    /// Blake2s 256 bit digest self-addressing derivation
    pub const BLAKE2S_256: &str = "G";

    /// SHA3 256 bit digest self-addressing derivation
    pub const SHA3_256: &str = "H";

    /// SHA2 256 bit digest self-addressing derivation
    pub const SHA2_256: &str = "I";

    /// Blake3 512 bit digest self-addressing derivation
    pub const BLAKE3_512: &str = "0D";

    /// Blake2b 512 bit digest self-addressing derivation
    pub const BLAKE2B_512: &str = "0E";

    /// SHA3 512 bit digest self-addressing derivation
    pub const SHA3_512: &str = "0F";

    /// SHA2 512 bit digest self-addressing derivation
    pub const SHA2_512: &str = "0G";

    #[allow(dead_code)]
    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("BLAKE3_256", BLAKE3_256);
        map.insert("BLAKE2B_256", BLAKE2B_256);
        map.insert("BLAKE2S_256", BLAKE2S_256);
        map.insert("SHA3_256", SHA3_256);
        map.insert("SHA2_256", SHA2_256);
        map.insert("BLAKE3_512", BLAKE3_512);
        map.insert("BLAKE2B_512", BLAKE2B_512);
        map.insert("SHA3_512", SHA3_512);
        map.insert("SHA2_512", SHA2_512);
        map
    });

    pub static TUPLE: [&'static str; 9] = [
        BLAKE3_256,
        BLAKE2B_256,
        BLAKE2S_256,
        SHA3_256,
        SHA2_256,
        BLAKE3_512,
        BLAKE2B_512,
        SHA3_512,
        SHA2_512,
    ];
}

/// NumCodex is codex of Base64 derivation codes for compactly representing
/// numbers across a wide rage of sizes.
///
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod num_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// Short 2 byte b2 number
    pub const SHORT: &str = "M";

    /// Long 4 byte b2 number
    pub const LONG: &str = "0H";

    /// Tall 5 byte b2 number
    pub const TALL: &str = "R";

    /// Big 8 byte b2 number
    pub const BIG: &str = "N";

    /// Large 11 byte b2 number
    pub const LARGE: &str = "S";

    /// Great 14 byte b2 number
    pub const GREAT: &str = "T";

    /// Huge 16 byte b2 number (same as Salt_128)
    pub const HUGE: &str = "0A";

    /// Vast 17 byte b2 number
    pub const VAST: &str = "U";

    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert(SHORT, "SHORT");
        map.insert(LONG, "LONG");
        map.insert(TALL, "TALL");
        map.insert(BIG, "BIG");
        map.insert(LARGE, "LARGE");
        map.insert(GREAT, "GREAT");
        map.insert(HUGE, "HUGE");
        map.insert(VAST, "VAST");
        map
    });

    pub static TUPLE: [&'static str; 8] = [SHORT, LONG, TALL, BIG, LARGE, GREAT, HUGE, VAST];
}

/// TagCodex is codex of Base64 derivation codes for compactly representing
/// various small Base64 tag values as special code soft part values.
///
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod tag_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// 1 B64 char tag with 1 pre pad
    pub const TAG1: &str = "0J";

    /// 2 B64 char tag
    pub const TAG2: &str = "0K";

    /// 3 B64 char tag
    pub const TAG3: &str = "X";

    /// 4 B64 char tag
    pub const TAG4: &str = "1AAF";

    /// 5 B64 char tag with 1 pre pad
    pub const TAG5: &str = "0L";

    /// 6 B64 char tag
    pub const TAG6: &str = "0M";

    /// 7 B64 char tag
    pub const TAG7: &str = "Y";

    /// 8 B64 char tag
    pub const TAG8: &str = "1AAN";

    /// 9 B64 char tag with 1 pre pad
    pub const TAG9: &str = "0N";

    /// 10 B64 char tag
    pub const TAG10: &str = "0O";

    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("TAG1", TAG1);
        map.insert("TAG2", TAG2);
        map.insert("TAG3", TAG3);
        map.insert("TAG4", TAG4);
        map.insert("TAG5", TAG5);
        map.insert("TAG6", TAG6);
        map.insert("TAG7", TAG7);
        map.insert("TAG8", TAG8);
        map.insert("TAG9", TAG9);
        map.insert("TAG10", TAG10);
        map
    });
}

/// LabelCodex is codex of.
///
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod label_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// 1 B64 char tag with 1 pre pad
    pub const TAG1: &str = "0J";

    /// 2 B64 char tag
    pub const TAG2: &str = "0K";

    /// 3 B64 char tag
    pub const TAG3: &str = "X";

    /// 4 B64 char tag
    pub const TAG4: &str = "1AAF";

    /// 5 B64 char tag with 1 pre pad
    pub const TAG5: &str = "0L";

    /// 6 B64 char tag
    pub const TAG6: &str = "0M";

    /// 7 B64 char tag
    pub const TAG7: &str = "Y";

    /// 8 B64 char tag
    pub const TAG8: &str = "1AAN";

    /// 9 B64 char tag with 1 pre pad
    pub const TAG9: &str = "0N";

    /// 10 B64 char tag
    pub const TAG10: &str = "0O";

    /// String Base64 Only Leader Size 0
    pub const STRB64_L0: &str = "4A";

    /// String Base64 Only Leader Size 1
    pub const STRB64_L1: &str = "5A";

    /// String Base64 Only Leader Size 2
    pub const STRB64_L2: &str = "6A";

    /// String Base64 Only Big Leader Size 0
    pub const STRB64_BIG_L0: &str = "7AAA";

    /// String Base64 Only Big Leader Size 1
    pub const STRB64_BIG_L1: &str = "8AAA";

    /// String Base64 Only Big Leader Size 2
    pub const STRB64_BIG_L2: &str = "9AAA";

    /// Label1 1 bytes for label lead size 1
    pub const LABEL1: &str = "V";

    /// Label2 2 bytes for label lead size 0
    pub const LABEL2: &str = "W";

    /// Byte String lead size 0
    pub const BYTES_L0: &str = "4B";

    /// Byte String lead size 1
    pub const BYTES_L1: &str = "5B";

    /// Byte String lead size 2
    pub const BYTES_L2: &str = "6B";

    /// Byte String big lead size 0
    pub const BYTES_BIG_L0: &str = "7AAB";

    /// Byte String big lead size 1
    pub const BYTES_BIG_L1: &str = "8AAB";

    /// Byte String big lead size 2
    pub const BYTES_BIG_L2: &str = "9AAB";

    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("TAG1", TAG1);
        map.insert("TAG2", TAG2);
        map.insert("TAG3", TAG3);
        map.insert("TAG4", TAG4);
        map.insert("TAG5", TAG5);
        map.insert("TAG6", TAG6);
        map.insert("TAG7", TAG7);
        map.insert("TAG8", TAG8);
        map.insert("TAG9", TAG9);
        map.insert("TAG10", TAG10);
        map.insert("STRB64_L0", STRB64_L0);
        map.insert("STRB64_L1", STRB64_L1);
        map.insert("STRB64_L2", STRB64_L2);
        map.insert("STRB64_BIG_L0", STRB64_BIG_L0);
        map.insert("STRB64_BIG_L1", STRB64_BIG_L1);
        map.insert("STRB64_BIG_L2", STRB64_BIG_L2);
        map.insert("LABEL1", LABEL1);
        map.insert("LABEL2", LABEL2);
        map.insert("BYTES_L0", BYTES_L0);
        map.insert("BYTES_L1", BYTES_L1);
        map.insert("BYTES_L2", BYTES_L2);
        map.insert("BYTES_BIG_L0", BYTES_BIG_L0);
        map.insert("BYTES_BIG_L1", BYTES_BIG_L1);
        map.insert("BYTES_BIG_L2", BYTES_BIG_L2);
        map
    });
}

/// PreCodex is codex of all identifier prefix derivation codes.
/// This is needed to verify valid inception events.
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod pre_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// Ed25519 verification key non-transferable, basic derivation
    pub const ED25519N: &str = "B";

    /// Ed25519 verification key, basic derivation
    pub const ED25519: &str = "D";

    /// Blake3 256 bit digest self-addressing derivation
    pub const BLAKE3_256: &str = "E";

    /// Blake2b 256 bit digest self-addressing derivation
    pub const BLAKE2B_256: &str = "F";

    /// Blake2s 256 bit digest self-addressing derivation
    pub const BLAKE2S_256: &str = "G";

    /// SHA3 256 bit digest self-addressing derivation
    pub const SHA3_256: &str = "H";

    /// SHA2 256 bit digest self-addressing derivation
    pub const SHA2_256: &str = "I";

    /// Blake3 512 bit digest self-addressing derivation
    pub const BLAKE3_512: &str = "0D";

    /// Blake2b 512 bit digest self-addressing derivation
    pub const BLAKE2B_512: &str = "0E";

    /// SHA3 512 bit digest self-addressing derivation
    pub const SHA3_512: &str = "0F";

    /// SHA2 512 bit digest self-addressing derivation
    pub const SHA2_512: &str = "0G";

    /// ECDSA secp256k1 verification key non-transferable, basic derivation
    pub const ECDSA_256K1N: &str = "1AAA";

    /// ECDSA public verification or encryption key, basic derivation
    pub const ECDSA_256K1: &str = "1AAB";

    /// Ed448 verification key non-transferable, basic derivation
    pub const ED448N: &str = "1AAC";

    /// Ed448 verification key, basic derivation
    pub const ED448: &str = "1AAD";

    /// Ed448 signature. Self-signing derivation
    pub const ED448_SIG: &str = "1AAE";

    /// ECDSA secp256r1 verification key non-transferable, basic derivation
    pub const ECDSA_256R1N: &str = "1AAI";

    /// ECDSA secp256r1 verification or encryption key, basic derivation
    pub const ECDSA_256R1: &str = "1AAJ";

    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("ED25519N", ED25519N);
        map.insert("ED25519", ED25519);
        map.insert("BLAKE3_256", BLAKE3_256);
        map.insert("BLAKE2B_256", BLAKE2B_256);
        map.insert("BLAKE2S_256", BLAKE2S_256);
        map.insert("SHA3_256", SHA3_256);
        map.insert("SHA2_256", SHA2_256);
        map.insert("BLAKE3_512", BLAKE3_512);
        map.insert("BLAKE2B_512", BLAKE2B_512);
        map.insert("SHA3_512", SHA3_512);
        map.insert("SHA2_512", SHA2_512);
        map.insert("ECDSA_256K1N", ECDSA_256K1N);
        map.insert("ECDSA_256K1", ECDSA_256K1);
        map.insert("ED448N", ED448N);
        map.insert("ED448", ED448);
        map.insert("ED448_SIG", ED448_SIG);
        map.insert("ECDSA_256R1N", ECDSA_256R1N);
        map.insert("ECDSA_256R1", ECDSA_256R1);
        map
    });

    pub static TUPLE: [&'static str; 18] = [
        ED25519N,
        ED25519,
        BLAKE3_256,
        BLAKE2B_256,
        BLAKE2S_256,
        SHA3_256,
        SHA2_256,
        BLAKE3_512,
        BLAKE2B_512,
        SHA3_512,
        SHA2_512,
        ECDSA_256K1N,
        ECDSA_256K1,
        ED448N,
        ED448,
        ED448_SIG,
        ECDSA_256R1N,
        ECDSA_256R1,
    ];
}

/// NonTransCodex is codex of all non-transferable derivation codes
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod non_trans_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// Ed25519 verification key non-transferable, basic derivation
    pub const ED25519N: &str = "B";

    /// ECDSA secp256k1 verification key non-transferable, basic derivation
    pub const ECDSA_256K1N: &str = "1AAA";

    /// Ed448 verification key non-transferable, basic derivation
    pub const ED448N: &str = "1AAC";

    /// ECDSA secp256r1 verification key non-transferable, basic derivation
    pub const ECDSA_256R1N: &str = "1AAI";

    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("ED25519N", ED25519N);
        map.insert("ECDSA_256K1N", ECDSA_256K1N);
        map.insert("ED448N", ED448N);
        map.insert("ECDSA_256R1N", ECDSA_256R1N);
        map
    });

    pub static TUPLE: [&'static str; 4] = [ED25519N, ECDSA_256K1N, ED448N, ECDSA_256R1N];
}

/// PreNonDigCodex is codex of all prefixive but non-digestive derivation codes
/// Only provides defined codes.
/// Undefined are left out so that inclusion(exclusion) via contains works.
#[allow(dead_code)]
pub mod pre_non_dig_dex {
    use once_cell::sync::Lazy;
    use std::collections::HashMap;

    /// Ed25519 verification key non-transferable, basic derivation
    pub const ED25519N: &str = "B";

    /// Ed25519 verification key, basic derivation
    pub const ED25519: &str = "D";

    /// ECDSA secp256k1 verification key non-transferable, basic derivation
    pub const ECDSA_256K1N: &str = "1AAA";

    /// ECDSA public verification or encryption key, basic derivation
    pub const ECDSA_256K1: &str = "1AAB";

    /// Ed448 verification key non-transferable, basic derivation
    pub const ED448N: &str = "1AAC";

    /// Ed448 verification key, basic derivation
    pub const ED448: &str = "1AAD";

    /// ECDSA secp256r1 verification key non-transferable, basic derivation
    pub const ECDSA_256R1N: &str = "1AAI";

    /// ECDSA secp256r1 verification or encryption key, basic derivation
    pub const ECDSA_256R1: &str = "1AAJ";

    pub static MAP: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| {
        let mut map = HashMap::new();
        map.insert("ED25519N", ED25519N);
        map.insert("ED25519", ED25519);
        map.insert("ECDSA_256K1N", ECDSA_256K1N);
        map.insert("ECDSA_256K1", ECDSA_256K1);
        map.insert("ED448N", ED448N);
        map.insert("ED448", ED448);
        map.insert("ECDSA_256R1N", ECDSA_256R1N);
        map.insert("ECDSA_256R1", ECDSA_256R1);
        map
    });
}

#[derive(Clone, Copy, Debug)]
pub struct Sizage {
    pub hs: u32,         // header size
    pub ss: u32,         // section size
    pub xs: u32,         // extra size
    pub fs: Option<u32>, // field size
    pub ls: u32,         // list size
}

pub fn get_sizes() -> HashMap<&'static str, Sizage> {
    let mut sizes = HashMap::new();

    // Adding all the size entries
    sizes.insert(
        "A",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Ed25519_Seed
    sizes.insert(
        "B",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Ed25519N
    sizes.insert(
        "C",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // X25519
    sizes.insert(
        "D",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Ed25519
    sizes.insert(
        "E",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Blake3_256
    sizes.insert(
        "F",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Blake2b_256
    sizes.insert(
        "G",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Blake2s_256
    sizes.insert(
        "H",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // SHA3_256
    sizes.insert(
        "I",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // SHA2_256
    sizes.insert(
        "J",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // ECDSA_256k1N
    sizes.insert(
        "K",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(76),
            ls: 0,
        },
    ); // ECDSA_256r1N
    sizes.insert(
        "L",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(76),
            ls: 0,
        },
    ); // X448
    sizes.insert(
        "M",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    ); // SHA3_512
    sizes.insert(
        "N",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(12),
            ls: 0,
        },
    ); // SHA2_512
    sizes.insert(
        "O",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // ECDSA_256k1
    sizes.insert(
        "P",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(124),
            ls: 0,
        },
    ); // ECDSA_256r1
    sizes.insert(
        "Q",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(44),
            ls: 0,
        },
    ); // Ed448N
    sizes.insert(
        "R",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(8),
            ls: 0,
        },
    ); // Ed448
    sizes.insert(
        "S",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(16),
            ls: 0,
        },
    ); // Ed448_Sig
    sizes.insert(
        "U",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(20),
            ls: 0,
        },
    ); // Blake3_512
    sizes.insert(
        "V",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(24),
            ls: 0,
        },
    ); // Blake2b_512
    sizes.insert(
        "W",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    ); // ECDSA_256k1_Sig
    sizes.insert(
        "X",
        Sizage {
            hs: 1,
            ss: 3,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    ); // ECDSA_256r1_Sig
    sizes.insert(
        "Y",
        Sizage {
            hs: 1,
            ss: 7,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    ); // ECDSA_256k1_Seed
    sizes.insert(
        "Z",
        Sizage {
            hs: 1,
            ss: 0,
            xs: 0,
            fs: Some(8),
            ls: 0,
        },
    ); // ECDSA_256r1_Seed
    sizes.insert(
        "0A",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(24),
            ls: 0,
        },
    );
    sizes.insert(
        "0B",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0C",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0D",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0E",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0F",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0G",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0H",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(8),
            ls: 0,
        },
    );
    sizes.insert(
        "0I",
        Sizage {
            hs: 2,
            ss: 0,
            xs: 0,
            fs: Some(88),
            ls: 0,
        },
    );
    sizes.insert(
        "0J",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 1,
            fs: Some(4),
            ls: 0,
        },
    );
    sizes.insert(
        "0K",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    );
    sizes.insert(
        "0L",
        Sizage {
            hs: 2,
            ss: 6,
            xs: 1,
            fs: Some(8),
            ls: 0,
        },
    );
    sizes.insert(
        "0M",
        Sizage {
            hs: 2,
            ss: 6,
            xs: 0,
            fs: Some(8),
            ls: 0,
        },
    );
    sizes.insert(
        "0N",
        Sizage {
            hs: 2,
            ss: 10,
            xs: 1,
            fs: Some(12),
            ls: 0,
        },
    );
    sizes.insert(
        "0O",
        Sizage {
            hs: 2,
            ss: 10,
            xs: 0,
            fs: Some(12),
            ls: 0,
        },
    );
    sizes.insert(
        "0P",
        Sizage {
            hs: 2,
            ss: 22,
            xs: 0,
            fs: Some(32),
            ls: 0,
        },
    );
    sizes.insert(
        "0Q",
        Sizage {
            hs: 2,
            ss: 22,
            xs: 0,
            fs: Some(28),
            ls: 0,
        },
    );
    sizes.insert(
        "0R",
        Sizage {
            hs: 2,
            ss: 22,
            xs: 0,
            fs: Some(76),
            ls: 0,
        },
    );
    sizes.insert(
        "0S",
        Sizage {
            hs: 2,
            ss: 22,
            xs: 0,
            fs: Some(72),
            ls: 0,
        },
    );

    sizes.insert(
        "1AAA",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(48),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAB",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(48),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAC",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(80),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAD",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(80),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAE",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(156),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAF",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: Some(8),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAG",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(36),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAH",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(100),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAI",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(48),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAJ",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(48),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAK",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAL",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAM",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(4),
            ls: 0,
        },
    );
    sizes.insert(
        "1AAN",
        Sizage {
            hs: 4,
            ss: 8,
            xs: 0,
            fs: Some(12),
            ls: 0,
        },
    );

    sizes.insert(
        "1__-",
        Sizage {
            hs: 4,
            ss: 2,
            xs: 0,
            fs: Some(12),
            ls: 0,
        },
    );
    sizes.insert(
        "1___",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(8),
            ls: 0,
        },
    );
    sizes.insert(
        "2__-",
        Sizage {
            hs: 4,
            ss: 2,
            xs: 1,
            fs: Some(12),
            ls: 1,
        },
    );
    sizes.insert(
        "2___",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(8),
            ls: 1,
        },
    );
    sizes.insert(
        "3__-",
        Sizage {
            hs: 4,
            ss: 2,
            xs: 0,
            fs: Some(12),
            ls: 2,
        },
    );
    sizes.insert(
        "3___",
        Sizage {
            hs: 4,
            ss: 0,
            xs: 0,
            fs: Some(8),
            ls: 2,
        },
    );

    sizes.insert(
        "4A",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "5A",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "6A",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );
    sizes.insert(
        "7AAA",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "8AAA",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "9AAA",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );

    sizes.insert(
        "4B",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "5B",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "6B",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );
    sizes.insert(
        "7AAB",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "8AAB",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "9AAB",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );

    sizes.insert(
        "4C",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "5C",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "6C",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );
    sizes.insert(
        "7AAC",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "8AAC",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "9AAC",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );

    sizes.insert(
        "4D",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "5D",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "6D",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );
    sizes.insert(
        "7AAD",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "8AAD",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "9AAD",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );

    sizes.insert(
        "4E",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "5E",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "6E",
        Sizage {
            hs: 2,
            ss: 2,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );
    sizes.insert(
        "7AAE",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 0,
        },
    );
    sizes.insert(
        "8AAE",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 1,
        },
    );
    sizes.insert(
        "9AAE",
        Sizage {
            hs: 4,
            ss: 4,
            xs: 0,
            fs: None,
            ls: 2,
        },
    );

    sizes
}

/// Map of hard characters to their respective values
///
/// Includes:
/// - Uppercase letters (A-Z): value 1
/// - Lowercase letters (a-z): value 1
/// - Digits with varying values:
///   - '0','4','5','6': value 2
///   - '1','2','3','7','8','9': value 4
pub fn hards() -> HashMap<u8, i32> {
    let mut map: HashMap<u8, i32> = (b'A'..=b'Z').map(|c| (c, 1)).collect();

    // Add lowercase letters with value 1
    map.extend((b'a'..=b'z').map(|c| (c, 1)));

    // Add digits with specific values
    map.extend([
        (b'0', 2),
        (b'1', 4),
        (b'2', 4),
        (b'3', 4),
        (b'4', 2),
        (b'5', 2),
        (b'6', 2),
        (b'7', 4),
        (b'8', 4),
        (b'9', 4),
    ]);

    map
}

/// Converts a base64 character to its binary quadlet (2-bit) representation
fn code_b64_to_b2(c: u8) -> u8 {
    match c {
        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'+' | b'/' => {
            let val = match c {
                b'A'..=b'Z' => c - b'A',
                b'a'..=b'z' => c - b'a' + 26,
                b'0'..=b'9' => c - b'0' + 52,
                b'+' => 62,
                b'/' => 63,
                _ => unreachable!(),
            };
            val
        }
        _ => b'0',
    }
}

/// Map of binary quadlet characters to their hardness values
/// This converts the base64 characters in the Hards map to their binary
/// representation and maps them to the same hardness values
pub fn get_bards() -> HashMap<u8, i32> {
    let hards = hards();
    let mut bards: HashMap<u8, i32> = hards
        .iter()
        .map(|(&c, &hs)| (code_b64_to_b2(c), hs))
        .collect();

    // Add specific mapping for SALT_128 code which starts with '0'
    // The binary sextet representation of '0' in qb2 format is 0xd0 (208)
    bards.insert(0xd0, 2); // '0' has a hard size of 2

    bards
}

/// Matter is a trait for fully qualified cryptographic material.
/// Implementations provide various specialized crypto material types.
pub trait Matter: Any {
    /// Returns the hard part of the derivation code
    fn code(&self) -> &str;

    /// Returns raw crypto material (without derivation code)
    fn raw(&self) -> &[u8];

    /// Returns base64 fully qualified representation
    fn qb64(&self) -> String;

    /// Returns base64 fully qualified representation
    fn qb64b(&self) -> Vec<u8>;

    /// Returns binary fully qualified representation
    fn qb2(&self) -> Vec<u8>;

    /// Soft portion of qb64 value
    fn soft(&self) -> &str;

    /// Return the full size of this Matter instance
    fn full_size(&self) -> usize;

    /// Calculate the populated size
    fn size(&self) -> usize;

    /// Returns whether the derivation code is transferable
    fn is_transferable(&self) -> bool;

    /// Returns whether the code represents a digest
    fn is_digestive(&self) -> bool;

    /// Returns whether the code represents a prefix
    fn is_prefixive(&self) -> bool;

    /// Returns whether the code represents a prefix
    fn is_special(&self) -> bool;

    fn as_any(&self) -> &dyn Any;
}

/// Trait that must be implemented by types that can be parsed
pub trait Parsable: Sized {
    fn from_qb64b(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError>;
    fn from_qb2(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError>;
}

/// Common implementation for all Matter types.
#[derive(Debug, Clone)]
pub struct BaseMatter {
    code: String,
    soft: String,
    raw: Vec<u8>,
}

impl TryFrom<Vec<u8>> for BaseMatter {
    type Error = MatterError;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        BaseMatter::from_qb64b(&mut value.clone(), None)
    }
}

impl BaseMatter {
    /// Creates a new BaseMatter from raw bytes and a code
    pub fn new(
        raw: Option<&[u8]>,
        code: Option<&str>,
        soft: Option<&str>,
        rize: Option<usize>,
    ) -> Result<Self, MatterError> {
        let code = code.ok_or_else(|| {
            MatterError::EmptyMaterial(
                "Improper initialization need either (raw not None and code) or \
             (code and soft) or qb64b or qb64 or qb2."
                    .to_string(),
            )
        })?;

        let raw =
            raw.ok_or_else(|| MatterError::TypeError(String::from("Raw data must be provided")))?;

        let sizes = get_sizes();
        // Check if code is supported
        if !sizes.contains_key(code) {
            return Err(MatterError::InvalidCode(format!(
                "Unsupported code={}",
                code
            )));
        }

        // Get sizes for this code
        let size = sizes[code].clone(); // Assumes valid sizes from unit tests
        let (_, ss, xs, fs, _) = (size.hs, size.ss, size.xs, size.fs, size.ls);
        let hs;
        let rize_val;
        let mut soft_val = String::new();
        let mut code_val = code.to_string();

        if fs.is_none() {
            // Variable sized - code[0] should be in SmallVrzDex or LargeVrzDex
            // Determine the size of raw data to use
            rize_val = match rize {
                Some(r) => r,
                None => raw.len(),
            };

            // Calculate actual lead (pad) size
            let ls = ((3 - (rize_val % 3)) % 3) as u32;
            // Calculate size in triplets
            let size = (rize_val + ls as usize) / 3;

            // Handle small vs large variable size codes
            if small_vrz_dex::TUPLE.contains(&&code[0..1]) {
                if size <= (64_usize.pow(2) - 1) {
                    // ss = 2
                    hs = 2;
                    let s = small_vrz_dex::TUPLE[ls as usize];
                    code_val = format!("{}{}", s, &code[1..hs as usize]);
                    soft_val = int_to_b64(size as u32, 2);
                } else if size <= (64_usize.pow(4) - 1) {
                    // ss = 4 make big version
                    hs = 4;
                    let s = large_vrz_dex::TUPLE[ls as usize];
                    code_val = format!("{}{}{}", s, "A".repeat(hs as usize - 2), &code[1..2]);
                    soft_val = int_to_b64(size as u32, 4);
                } else {
                    return Err(MatterError::InvalidVarRawSize(format!(
                        "Unsupported raw size for code={}",
                        code
                    )));
                }
            } else if large_vrz_dex::TUPLE.contains(&&code[0..1]) {
                if size <= (64_usize.pow(4) - 1) {
                    // ss = 4
                    hs = 4;
                    let s = large_vrz_dex::TUPLE[ls as usize];
                    code_val = format!("{}{}", s, &code[1..hs as usize]);
                    soft_val = int_to_b64(size as u32, 4);
                } else {
                    return Err(MatterError::InvalidVarRawSize(format!(
                        "Unsupported raw size for large code={}. {} <= {}",
                        code,
                        size,
                        64_usize.pow(4) - 1
                    )));
                }
            } else {
                return Err(MatterError::InvalidVarRawSize(format!(
                    "Unsupported variable raw size code={}",
                    code
                )));
            }
        } else {
            // Fixed size
            rize_val = raw_size(&code_val)?;

            if ss > 0 {
                // Special soft size, so soft must be provided
                let soft_str = soft.unwrap_or("");
                let trimmed_soft =
                    &soft_str[..std::cmp::min(soft_str.len(), ss as usize - xs as usize)];

                if trimmed_soft.len() != ss as usize - xs as usize {
                    return Err(MatterError::SoftMaterial(format!(
                        "Not enough chars in soft={} with ss={} xs={} for code={}",
                        soft_str, ss, xs, code
                    )));
                }

                // Check if all characters are Base64
                if !trimmed_soft
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=')
                {
                    return Err(MatterError::InvalidSoft(format!(
                        "Non Base64 chars in soft={}",
                        trimmed_soft
                    )));
                }

                soft_val = trimmed_soft.to_string();
            }
        }

        // Ensure raw has exactly the right size
        if raw.len() < rize_val {
            return Err(MatterError::RawMaterial(format!(
                "Not enough raw bytes for code={} expected rize={} got {}",
                code,
                rize_val,
                raw.len()
            )));
        }

        // Clone only the exact size needed from raw
        let raw_val = Vec::from(&raw[..rize_val]);

        Ok(BaseMatter {
            code: code_val,
            soft: soft_val,
            raw: raw_val,
            // Add other fields as needed
        })
    }

    pub fn from_raw(raw: Option<&[u8]>) -> Result<Self, MatterError> {
        BaseMatter::new(raw, Some(mtr_dex::ED25519N), None, None)
    }

    /// Creates a new BaseMatter from a qb64 string
    pub fn from_qb64(qb64: &str) -> Result<Self, MatterError> {
        if qb64.is_empty() {
            return Err(MatterError::ShortageError(
                "Empty qb64, invalid".to_string(),
            ));
        }

        let first = &qb64[0..1];

        let hards = hards();
        let sizes = get_sizes();
        // Check if first character is in Hards
        if !hards.contains_key(&first.bytes().next().unwrap_or(b'A')) {
            return if first == "-" {
                Err(MatterError::UnexpectedCountCodeError(
                    "Unexpected count code start while extracting Matter.".to_string(),
                ))
            } else if first == "_" {
                Err(MatterError::UnexpectedOpCodeError(
                    "Unexpected op code start while extracting Matter.".to_string(),
                ))
            } else {
                Err(MatterError::UnexpectedCodeError(format!(
                    "Unsupported code start char={}",
                    first
                )))
            };
        }

        let hs = *hards.get(&first.bytes().next().unwrap_or(b'A')).unwrap(); // get hard code size

        if qb64.len() < hs as usize {
            return Err(MatterError::ShortageError(format!(
                "Need {} more characters.",
                hs - qb64.len() as i32
            )));
        }

        let hard = &qb64[0..hs as usize];

        if !sizes.contains_key(hard) {
            return Err(MatterError::UnexpectedCodeError(format!(
                "Unsupported code ={}",
                hard
            )));
        }

        let size = *sizes.get(hard).unwrap();
        let cs = hs as u32 + size.ss; // both hs and ss

        // Extract soft chars including xtra, empty when ss==0 and xs == 0
        let soft = if size.ss > 0 {
            &qb64[hs as usize..(hs as u32 + size.ss) as usize]
        } else {
            ""
        };
        let xtra = if size.xs > 0 {
            &soft[0..size.xs as usize]
        } else {
            ""
        };
        let soft_without_xtra = if size.xs > 0 {
            &soft[size.xs as usize..]
        } else {
            soft
        };

        if size.xs > 0 && xtra != &"A".repeat(size.xs as usize) {
            return Err(MatterError::UnexpectedCodeError(format!(
                "Invalid prepad xtra ={}",
                xtra
            )));
        }

        let fs = if size.fs.is_none() {
            // compute fs from soft from ss part which provides size B64
            (b64_to_int(soft_without_xtra) * 4) + cs
        } else {
            size.fs.unwrap()
        };

        if qb64.len() < fs as usize {
            return Err(MatterError::ShortageError(format!(
                "Need {} more chars.",
                fs - qb64.len() as u32
            )));
        }

        let qb64 = &qb64[0..fs as usize]; // fully qualified primitive code plus material

        // Check for non-zeroed pad bits and/or lead bytes
        let ps = cs % 4; // net prepad bytes to ensure 24 bit align when encodeB64
        let base = "A".repeat(ps as usize) + &qb64[cs as usize..]; // prepad ps 'A's to B64 of (lead + raw)
        let paw = decode_b64(&base)?;

        // Ensure midpad bytes are zero
        let midpad = &paw[0..(ps + size.ls) as usize];
        let pi = u32::from_be_bytes([
            if midpad.len() > 0 { midpad[0] } else { 0 },
            if midpad.len() > 1 { midpad[1] } else { 0 },
            if midpad.len() > 2 { midpad[2] } else { 0 },
            if midpad.len() > 3 { midpad[3] } else { 0 },
        ]);

        if pi != 0 {
            return Err(MatterError::ConversionError(format!(
                "Nonzero midpad bytes=0x{:0width$x}.",
                pi,
                width = (ps + size.ls) as usize * 2
            )));
        }

        // Remove prepad midpat bytes to invert back to raw
        let raw = paw[(ps + size.ls) as usize..].to_vec();

        let expected_len = ((qb64.len() - cs as usize) * 3 / 4) - size.ls as usize;
        if raw.len() != expected_len {
            return Err(MatterError::ConversionError(format!(
                "Improperly qualified material = {}",
                qb64
            )));
        }

        Ok(Self {
            code: hard.to_string(),
            soft: soft.to_string(),
            raw,
        })
    }

    pub fn bexfil(qb2: &[u8]) -> Result<Self, MatterError> {
        if qb2.is_empty() {
            return Err(MatterError::Shortage(
                "Empty material, Need more bytes.".into(),
            ));
        }

        // Extract first sextet as code selector
        let first = nab_sextets(qb2, 1)?;

        let bards = get_bards();
        let hs = match bards.get(&first[0]) {
            Some(hs) => *hs,
            None => {
                return if first[0] == 0xf8 {
                    // b64ToB2('-')
                    Err(MatterError::UnexpectedCountCode(
                        "Unexpected count code start while extracting Matter.".into(),
                    ))
                } else if first[0] == 0xfc {
                    // b64ToB2('_')
                    Err(MatterError::UnexpectedOpCode(
                        "Unexpected op code start while extracting Matter.".into(),
                    ))
                } else {
                    Err(MatterError::UnexpectedCode(format!(
                        "Unsupported code start sextet={:02x?}.",
                        first
                    )))
                };
            }
        };

        // bhs is min bytes to hold hs sextets
        let bhs = ((hs as f64) * 3.0 / 4.0).ceil() as usize;
        if qb2.len() < bhs {
            return Err(MatterError::Shortage(format!(
                "Need {} more bytes.",
                bhs - qb2.len()
            )));
        }

        // Extract and convert hard part of code
        let hard = code_b2_to_b64(qb2, hs as usize)?;

        let sizes = get_sizes();
        let size = sizes[hard.as_str()].clone();
        let (hs, ss, xs, fs, ls) = (size.hs, size.ss, size.xs, size.fs, size.ls);
        let cs = hs + ss; // both hs and ss

        // bcs is min bytes to hold cs sextets
        let bcs = ((cs as f64) * 3.0 / 4.0).ceil() as usize;
        if qb2.len() < bcs {
            return Err(MatterError::Shortage(format!(
                "Need {} more bytes.",
                bcs - qb2.len()
            )));
        }

        // Extract and convert both hard and soft part of code
        let both = code_b2_to_b64(qb2, cs as usize)?;

        // Extract soft chars including xtra, empty when ss==0 and xs == 0
        // Assumes that when ss == 0 then xs must be 0
        let mut soft = both[hs as usize..].to_string();
        let xtra = if xs > 0 {
            soft[..xs as usize].to_string()
        } else {
            String::new()
        };

        if xs > 0 {
            soft = soft[xs as usize..].to_string();
        }

        // Check for valid padding in xtra
        if xs > 0 && xtra != PAD.to_string().repeat(xs as usize) {
            return Err(MatterError::UnexpectedCode(format!(
                "Invalid prepad xtra ={}",
                xtra
            )));
        }

        // Calculate the full size (fs)
        let calculated_fs = if fs.unwrap_or(0) == 0 {
            // Compute fs from size chars in ss part of code
            if qb2.len() < bcs {
                return Err(MatterError::Shortage(format!(
                    "Need {} more bytes.",
                    bcs - qb2.len()
                )));
            }

            // Compute size as int from soft part given by ss B64 chars
            let soft_int = b64_to_int(&soft);
            (soft_int * 4) + cs
        } else {
            fs.unwrap_or(0)
        };

        // bfs is min bytes to hold fs sextets
        let bfs = ((calculated_fs as f64) * 3.0 / 4.0).ceil() as usize;
        if qb2.len() < bfs {
            return Err(MatterError::Shortage(format!(
                "Need {} more bytes.",
                bfs - qb2.len()
            )));
        }

        let qb2 = &qb2[..bfs]; // Extract qb2 fully qualified primitive code plus material

        // Check for nonzero trailing full code mid pad bits
        let ps = cs % 4; // Full code (both) net pad size for 24 bit alignment
        let pbs = 2 * ps; // Mid pad bits = 2 per net pad

        if pbs > 0 {
            // Get pad bits in last byte of full code
            let pi = qb2[bcs - 1];
            let mask = (1 << pbs) - 1; // Mask with 1's in pad bit locations
            if pi & mask != 0 {
                // Not zero so raise error
                return Err(MatterError::Conversion(format!(
                    "Nonzero code mid pad bits=0b{:0width$b}.",
                    pi & mask,
                    width = pbs as usize
                )));
            }
        }

        // Check nonzero leading mid pad lead bytes in lead + raw
        if ls > 0 {
            let mut lead_bytes = vec![0u8; ls as usize];
            lead_bytes.copy_from_slice(&qb2[bcs..bcs + ls as usize]);

            let mut is_zero = true;
            for byte in &lead_bytes {
                if *byte != 0 {
                    is_zero = false;
                    break;
                }
            }

            if !is_zero {
                return Err(MatterError::Conversion(format!(
                    "Nonzero lead midpad bytes={:0width$x?}.",
                    lead_bytes,
                    width = (ls * 2) as usize
                )));
            }
        }

        // Strip code and leader bytes from qb2 to get raw
        let raw = if (bcs + ls as usize) < qb2.len() {
            qb2[bcs + ls as usize..].to_vec()
        } else {
            Vec::new()
        };

        if raw.len() != (qb2.len() - bcs - ls as usize) {
            return Err(MatterError::Conversion(format!(
                "Improperly qualified material = {:?}",
                qb2
            )));
        }

        // Update the struct fields
        Ok(Self {
            code: hard.to_string(),
            soft,
            raw,
        })
    }

    /// Creates a new BaseMatter instance from soft and code components
    ///
    /// # Arguments
    /// * `soft` - The soft part of the code as a string slice
    /// * `code` - The hard part of the code as a string slice
    ///
    /// # Returns
    /// * `Result<Self, MatterError>` - A BaseMatter instance or an error
    fn from_soft_and_code(soft: &str, code: &str) -> Result<Self, MatterError> {
        // Get the sizes associated with the given code
        let sizes = get_sizes();
        let size = sizes[code].clone();
        let (hs, ss, xs, fs, ls) = (size.hs, size.ss, size.xs, size.fs.unwrap_or(0), size.ls);

        // Check if code is a variable sized code
        if fs == 0 {
            return Err(MatterError::InvalidSoftError(format!(
                "Unsupported variable sized code={} with fs={} for special soft={}.",
                code, fs, soft
            )));
        }

        // Check if it's not a special soft - validate ss, fs, hs, and ls
        if !(ss > 0) || (fs == hs + ss && ls != 0) {
            return Err(MatterError::InvalidSoftError(format!(
                "Invalid soft size={} or lead={} or code={} fs={} when special soft.",
                ss, ls, code, fs
            )));
        }

        // Trim soft to correct length
        let trimmed_soft = if soft.len() >= (ss - xs) as usize {
            &soft[0..(ss - xs) as usize]
        } else {
            return Err(MatterError::SoftMaterialError(format!(
                "Not enough chars in soft={} with ss={} xs={} for code={}.",
                soft, ss, xs, code
            )));
        };

        // Validate that soft contains only Base64 characters
        if !is_base64(trimmed_soft) {
            return Err(MatterError::InvalidSoftError(format!(
                "Non Base64 chars in soft={}.",
                trimmed_soft
            )));
        }

        // Return populated BaseMatter struct
        Ok(BaseMatter {
            code: code.to_string(),
            soft: trimmed_soft.to_string(),
            raw: Vec::new(), // Empty raw bytes as in Python: self._raw = b''
        })
    }

    fn infil(&self) -> Result<String, MatterError> {
        let code = &self.code; // hard part of full code == codex value
        let both = format!("{}{}", self.code, self.soft); // code + soft, soft may be empty
        let raw = &self.raw; // bytes, raw may be empty
        let rs = raw.len(); // raw size

        // Get sizes from the Sizes table based on the code
        let sizes = get_sizes();
        let size = sizes[code.as_str()];
        let (hs, ss, xs, fs, ls) = (size.hs, size.ss, size.xs, size.fs, size.ls);
        let cs = hs + ss;

        // Verify the code size is valid
        if cs != both.len() as u32 {
            return Err(MatterError::InvalidCodeSize(format!(
                "Invalid full code={} for sizes hs={} and ss={}.",
                both, hs, ss
            )));
        }

        let full = if fs.unwrap_or(0) == 0 {
            // Variable sized
            // Ensure that (ls + rs) % 3 == 0 and cs % 4 == 0
            if (ls + rs as u32) % 3 != 0 || cs % 4 != 0 {
                return Err(MatterError::InvalidCodeSize(format!(
                    "Invalid full code both={} with variable raw size={} given cs={}, hs={}, ss={}, fs={}, and ls={}.",
                    both, rs, cs, hs, ss, fs.unwrap_or(0), ls
                )));
            }

            // Prepad raw with ls zero bytes and convert
            let mut padded_raw = vec![0; ls as usize];
            padded_raw.extend_from_slice(raw);
            let encoded = encode_b64(&padded_raw);

            format!("{}{}", both, encoded)
        } else {
            // Fixed size
            let ps = (3 - ((rs + ls as usize) % 3)) % 3; // net pad size given raw with lead

            // Check if pad size matches code size remainder
            if ps != (cs % 4) as usize {
                return Err(MatterError::InvalidCodeSize(format!(
                    "Invalid full code both={} with fixed raw size={} given cs={}, hs={}, ss={}, fs={}, and ls={}.",
                    both, rs, cs, hs, ss, fs.unwrap_or(0), ls
                )));
            }

            // Prepad raw with ps+ls zero bytes
            let mut padded_raw = vec![0; ps + ls as usize];
            padded_raw.extend_from_slice(raw);
            let encoded = encode_b64(&padded_raw);

            // Skip first ps == cs % 4 of the converted characters
            format!("{}{}", both, &encoded[ps..])
        };

        // Final validation
        if (full.len() % 4 != 0) || (fs.unwrap_or(0) > 0 && full.len() != fs.unwrap_or(0) as usize)
        {
            return Err(MatterError::InvalidCodeSize(format!(
                "Invalid full size given code both={} with raw size={}, cs={}, hs={}, ss={}, xs={}, fs={}, and ls={}.",
                both, rs, cs, hs, ss, xs, fs.unwrap_or(0), ls
            )));
        }

        Ok(full)
    }

    /// Create binary domain representation
    ///
    /// Returns bytes of fully qualified base2 bytes, that is .qb2
    /// self.code converted to Base2 + self.raw left shifted with pad bits
    /// equivalent of Base64 decode of .qb64 into .qb2
    pub fn binfil(&self) -> Result<Vec<u8>, MatterError> {
        let code = &self.code; // hard part of full code == codex value
        let both = format!("{}{}", &self.code, &self.soft); // code + soft, soft may be empty
        let raw = &self.raw; // bytes may be empty

        // Get sizes from the Sizes table based on the code
        let sizes = get_sizes();
        let size = sizes[code.as_str()];
        let (hs, ss, fs, ls) = (size.hs, size.ss, size.fs, size.ls);
        let cs = hs + ss;
        // assumes unit tests on BaseMatter.get_sizes ensure valid size entries

        // Number of b2 bytes to hold b64 code
        let n = ((cs * 3) as f64 / 4.0).ceil() as usize; // sceil equivalent

        // Convert code both to right align b2 int then left shift in pad bits
        // then convert to bytes
        let b64_int = b64_to_int(&both);
        let shift = 2 * (cs % 4);
        let b64_shifted = b64_int << shift;

        // Create bytes from the shifted integer
        let bcode = b64_shifted.to_be_bytes()[b64_shifted.to_be_bytes().len() - n..].to_vec();

        // Combine bcode with lead bytes and raw data
        let mut full = Vec::new();
        full.extend_from_slice(&bcode);
        full.extend_from_slice(&vec![0; ls as usize]);
        full.extend_from_slice(raw);

        let bfs = full.len();

        // Compute fs if not provided (variable size)
        let calculated_fs = if fs.unwrap_or(0) == 0 {
            hs + ss + ((raw.len() as u32 + ls) * 4) / 3
        } else {
            fs.unwrap()
        };

        // Validate size
        if bfs % 3 != 0 || ((bfs * 4) / 3) != calculated_fs as usize {
            return Err(MatterError::InvalidCodeSize(format!(
                "Invalid full code={} for raw size={}.",
                both,
                raw.len()
            )));
        }

        Ok(full)
    }
}

impl Parsable for BaseMatter {
    fn from_qb64b(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError> {
        let qb64b = data.as_slice();
        let qb64 = str::from_utf8(qb64b).ok();
        let mtr = BaseMatter::from_qb64(qb64.unwrap_or(""))?;
        if strip.unwrap_or(false) {
            let fs = mtr.full_size();
            data.drain(..fs);
        }
        Ok(mtr)
    }

    /// Creates a new BaseMatter from qb2 bytes
    fn from_qb2(data: &mut Vec<u8>, strip: Option<bool>) -> Result<Self, MatterError> {
        let qb2 = data.as_slice();
        let mtr = BaseMatter::bexfil(qb2)?;
        if strip.unwrap_or(false) {
            let fs = mtr.full_size();
            data.drain(..fs);
        }
        Ok(mtr)
    }
}

// Helper function to decode base64 string to bytes
fn decode_b64(data: &str) -> Result<Vec<u8>, MatterError> {
    general_purpose::URL_SAFE_NO_PAD
        .decode(data)
        .map_err(|_| MatterError::InvalidBase64)
}

fn encode_b64(data: &[u8]) -> String {
    general_purpose::URL_SAFE_NO_PAD.encode(data)
}

// Helper function to convert base64 string to integer
pub fn b64_to_int(b64_str: &str) -> u32 {
    let mut result = 0u32;
    for c in b64_str.chars() {
        result = result * 64
            + match c {
                'A'..='Z' => c as u32 - 'A' as u32,
                'a'..='z' => c as u32 - 'a' as u32 + 26,
                '0'..='9' => c as u32 - '0' as u32 + 52,
                '+' | '-' => 62,
                '/' | '_' => 63,
                _ => 0,
            };
    }
    result
}

// Helper function to convert integer to base64 string
pub fn int_to_b64(num: u32, length: usize) -> String {
    const B64_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

    let mut result = String::with_capacity(length);
    let mut n = num;

    for _ in 0..length {
        let idx = (n % 64) as usize;
        result.insert(0, B64_CHARS[idx] as char);
        n /= 64;
    }

    result
}

pub fn raw_size(code: &str) -> Result<usize, MatterError> {
    // Implementation would access self.sizes to get the raw size for this code
    // For this example, we'll return a placeholder
    // In the actual implementation, this would look up the size from the Sizes map
    let sizes = get_sizes();
    let size = sizes[code].clone();
    let cs = size.hs + size.ss;
    let fs = size
        .fs
        .ok_or_else(|| MatterError::InvalidCode(code.to_string()))?;

    Ok((((fs - cs) * 3 / 4) - size.ls) as usize)
}

/// Nab l sextets from front of b
///
/// # Returns
/// Bytes containing first l sextets from front (left) of b as a Vec<u8>.
/// Length of bytes returned is minimum sufficient to hold all l sextets.
/// Last byte returned is right bit padded with zeros which is compatible
/// with mid padded codes on front of primitives.
///
/// # Parameters
/// * `b`: target from which to nab sextets
/// * `l`: number of sextets to nab from front of b
///
/// # Errors
/// Returns an error message if there aren't enough bytes in b to nab l sextets.
pub fn nab_sextets(b: &[u8], l: usize) -> Result<Vec<u8>, MatterError> {
    // Calculate number of bytes needed for l sextets (ceiling of l*3/4)
    let n = (l * 3 + 3) / 4; // Equivalent to ceiling of l*3/4

    if n > b.len() {
        return Err(MatterError::ShortageError(format!(
            "Not enough bytes in {:?} to nab {} sextets.",
            b, l
        )));
    }

    // Extract the first n bytes and convert to a BigUint
    let bytes = &b[..n];
    let mut i = BigUint::from_bytes_be(bytes);

    // Calculate padding bits based on l % 4
    let p = 2 * (l % 4);

    if p > 0 {
        // Apply bit shifting operations
        // i >>= p  (strip off last bits)
        i >>= p;

        // i <<= p  (pad with empty bits)
        i <<= p;
    }

    // Convert back to bytes
    let mut result = i.to_bytes_be();

    // Ensure the result is exactly n bytes by padding with zeros if needed
    if result.len() < n {
        let padding = vec![0; n - result.len()];
        let mut padded_result = padding;
        padded_result.extend(result);
        result = padded_result;
    }

    Ok(result)
}

/// Convert l sextets from base2 b to base64
///
/// # Returns
/// A String containing the conversion (encode) of l Base2 sextets from front of b
/// to Base64 chars. One char for each of l sextets from front (left) of b.
///
/// This is useful for encoding as code characters, sextets from the front of
/// a Base2 bytes. Must provide l because of ambiguity between l=3
/// and l=4. Both require 3 bytes in b. Trailing pad bits are removed so
/// returned sextets as characters are right aligned.
///
/// # Parameters
/// * `b`: target from which to nab sextets
/// * `l`: number of sextets to convert from front of b
///
/// # Errors
/// Returns an error message if there aren't enough bytes in b to nab l sextets.
pub fn code_b2_to_b64(b: &[u8], l: usize) -> Result<String, MatterError> {
    // Calculate number of bytes needed for l sextets (ceiling of l*3/4)
    let n = (l * 3 + 3) / 4; // Equivalent to ceiling of l*3/4

    if n > b.len() {
        return Err(MatterError::ShortageError(format!(
            "Not enough bytes in {:?} to nab {} sextets.",
            b, l
        )));
    }

    // Extract the first n bytes and convert to a BigUint
    let bytes = &b[..n];
    let i = BigUint::from_bytes_be(bytes);

    // Calculate trailing bit size in bits
    let tbs = 2 * (l % 4);

    // Right shift out trailing bits to make right aligned
    let adjusted_i = if tbs > 0 { i >> tbs } else { i };

    let result = adjusted_i.to_u64().unwrap_or_else(|| 0);
    // Return as Base64
    Ok(int_to_b64(result as u32, l))
}

// Helper function to check if a string contains only Base64 characters
fn is_base64(s: &str) -> bool {
    s.chars().all(|c| {
        (c >= 'A' && c <= 'Z')
            || (c >= 'a' && c <= 'z')
            || (c >= '0' && c <= '9')
            || c == '+'
            || c == '/'
            || c == '-'
            || c == '_'
    })
}

impl Matter for BaseMatter {
    fn code(&self) -> &str {
        &self.code
    }

    fn raw(&self) -> &[u8] {
        &self.raw
    }

    fn qb64(&self) -> String {
        let result = self.infil();
        result.unwrap()
    }

    fn qb64b(&self) -> Vec<u8> {
        let result = self.infil();
        result.unwrap().into_bytes()
    }

    fn qb2(&self) -> Vec<u8> {
        let result = self.binfil();
        result.unwrap()
    }

    fn soft(&self) -> &str {
        &self.soft
    }

    /// Returns full size of matter in bytes
    ///
    /// Fixed size codes returns fs from .Sizes
    /// Variable size codes where fs==None computes fs from .size and sizes
    ///
    /// # Returns
    /// * `usize` - Full size in bytes
    fn full_size(&self) -> usize {
        // Extract sizes from the Sizes map using the code
        let sizes = get_sizes();
        let size = sizes[self.code.as_str()];
        let (hs, ss, fs) = (size.hs, size.ss, size.fs);

        // If fs is None, compute the full size
        match fs {
            Some(fixed_size) => fixed_size as usize,
            None => {
                // Compute fs from ss characters in code and self.size
                (hs + ss) as usize + (self.size() * 4)
            }
        }
    }

    fn size(&self) -> usize {
        let soft = self.soft();
        if soft.len() == 0 {
            0
        } else {
            b64_to_int(self.soft()) as usize
        }
    }

    fn is_transferable(&self) -> bool {
        !non_trans_dex::TUPLE.contains(&(self.code.as_str()))
    }

    fn is_digestive(&self) -> bool {
        dig_dex::TUPLE.contains(&(self.code.as_str()))
    }

    fn is_prefixive(&self) -> bool {
        pre_dex::TUPLE.contains(&(self.code.as_str()))
    }

    fn is_special(&self) -> bool {
        let sizes = get_sizes();
        let size = sizes[self.code.as_str()];

        match size.fs {
            Some(_) => size.ss > 0,
            None => false,
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

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

    #[test]
    fn test_base_matter_from_qb64() {
        // Given input qb64 string
        let qb64 = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";

        // Expected raw value (in Rust byte string)
        let expected_raw =
            b"iN\x89Gi\xe6\xc3&~\x8bG|%\x90(L\xd6G\xddB\xef`\x07\xd2T\xfc\xe1\xcd.\x9b\xe4#";

        let prebin: [u8; 33] = [
            0x04, 0x69, 0x4E, 0x89, 0x47, 0x69, 0xE6, 0xC3, 0x26, 0x7E, 0x8B, 0x47, 0x7C, 0x25,
            0x90, 0x28, 0x4C, 0xD6, 0x47, 0xDD, 0x42, 0xEF, 0x60, 0x07, 0xD2, 0x54, 0xFC, 0xE1,
            0xCD, 0x2E, 0x9B, 0xE4, 0x23,
        ];

        // When converting from qb64
        let matter = BaseMatter::from_qb64(qb64).expect("Failed to create BaseMatter from qb64");

        assert_eq!(matter.raw(), expected_raw);
        assert_eq!(matter.code(), "B");
        assert_eq!(matter.qb64(), qb64);
        assert_eq!(matter.qb2(), prebin.to_vec());
    }

    #[test]
    fn test_base_matter_from_raw() {
        let raw = b"iN\x89Gi\xe6\xc3&~\x8bG|%\x90(L\xd6G\xddB\xef`\x07\xd2T\xfc\xe1\xcd.\x9b\xe4#";
        let prebin: [u8; 33] = [
            0x04, 0x69, 0x4E, 0x89, 0x47, 0x69, 0xE6, 0xC3, 0x26, 0x7E, 0x8B, 0x47, 0x7C, 0x25,
            0x90, 0x28, 0x4C, 0xD6, 0x47, 0xDD, 0x42, 0xEF, 0x60, 0x07, 0xD2, 0x54, 0xFC, 0xE1,
            0xCD, 0x2E, 0x9B, 0xE4, 0x23,
        ];

        let matter = BaseMatter::new(Some(raw), Some("B"), None, None).unwrap();
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.code(), "B");
        assert_eq!(
            matter.qb64(),
            "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj"
        );
        assert_eq!(matter.qb2(), prebin.to_vec());

        let matter1 = BaseMatter::from_raw(Some(raw)).unwrap();
        assert_eq!(matter1.raw(), raw);
        assert_eq!(matter1.code(), "B");
        assert_eq!(
            matter1.qb64(),
            "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj"
        );
        assert_eq!(matter1.qb2(), prebin.to_vec());

        let matter2 = BaseMatter::from_qb2(&mut prebin.to_vec(), None).unwrap();
        assert_eq!(matter2.raw(), raw);
        assert_eq!(matter2.code(), "B");
        assert_eq!(
            matter2.qb64(),
            "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj"
        );
    }

    #[test]
    fn test_matter_codex() {
        let sizes = get_sizes();
        // Test that MtrDex constants are defined correctly
        assert_eq!(mtr_dex::ED25519_SEED, "A");
        assert_eq!(mtr_dex::ED25519N, "B");
        assert_eq!(mtr_dex::X25519, "C");
        assert_eq!(mtr_dex::ED25519, "D");
        assert_eq!(mtr_dex::BLAKE3_256, "E");
        assert_eq!(mtr_dex::BLAKE2B_256, "F");
        assert_eq!(mtr_dex::BLAKE2S_256, "G");
        assert_eq!(mtr_dex::SHA3_256, "H");
        assert_eq!(mtr_dex::SHA2_256, "I");

        // Test that Sizage values are correct for some codes
        let size = sizes[mtr_dex::ED25519_SEED];
        assert_eq!(size.hs, 1);
        assert_eq!(size.ss, 0);
        assert_eq!(size.xs, 0);
        assert_eq!(size.fs, Some(44));
        assert_eq!(size.ls, 0);

        let size = sizes[mtr_dex::ED25519N];
        assert_eq!(size.hs, 1);
        assert_eq!(size.ss, 0);
        assert_eq!(size.xs, 0);
        assert_eq!(size.fs, Some(44));
        assert_eq!(size.ls, 0);

        let size = sizes[mtr_dex::BLAKE3_256];
        assert_eq!(size.hs, 1);
        assert_eq!(size.ss, 0);
        assert_eq!(size.xs, 0);
        assert_eq!(size.fs, Some(44));
        assert_eq!(size.ls, 0);

        // Test raw_size function
        assert_eq!(raw_size(mtr_dex::ED25519).unwrap(), 32);
        assert_eq!(raw_size(mtr_dex::ED25519N).unwrap(), 32);
        assert_eq!(raw_size(mtr_dex::BLAKE3_256).unwrap(), 32);
    }

    #[test]
    fn test_matter_basic() {
        // Test with empty material
        let result = BaseMatter::new(None, None, None, None);
        assert!(result.is_err());

        // Test with raw bytes but no code
        let verkey =
            b"iN\x89Gi\xe6\xc3&~\x8bG|%\x90(L\xd6G\xddB\xef`\x07\xd2T\xfc\xe1\xcd.\x9b\xe4#";
        let result = BaseMatter::new(Some(verkey), None, None, None);
        assert!(result.is_err());

        // Test with valid raw and code
        let result = BaseMatter::new(Some(verkey), Some(mtr_dex::ED25519N), None, None);
        assert!(result.is_ok());
        let matter = result.unwrap();
        assert_eq!(matter.code(), mtr_dex::ED25519N);
        assert_eq!(matter.raw(), verkey);

        // Test qb64 generation
        let qb64 = matter.qb64();
        assert_eq!(qb64, "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj");

        // Test from qb64
        let matter2 = BaseMatter::from_qb64(&qb64).unwrap();
        assert_eq!(matter2.code(), mtr_dex::ED25519N);
        assert_eq!(matter2.raw(), verkey);
        assert_eq!(matter2.qb64(), qb64);

        // Test qb2 generation and conversion
        let qb2 = matter.qb2();
        let matter3 = BaseMatter::from_qb2(&mut qb2.to_vec(), None).unwrap();
        assert_eq!(matter3.code(), mtr_dex::ED25519N);
        assert_eq!(matter3.raw(), verkey);
        assert_eq!(matter3.qb64(), qb64);

        // Test transferable property
        assert!(!matter.is_transferable());

        // Test with transferable code
        let result = BaseMatter::new(Some(verkey), Some(mtr_dex::ED25519), None, None);
        assert!(result.is_ok());
        let matter = result.unwrap();
        assert_eq!(matter.code(), mtr_dex::ED25519);
        assert!(matter.is_transferable());

        // Test digestive property
        assert!(!matter.is_digestive());

        // Test with digest code
        let digest = [0u8; 32];
        let result = BaseMatter::new(
            Some(digest.as_slice()),
            Some(mtr_dex::BLAKE3_256),
            None,
            None,
        );
        assert!(result.is_ok());
        let matter = result.unwrap();
        assert_eq!(matter.code(), mtr_dex::BLAKE3_256);
        assert!(matter.is_digestive());

        // Test prefixive property
        assert!(matter.is_prefixive());
    }

    #[test]
    fn test_matter_from_qb64() {
        let prefix = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
        let matter = BaseMatter::from_qb64(prefix).unwrap();
        assert_eq!(matter.code(), mtr_dex::ED25519N);
        assert_eq!(matter.qb64(), prefix);

        // Test with full identifier
        let both = format!("{}:mystuff/mypath/toresource?query=what#fragment", prefix);
        let matter = BaseMatter::from_qb64(&both).unwrap();
        assert_eq!(matter.code(), mtr_dex::ED25519N);
        assert_eq!(matter.qb64(), prefix);
        assert!(!matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(matter.is_prefixive());
    }

    #[test]
    fn test_matter_from_qb64b() {
        let prefix = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
        let mut prefixb = prefix.as_bytes().to_vec();
        let matter = BaseMatter::from_qb64b(&mut prefixb, None).unwrap();
        assert_eq!(matter.code(), mtr_dex::ED25519N);
        assert_eq!(matter.qb64(), prefix);

        // Test with full identifier
        let both = format!("{}:mystuff/mypath/toresource?query=what#fragment", prefix);
        let mut bothb = both.as_bytes().to_vec();
        let matter = BaseMatter::from_qb64b(&mut bothb, None).unwrap();
        assert_eq!(matter.code(), mtr_dex::ED25519N);
        assert_eq!(matter.qb64(), prefix);
        assert!(!matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(matter.is_prefixive());
    }

    #[test]
    fn test_matter_from_qb2() {
        let prefix = "BGlOiUdp5sMmfotHfCWQKEzWR91C72AH0lT84c0um-Qj";
        let matter = BaseMatter::from_qb64(prefix).unwrap();
        let mut qb2 = matter.qb2();

        let matter2 = BaseMatter::from_qb2(&mut qb2, None).unwrap();
        assert_eq!(matter2.code(), mtr_dex::ED25519N);
        assert_eq!(matter2.qb64(), prefix);
        assert!(!matter2.is_transferable());
        assert!(!matter2.is_digestive());
        assert!(matter2.is_prefixive());
    }

    #[test]
    fn test_matter_with_fixed_sizes() {
        // Test TBD0 code with fixed size and lead size 0
        let code = mtr_dex::TBD0;
        let raw = b"abc";
        let qb64 = "1___YWJj";

        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(!matter.is_prefixive());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.raw(), raw);

        // Test TBD1 code with fixed size and lead size 1
        let code = mtr_dex::TBD1;
        let raw = b"ab";
        let qb64 = "2___AGFi";

        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(!matter.is_prefixive());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.raw(), raw);

        // Test TBD2 code with fixed size and lead size 2
        let code = mtr_dex::TBD2;
        let raw = b"z";
        let qb64 = "3___AAB6";

        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(!matter.is_prefixive());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.raw(), raw);
    }

    #[test]
    fn test_matter_with_variable_sizes() {
        // Test Bytes_L0 code with variable size and lead size 0
        let code = mtr_dex::BYTES_L0;
        let raw = b"abcdef";
        let qb64 = "4BACYWJjZGVm";

        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(!matter.is_prefixive());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.raw(), raw);

        // Test Bytes_L1 code with variable size and lead size 1
        let code = mtr_dex::BYTES_L1;
        let raw = b"abcde";
        let qb64 = "5BACAGFiY2Rl";

        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(!matter.is_prefixive());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.raw(), raw);

        // Test Bytes_L2 code with variable size and lead size 2
        let code = mtr_dex::BYTES_L2;
        let raw = b"abcd";
        let qb64 = "6BACAABhYmNk";

        let matter = BaseMatter::new(Some(raw), Some(code), None, None).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_transferable());
        assert!(!matter.is_digestive());
        assert!(!matter.is_prefixive());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.raw(), raw);
    }

    #[test]
    fn test_matter_with_special_codes() {
        // Test Tag3 code with special soft value
        let code = mtr_dex::TAG3;
        let soft = "icp";
        let qb64 = "Xicp";
        let raw = b"";

        let matter = BaseMatter::from_soft_and_code(soft, code).unwrap();
        assert_eq!(matter.code(), code);
        assert_eq!(matter.soft.as_str(), soft);
        assert_eq!(matter.raw(), raw);
        assert_eq!(matter.qb64(), qb64);
        assert!(matter.is_special());

        let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        assert_eq!(matter2.code(), code);
        assert_eq!(matter2.soft.as_str(), soft);
        assert_eq!(matter2.raw(), raw);

        // Test TBD0S code with special soft value and non-empty raw
        // let code = mtr_dex::TBD0S;
        // let soft = "TG";
        // let raw = b"uvwx";
        // let qb64 = "1__-TGB1dnd4";
        //
        // let matter = BaseMatter::from_soft_and_code(soft, code).unwrap();
        // assert_eq!(matter.code(), code);
        // assert_eq!(matter.soft, soft);
        // assert_eq!(matter.raw(), b"");
        // assert_eq!(matter.qb64(), qb64);
        // assert!(matter.is_special());
        //
        // let matter2 = BaseMatter::from_qb64(qb64).unwrap();
        // assert_eq!(matter2.code(), code);
        // assert_eq!(matter2.soft, soft);
        // assert_eq!(matter2.raw(), raw);
    }

    #[test]
    fn test_versionage_from_string() {
        // Valid version string
        let version_str = "KERI10JSON000000_".to_string();
        let versionage = Versionage::from(version_str);
        assert_eq!(versionage.major, 1);
        assert_eq!(versionage.minor, 0);

        // Version with different numbers
        let version_str = "KERI25CBOR000123_".to_string();
        let versionage = Versionage::from(version_str);
        assert_eq!(versionage.major, 2);
        assert_eq!(versionage.minor, 5);

        // Reference implementation
        let version_str = "KERI10JSON000000_";
        let versionage = Versionage::from(version_str);
        assert_eq!(versionage.major, 1);
        assert_eq!(versionage.minor, 0);
    }

    #[test]
    fn test_parse_version_string() {
        // Valid version string
        let result = Versionage::parse_version_string("KERI10JSON000000_");
        assert!(result.is_ok());
        let versionage = result.unwrap();
        assert_eq!(versionage.major, 1);
        assert_eq!(versionage.minor, 0);

        // Invalid prefix
        let result = Versionage::parse_version_string("XERI10JSON000000_");
        assert!(result.is_err());

        // Too short
        let result = Versionage::parse_version_string("KERI");
        assert!(result.is_err());

        // Invalid hex digits
        let result = Versionage::parse_version_string("KERIGZJSON000000_");
        assert!(result.is_err());
    }
}