zakura-keys 5.4.0

Zcash key and address management
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
//! Helper functions for managing light client key material.
#[cfg(feature = "transparent-inputs")]
use ::transparent::keys::TransparentKeyScope;
#[cfg(feature = "zip32-addresses")]
use alloc::collections::BTreeSet;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt::{self, Display};
use nonempty::NonEmpty;

use zcash_address::unified::{self, Container, Encoding, Typecode, Ufvk, Uivk};
use zcash_protocol::{PoolType, consensus};
use zip32::{AccountId, DiversifierIndex};

#[cfg(feature = "zip32-addresses")]
use crate::address::UnifiedAddress;

#[cfg(any(feature = "sapling", feature = "orchard"))]
use zcash_protocol::consensus::NetworkConstants;

#[cfg(feature = "transparent-inputs")]
use {
    ::transparent::keys::{IncomingViewingKey, NonHardenedChildIndex},
    core::convert::TryInto,
};

#[cfg(all(
    feature = "transparent-inputs",
    any(test, feature = "test-dependencies")
))]
use ::transparent::address::TransparentAddress;

#[cfg(feature = "unstable")]
use {
    byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt},
    core::convert::TryFrom,
    corez::io::{Read, Write},
    zcash_protocol::consensus::BranchId,
    zcash_protocol::encoding::CompactSize,
};

#[cfg(feature = "orchard")]
use orchard::{self, keys::Scope};

#[cfg(all(feature = "sapling", feature = "unstable"))]
use ::sapling::zip32::ExtendedFullViewingKey;

#[cfg(feature = "sapling")]
pub mod sapling {
    pub use sapling::zip32::{
        DiversifiableFullViewingKey, ExtendedFullViewingKey, ExtendedSpendingKey,
    };
    use zip32::{AccountId, ChildIndex};

    /// Derives the ZIP 32 [`ExtendedSpendingKey`] for a given coin type and account from the
    /// given seed.
    ///
    /// # Panics
    ///
    /// Panics if `seed` is shorter than 32 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use zcash_protocol::constants::testnet::COIN_TYPE;
    /// use zcash_keys::keys::sapling;
    /// use zip32::AccountId;
    ///
    /// let extsk = sapling::spending_key(&[0; 32][..], COIN_TYPE, AccountId::ZERO);
    /// ```
    /// [`ExtendedSpendingKey`]: sapling::zip32::ExtendedSpendingKey
    pub fn spending_key(seed: &[u8], coin_type: u32, account: AccountId) -> ExtendedSpendingKey {
        if seed.len() < 32 {
            panic!("ZIP 32 seeds MUST be at least 32 bytes");
        }

        ExtendedSpendingKey::from_path(
            &ExtendedSpendingKey::master(seed),
            &[
                ChildIndex::hardened(32),
                ChildIndex::hardened(coin_type),
                account.into(),
            ],
        )
    }
}

#[cfg(any(feature = "transparent-key-encoding", feature = "transparent-inputs"))]
pub mod transparent;

#[cfg(feature = "zcashd-compat")]
pub mod zcashd;

#[cfg(all(feature = "transparent-inputs", feature = "zip32-addresses"))]
fn to_transparent_child_index(j: DiversifierIndex) -> Option<NonHardenedChildIndex> {
    let (low_4_bytes, rest) = j.as_bytes().split_at(4);
    let transparent_j = u32::from_le_bytes(low_4_bytes.try_into().unwrap());
    if rest.iter().any(|b| b != &0) {
        None
    } else {
        NonHardenedChildIndex::from_index(transparent_j)
    }
}

#[derive(Debug)]
pub enum DerivationError {
    #[cfg(feature = "orchard")]
    Orchard(orchard::zip32::Error),
    #[cfg(feature = "transparent-inputs")]
    Transparent(bip32::Error),
}

impl Display for DerivationError {
    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            #[cfg(feature = "orchard")]
            DerivationError::Orchard(e) => write!(_f, "Orchard error: {e}"),
            #[cfg(feature = "transparent-inputs")]
            DerivationError::Transparent(e) => write!(_f, "Transparent error: {e}"),
            #[cfg(not(any(feature = "orchard", feature = "transparent-inputs")))]
            other => {
                unreachable!("Unhandled DerivationError variant {:?}", other)
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DerivationError {}

/// A version identifier for the encoding of unified spending keys.
///
/// Each era corresponds to a range of block heights. During an era, the unified spending key
/// parsed from an encoded form tagged with that era's identifier is expected to provide
/// sufficient spending authority to spend any non-Sprout shielded note created in a transaction
/// within the era's block range.
#[cfg(feature = "unstable")]
#[derive(Debug, PartialEq, Eq)]
pub enum Era {
    /// The Orchard era begins at Orchard activation, and will end if a new pool that requires a
    /// change to unified spending keys is introduced.
    Orchard,
}

/// A type for errors that can occur when decoding keys from their serialized representations.
#[derive(Debug, PartialEq, Eq)]
pub enum DecodingError {
    #[cfg(feature = "unstable")]
    ReadError(&'static str),
    #[cfg(feature = "unstable")]
    EraInvalid,
    #[cfg(feature = "unstable")]
    EraMismatch(Era),
    #[cfg(feature = "unstable")]
    TypecodeInvalid,
    #[cfg(feature = "unstable")]
    LengthInvalid,
    #[cfg(feature = "unstable")]
    LengthMismatch(Typecode, u32),
    #[cfg(feature = "unstable")]
    InsufficientData(Typecode),
    /// The key data could not be decoded from its string representation to a valid key.
    KeyDataInvalid(Typecode),
}

impl core::fmt::Display for DecodingError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            #[cfg(feature = "unstable")]
            DecodingError::ReadError(s) => write!(f, "Read error: {s}"),
            #[cfg(feature = "unstable")]
            DecodingError::EraInvalid => write!(f, "Invalid era"),
            #[cfg(feature = "unstable")]
            DecodingError::EraMismatch(e) => write!(f, "Era mismatch: actual {e:?}"),
            #[cfg(feature = "unstable")]
            DecodingError::TypecodeInvalid => write!(f, "Invalid typecode"),
            #[cfg(feature = "unstable")]
            DecodingError::LengthInvalid => write!(f, "Invalid length"),
            #[cfg(feature = "unstable")]
            DecodingError::LengthMismatch(t, l) => {
                write!(f, "Length mismatch: received {l} bytes for typecode {t:?}")
            }
            #[cfg(feature = "unstable")]
            DecodingError::InsufficientData(t) => {
                write!(f, "Insufficient data for typecode {t:?}")
            }
            DecodingError::KeyDataInvalid(t) => write!(f, "Invalid key data for key type {t:?}"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DecodingError {}

#[cfg(feature = "unstable")]
impl Era {
    /// Returns the unique identifier for the era.
    fn id(&self) -> u32 {
        // We use the consensus branch id of the network upgrade that introduced a
        // new USK format as the identifier for the era.
        match self {
            Era::Orchard => u32::from(BranchId::Nu5),
        }
    }

    fn try_from_id(id: u32) -> Option<Self> {
        BranchId::try_from(id).ok().and_then(|b| match b {
            BranchId::Nu5 => Some(Era::Orchard),
            _ => None,
        })
    }
}

/// A set of spending keys that are all associated with a single ZIP-0032 account identifier.
#[derive(Clone)]
pub struct UnifiedSpendingKey {
    #[cfg(feature = "transparent-inputs")]
    transparent: ::transparent::keys::AccountPrivKey,
    #[cfg(feature = "sapling")]
    sapling: sapling::ExtendedSpendingKey,
    #[cfg(feature = "orchard")]
    orchard: orchard::keys::SpendingKey,
}

impl core::fmt::Debug for UnifiedSpendingKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut d = f.debug_struct("UnifiedSpendingKey");
        #[cfg(feature = "transparent-inputs")]
        d.field("transparent", &"...");
        #[cfg(feature = "sapling")]
        d.field("sapling", &"...");
        #[cfg(feature = "orchard")]
        d.field("orchard", &"...");
        d.finish()
    }
}

impl UnifiedSpendingKey {
    pub fn from_seed<P: consensus::Parameters>(
        _params: &P,
        seed: &[u8],
        _account: AccountId,
    ) -> Result<UnifiedSpendingKey, DerivationError> {
        if seed.len() < 32 {
            panic!("ZIP 32 seeds MUST be at least 32 bytes");
        }

        UnifiedSpendingKey::from_checked_parts(
            #[cfg(feature = "transparent-inputs")]
            ::transparent::keys::AccountPrivKey::from_seed(_params, seed, _account)
                .map_err(DerivationError::Transparent)?,
            #[cfg(feature = "sapling")]
            sapling::spending_key(seed, _params.coin_type(), _account),
            #[cfg(feature = "orchard")]
            orchard::keys::SpendingKey::from_zip32_seed(seed, _params.coin_type(), _account)
                .map_err(DerivationError::Orchard)?,
        )
    }

    /// Construct a USK from its constituent parts, after verifying that UIVK derivation can
    /// succeed.
    fn from_checked_parts(
        #[cfg(feature = "transparent-inputs")] transparent: ::transparent::keys::AccountPrivKey,
        #[cfg(feature = "sapling")] sapling: sapling::ExtendedSpendingKey,
        #[cfg(feature = "orchard")] orchard: orchard::keys::SpendingKey,
    ) -> Result<UnifiedSpendingKey, DerivationError> {
        // Verify that FVK and IVK derivation succeed; we don't want to construct a USK
        // that can't derive transparent addresses.
        #[cfg(feature = "transparent-inputs")]
        let _ = transparent.to_account_pubkey().derive_external_ivk()?;

        Ok(UnifiedSpendingKey {
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
        })
    }

    pub fn to_unified_full_viewing_key(&self) -> UnifiedFullViewingKey {
        UnifiedFullViewingKey {
            #[cfg(feature = "transparent-inputs")]
            transparent: Some(self.transparent.to_account_pubkey()),
            #[cfg(feature = "sapling")]
            sapling: Some(self.sapling.to_diversifiable_full_viewing_key()),
            #[cfg(feature = "orchard")]
            orchard: Some((&self.orchard).into()),
            unknown: vec![],
        }
    }

    /// Returns the transparent component of the unified key at the
    /// BIP44 path `m/44'/<coin_type>'/<account>'`.
    #[cfg(feature = "transparent-inputs")]
    pub fn transparent(&self) -> &::transparent::keys::AccountPrivKey {
        &self.transparent
    }

    /// Returns the Sapling extended spending key component of this unified spending key.
    #[cfg(feature = "sapling")]
    pub fn sapling(&self) -> &sapling::ExtendedSpendingKey {
        &self.sapling
    }

    /// Returns the Orchard spending key component of this unified spending key.
    #[cfg(feature = "orchard")]
    pub fn orchard(&self) -> &orchard::keys::SpendingKey {
        &self.orchard
    }

    /// Returns a binary encoding of this key suitable for decoding with [`Self::from_bytes`].
    ///
    /// The encoded form of a unified spending key is only intended for use
    /// within wallets when required for storage and/or crossing FFI boundaries;
    /// unified spending keys should not be exposed to users, and consequently
    /// no string-based encoding is defined. This encoding does not include any
    /// internal validation metadata (such as checksums) as keys decoded from
    /// this form will necessarily be validated when the attempt is made to
    /// spend a note that they have authority for.
    #[cfg(feature = "unstable")]
    pub fn to_bytes(&self, era: Era) -> Vec<u8> {
        let mut result = vec![];
        result.write_u32::<LittleEndian>(era.id()).unwrap();

        #[cfg(feature = "orchard")]
        {
            let orchard_key = self.orchard();
            CompactSize::write(&mut result, usize::try_from(Typecode::Orchard).unwrap()).unwrap();

            let orchard_key_bytes = orchard_key.to_bytes();
            CompactSize::write(&mut result, orchard_key_bytes.len()).unwrap();
            result.write_all(orchard_key_bytes).unwrap();
        }

        #[cfg(feature = "sapling")]
        {
            let sapling_key = self.sapling();
            CompactSize::write(&mut result, usize::try_from(Typecode::Sapling).unwrap()).unwrap();

            let sapling_key_bytes = sapling_key.to_bytes();
            CompactSize::write(&mut result, sapling_key_bytes.len()).unwrap();
            result.write_all(&sapling_key_bytes).unwrap();
        }

        #[cfg(feature = "transparent-inputs")]
        {
            let account_tkey = self.transparent();
            CompactSize::write(&mut result, usize::try_from(Typecode::P2pkh).unwrap()).unwrap();

            let account_tkey_bytes = account_tkey.to_bytes();
            CompactSize::write(&mut result, account_tkey_bytes.len()).unwrap();
            result.write_all(&account_tkey_bytes).unwrap();
        }

        result
    }

    /// Decodes a [`UnifiedSpendingKey`] value from its serialized representation.
    ///
    /// See [`Self::to_bytes`] for additional detail about the encoded form.
    #[allow(clippy::unnecessary_unwrap)]
    #[cfg(feature = "unstable")]
    pub fn from_bytes(era: Era, encoded: &[u8]) -> Result<Self, DecodingError> {
        let mut source = corez::io::Cursor::new(encoded);
        let decoded_era = source
            .read_u32::<LittleEndian>()
            .map_err(|_| DecodingError::ReadError("era"))
            .and_then(|id| Era::try_from_id(id).ok_or(DecodingError::EraInvalid))?;

        if decoded_era != era {
            return Err(DecodingError::EraMismatch(decoded_era));
        }

        #[cfg(feature = "orchard")]
        let mut orchard = None;
        #[cfg(feature = "sapling")]
        let mut sapling = None;
        #[cfg(feature = "transparent-inputs")]
        let mut transparent = None;
        loop {
            let tc = CompactSize::read_t::<_, u32>(&mut source)
                .map_err(|_| DecodingError::ReadError("typecode"))
                .and_then(|v| Typecode::try_from(v).map_err(|_| DecodingError::TypecodeInvalid))?;

            let len = CompactSize::read_t::<_, u32>(&mut source)
                .map_err(|_| DecodingError::ReadError("key length"))?;

            match tc {
                Typecode::Orchard => {
                    if len != 32 {
                        return Err(DecodingError::LengthMismatch(Typecode::Orchard, len));
                    }

                    let mut key = [0u8; 32];
                    source
                        .read_exact(&mut key)
                        .map_err(|_| DecodingError::InsufficientData(Typecode::Orchard))?;

                    #[cfg(feature = "orchard")]
                    {
                        orchard = Some(
                            Option::<orchard::keys::SpendingKey>::from(
                                orchard::keys::SpendingKey::from_bytes(key),
                            )
                            .ok_or(DecodingError::KeyDataInvalid(Typecode::Orchard))?,
                        );
                    }
                }
                Typecode::Sapling => {
                    if len != 169 {
                        return Err(DecodingError::LengthMismatch(Typecode::Sapling, len));
                    }

                    let mut key = [0u8; 169];
                    source
                        .read_exact(&mut key)
                        .map_err(|_| DecodingError::InsufficientData(Typecode::Sapling))?;

                    #[cfg(feature = "sapling")]
                    {
                        sapling = Some(
                            sapling::ExtendedSpendingKey::from_bytes(&key)
                                .map_err(|_| DecodingError::KeyDataInvalid(Typecode::Sapling))?,
                        );
                    }
                }
                Typecode::P2pkh => {
                    if len != 74 {
                        return Err(DecodingError::LengthMismatch(Typecode::P2pkh, len));
                    }

                    let mut key = [0u8; 74];
                    source
                        .read_exact(&mut key)
                        .map_err(|_| DecodingError::InsufficientData(Typecode::P2pkh))?;

                    #[cfg(feature = "transparent-inputs")]
                    {
                        transparent = Some(
                            ::transparent::keys::AccountPrivKey::from_bytes(&key)
                                .ok_or(DecodingError::KeyDataInvalid(Typecode::P2pkh))?,
                        );
                    }
                }
                _ => {
                    return Err(DecodingError::TypecodeInvalid);
                }
            }

            #[cfg(feature = "orchard")]
            let has_orchard = orchard.is_some();
            #[cfg(not(feature = "orchard"))]
            let has_orchard = true;

            #[cfg(feature = "sapling")]
            let has_sapling = sapling.is_some();
            #[cfg(not(feature = "sapling"))]
            let has_sapling = true;

            #[cfg(feature = "transparent-inputs")]
            let has_transparent = transparent.is_some();
            #[cfg(not(feature = "transparent-inputs"))]
            let has_transparent = true;

            if has_orchard && has_sapling && has_transparent {
                return UnifiedSpendingKey::from_checked_parts(
                    #[cfg(feature = "transparent-inputs")]
                    transparent.unwrap(),
                    #[cfg(feature = "sapling")]
                    sapling.unwrap(),
                    #[cfg(feature = "orchard")]
                    orchard.unwrap(),
                )
                .map_err(|_| DecodingError::KeyDataInvalid(Typecode::P2pkh));
            }
        }
    }

    /// Returns the unified address corresponding to the smallest valid diversifier index,
    /// along with that diversifier index.
    ///
    /// See [`UnifiedFullViewingKey::default_address`] for additional details.
    #[cfg(any(test, feature = "test-dependencies"))]
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn default_address(
        &self,
        request: UnifiedAddressRequest,
    ) -> (UnifiedAddress, DiversifierIndex) {
        self.to_unified_full_viewing_key()
            .default_address(request)
            .unwrap()
    }

    /// Returns the default external transparent address using the transparent account pubkey.
    ///
    /// See [`ExternalIvk::default_address`] for more information.
    ///
    /// [`ExternalIvk::default_address`]: ::transparent::keys::ExternalIvk::default_address
    #[cfg(all(
        feature = "transparent-inputs",
        any(test, feature = "test-dependencies")
    ))]
    pub fn default_transparent_address(&self) -> (TransparentAddress, NonHardenedChildIndex) {
        self.transparent()
            .to_account_pubkey()
            .derive_external_ivk()
            .unwrap()
            .default_address()
    }
}

/// Errors that can occur in the generation of unified addresses.
#[derive(Clone, Debug)]
pub enum AddressGenerationError {
    /// The requested diversifier index was outside the range of valid transparent
    /// child address indices.
    #[cfg(feature = "transparent-inputs")]
    InvalidTransparentChildIndex(DiversifierIndex),
    /// The requested key scope is not supported for address derivation.
    #[cfg(feature = "transparent-inputs")]
    UnsupportedTransparentKeyScope(TransparentKeyScope),
    /// An error occurred in [`bip32`] derivation of a transparent address.
    #[cfg(feature = "transparent-inputs")]
    Bip32DerivationError(bip32::Error),
    /// The diversifier index could not be mapped to a valid Sapling diversifier.
    #[cfg(feature = "sapling")]
    InvalidSaplingDiversifierIndex(DiversifierIndex),
    /// The space of available diversifier indices has been exhausted.
    DiversifierSpaceExhausted,
    /// A requested address typecode was not recognized, so we are unable to generate the address
    /// as requested.
    ReceiverTypeNotSupported(Typecode),
    /// A requested address typecode was recognized, but the unified key being used to generate the
    /// address lacks an item of the requested type.
    KeyNotAvailable(Typecode),
    /// A Unified address cannot be generated without at least one shielded receiver being
    /// included.
    ShieldedReceiverRequired,
}

impl fmt::Display for AddressGenerationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self {
            #[cfg(feature = "transparent-inputs")]
            AddressGenerationError::InvalidTransparentChildIndex(i) => {
                write!(
                    f,
                    "Child index {i:?} does not generate a valid transparent receiver"
                )
            }
            #[cfg(feature = "transparent-inputs")]
            AddressGenerationError::UnsupportedTransparentKeyScope(i) => {
                write!(f, "Key scope {i:?} is not supported for key derivation")
            }
            #[cfg(feature = "transparent-inputs")]
            AddressGenerationError::Bip32DerivationError(e) => {
                write!(f, "{e}")
            }
            #[cfg(feature = "sapling")]
            AddressGenerationError::InvalidSaplingDiversifierIndex(i) => {
                write!(
                    f,
                    "Child index {i:?} does not generate a valid Sapling receiver"
                )
            }
            AddressGenerationError::DiversifierSpaceExhausted => {
                write!(
                    f,
                    "Exhausted the space of diversifier indices without finding an address."
                )
            }
            AddressGenerationError::ReceiverTypeNotSupported(t) => {
                write!(
                    f,
                    "Unified Address generation does not yet support receivers of type {t:?}."
                )
            }
            AddressGenerationError::KeyNotAvailable(t) => {
                write!(
                    f,
                    "The Unified Viewing Key does not contain a key for typecode {t:?}."
                )
            }
            AddressGenerationError::ShieldedReceiverRequired => {
                write!(
                    f,
                    "A Unified Address requires at least one shielded (Sapling or Orchard) receiver."
                )
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for AddressGenerationError {}

#[cfg(feature = "transparent-inputs")]
impl From<bip32::Error> for AddressGenerationError {
    fn from(value: bip32::Error) -> Self {
        AddressGenerationError::Bip32DerivationError(value)
    }
}

/// An error type for failures in combining [`ReceiverRequirement`] values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReceiverRequirementError {
    /// The two requirements are incompatible: one requires inclusion and the other requires
    /// omission.
    Conflict,
    /// A set of receiver requirements would not include any shielded receiver.
    NoShieldedReceiver,
}

impl Display for ReceiverRequirementError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ReceiverRequirementError::Conflict => {
                write!(f, "Require and Omit receiver requirements are incompatible")
            }
            ReceiverRequirementError::NoShieldedReceiver => {
                write!(
                    f,
                    "A unified address must include at least one shielded receiver"
                )
            }
        }
    }
}

/// An enumeration of the ways in which a receiver may be requested to be present in a generated
/// [`crate::address::UnifiedAddress`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReceiverRequirement {
    /// A receiver of the associated type is required to be present in the generated
    /// `[UnifiedAddress`], and if it is not possible to generate a receiver of this type, the
    /// address generation method should return an error. When calling [`Self::intersect`], this
    /// variant will be preferred over [`ReceiverRequirement::Allow`].
    Require,
    /// The associated receiver should be included, if a corresponding item exists in the IVK from
    /// which the address is being derived and derivation of the receiver succeeds at the given
    /// diversifier index.
    Allow,
    /// No receiver of the associated type may be included in the generated [`crate::address::UnifiedAddress`]
    /// under any circumstances. When calling [`Self::intersect`], this variant will be preferred
    /// over [`ReceiverRequirement::Allow`].
    Omit,
}

impl ReceiverRequirement {
    /// Return the intersection of two requirements that chooses the stronger requirement, if one
    /// exists. [`ReceiverRequirement::Require`] and [`ReceiverRequirement::Omit`] are
    /// incompatible; attempting an intersection between these will return an error.
    pub fn intersect(self, other: Self) -> Result<Self, ReceiverRequirementError> {
        use ReceiverRequirement::*;
        match (self, other) {
            (Require, Omit) | (Omit, Require) => Err(ReceiverRequirementError::Conflict),
            (Require, Require) | (Require, Allow) | (Allow, Require) => Ok(Require),
            (Allow, Allow) => Ok(Allow),
            (Allow, Omit) | (Omit, Allow) | (Omit, Omit) => Ok(Omit),
        }
    }
}

/// Specification for how a unified address should be generated from a unified viewing key.
#[derive(Clone, Copy, Debug)]
pub enum UnifiedAddressRequest {
    AllAvailableKeys,
    Custom(ReceiverRequirements),
}

impl UnifiedAddressRequest {
    /// Constructs a new unified address request that allows a receiver of each type.
    pub const ALLOW_ALL: Self = Self::Custom(ReceiverRequirements::ALLOW_ALL);

    /// Constructs a new unified address request that allows only shielded receivers.
    pub const SHIELDED: Self = Self::Custom(ReceiverRequirements::SHIELDED);

    /// Constructs a new unified address request that requires an Orchard receiver and no others.
    pub const ORCHARD: Self = Self::Custom(ReceiverRequirements::ORCHARD);

    pub fn custom(
        orchard: ReceiverRequirement,
        sapling: ReceiverRequirement,
        p2pkh: ReceiverRequirement,
    ) -> Result<Self, ReceiverRequirementError> {
        ReceiverRequirements::new(orchard, sapling, p2pkh).map(UnifiedAddressRequest::Custom)
    }

    pub const fn unsafe_custom(
        orchard: ReceiverRequirement,
        sapling: ReceiverRequirement,
        p2pkh: ReceiverRequirement,
    ) -> Self {
        UnifiedAddressRequest::Custom(ReceiverRequirements::unsafe_new(orchard, sapling, p2pkh))
    }
}

/// Specification for how a unified address should be generated from a unified viewing key.
#[derive(Clone, Copy, Debug)]
pub struct ReceiverRequirements {
    orchard: ReceiverRequirement,
    sapling: ReceiverRequirement,
    p2pkh: ReceiverRequirement,
}

impl ReceiverRequirements {
    /// Construct a new unified address request from its constituent parts.
    ///
    /// Returns an error if the resulting unified address would not include at least one shielded
    /// receiver.
    pub fn new(
        orchard: ReceiverRequirement,
        sapling: ReceiverRequirement,
        p2pkh: ReceiverRequirement,
    ) -> Result<Self, ReceiverRequirementError> {
        use ReceiverRequirement::*;
        if orchard == Omit && sapling == Omit {
            Err(ReceiverRequirementError::NoShieldedReceiver)
        } else {
            Ok(Self {
                orchard,
                sapling,
                p2pkh,
            })
        }
    }

    /// Constructs a new unified address request that allows a receiver of each type.
    pub const ALLOW_ALL: ReceiverRequirements = {
        use ReceiverRequirement::*;
        Self::unsafe_new(Allow, Allow, Allow)
    };

    /// Constructs a new unified address request that allows only shielded receivers.
    pub const SHIELDED: ReceiverRequirements = {
        use ReceiverRequirement::*;
        Self::unsafe_new(Allow, Allow, Omit)
    };

    /// Constructs a new unified address request that requires an Orchard receiver, and no others.
    pub const ORCHARD: ReceiverRequirements = {
        use ReceiverRequirement::*;
        Self::unsafe_new(Require, Omit, Omit)
    };

    /// Constructs a new unified address request that includes only the receivers that are allowed
    /// both in itself and a given other request. Returns an error if requirements are incompatible
    /// or if no shielded receiver type is allowed.
    pub fn intersect(
        &self,
        other: &ReceiverRequirements,
    ) -> Result<ReceiverRequirements, ReceiverRequirementError> {
        let orchard = self.orchard.intersect(other.orchard)?;
        let sapling = self.sapling.intersect(other.sapling)?;
        let p2pkh = self.p2pkh.intersect(other.p2pkh)?;
        Self::new(orchard, sapling, p2pkh)
    }

    /// Construct a new unified address request from its constituent parts.
    ///
    /// Panics: at least one of `orchard` or `sapling` must be allowed.
    pub const fn unsafe_new(
        orchard: ReceiverRequirement,
        sapling: ReceiverRequirement,
        p2pkh: ReceiverRequirement,
    ) -> Self {
        use ReceiverRequirement::*;
        if matches!(orchard, Omit) && matches!(sapling, Omit) {
            panic!("At least one shielded receiver must be allowed.")
        }

        Self {
            orchard,
            sapling,
            p2pkh,
        }
    }

    /// Returns the [`ReceiverRequirement`] for inclusion of an Orchard receiver.
    pub fn orchard(&self) -> ReceiverRequirement {
        self.orchard
    }

    /// Returns the [`ReceiverRequirement`] for inclusion of a Sapling receiver.
    pub fn sapling(&self) -> ReceiverRequirement {
        self.sapling
    }

    /// Returns the [`ReceiverRequirement`] for inclusion of a P2PKH receiver.
    pub fn p2pkh(&self) -> ReceiverRequirement {
        self.p2pkh
    }
}

#[cfg(feature = "transparent-inputs")]
impl From<bip32::Error> for DerivationError {
    fn from(e: bip32::Error) -> Self {
        DerivationError::Transparent(e)
    }
}

/// A key that provides the capability to recover outgoing transaction information from
/// the block chain.
#[derive(Clone, Copy)]
pub struct OutgoingViewingKey([u8; 32]);

impl core::fmt::Debug for OutgoingViewingKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_tuple("OutgoingViewingKey").field(&"...").finish()
    }
}

impl From<[u8; 32]> for OutgoingViewingKey {
    fn from(ovk: [u8; 32]) -> Self {
        OutgoingViewingKey(ovk)
    }
}

#[cfg(feature = "sapling")]
impl From<OutgoingViewingKey> for ::sapling::keys::OutgoingViewingKey {
    fn from(value: OutgoingViewingKey) -> Self {
        ::sapling::keys::OutgoingViewingKey(value.0)
    }
}

#[cfg(feature = "sapling")]
impl From<::sapling::keys::OutgoingViewingKey> for OutgoingViewingKey {
    fn from(value: ::sapling::keys::OutgoingViewingKey) -> Self {
        OutgoingViewingKey(value.0)
    }
}

#[cfg(feature = "orchard")]
impl From<OutgoingViewingKey> for ::orchard::keys::OutgoingViewingKey {
    fn from(value: OutgoingViewingKey) -> Self {
        ::orchard::keys::OutgoingViewingKey::from(value.0)
    }
}

#[cfg(feature = "orchard")]
impl From<::orchard::keys::OutgoingViewingKey> for OutgoingViewingKey {
    fn from(value: ::orchard::keys::OutgoingViewingKey) -> Self {
        OutgoingViewingKey(*value.as_ref())
    }
}

impl AsRef<[u8; 32]> for OutgoingViewingKey {
    fn as_ref(&self) -> &[u8; 32] {
        &self.0
    }
}

/// A [ZIP 316](https://zips.z.cash/zip-0316) unified full viewing key.
#[derive(Clone)]
pub struct UnifiedFullViewingKey {
    #[cfg(feature = "transparent-inputs")]
    transparent: Option<::transparent::keys::AccountPubKey>,
    #[cfg(feature = "sapling")]
    sapling: Option<sapling::DiversifiableFullViewingKey>,
    #[cfg(feature = "orchard")]
    orchard: Option<orchard::keys::FullViewingKey>,
    unknown: Vec<(u32, Vec<u8>)>,
}

impl core::fmt::Debug for UnifiedFullViewingKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut d = f.debug_struct("UnifiedFullViewingKey");
        #[cfg(feature = "transparent-inputs")]
        d.field("transparent", &self.transparent.as_ref().map(|_| "..."));
        #[cfg(feature = "sapling")]
        d.field("sapling", &self.sapling.as_ref().map(|_| "..."));
        #[cfg(feature = "orchard")]
        d.field("orchard", &self.orchard.as_ref().map(|_| "..."));
        d.field(
            "unknown_typecodes",
            &self
                .unknown
                .iter()
                .map(|(typecode, _)| *typecode)
                .collect::<Vec<_>>(),
        )
        .finish()
    }
}

impl UnifiedFullViewingKey {
    /// Construct a new unified full viewing key.
    ///
    /// This method is only available when the `test-dependencies` feature is enabled,
    /// as derivation from the USK or deserialization from the serialized form should
    /// be used instead.
    #[cfg(any(test, feature = "test-dependencies"))]
    pub fn new(
        #[cfg(feature = "transparent-inputs")] transparent: Option<
            ::transparent::keys::AccountPubKey,
        >,
        #[cfg(feature = "sapling")] sapling: Option<sapling::DiversifiableFullViewingKey>,
        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::FullViewingKey>,
        // TODO: Implement construction of UFVKs with metadata items.
    ) -> Result<UnifiedFullViewingKey, DerivationError> {
        Self::from_checked_parts(
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            // We don't currently allow constructing new UFVKs with unknown items, but we store
            // this to allow parsing such UFVKs.
            vec![],
        )
    }

    #[cfg(feature = "unstable-frost")]
    pub fn from_orchard_fvk(
        orchard: orchard::keys::FullViewingKey,
    ) -> Result<UnifiedFullViewingKey, DerivationError> {
        Self::from_checked_parts(
            #[cfg(feature = "transparent-inputs")]
            None,
            #[cfg(feature = "sapling")]
            None,
            #[cfg(feature = "orchard")]
            Some(orchard),
            // We don't currently allow constructing new UFVKs with unknown items, but we store
            // this to allow parsing such UFVKs.
            vec![],
        )
    }

    #[cfg(all(feature = "sapling", feature = "unstable"))]
    pub fn from_sapling_extended_full_viewing_key(
        sapling: ExtendedFullViewingKey,
    ) -> Result<UnifiedFullViewingKey, DerivationError> {
        Self::from_checked_parts(
            #[cfg(feature = "transparent-inputs")]
            None,
            #[cfg(feature = "sapling")]
            Some(sapling.to_diversifiable_full_viewing_key()),
            #[cfg(feature = "orchard")]
            None,
            // We don't currently allow constructing new UFVKs with unknown items, but we store
            // this to allow parsing such UFVKs.
            vec![],
        )
    }

    /// Construct a UFVK from its constituent parts, after verifying that UIVK derivation can
    /// succeed.
    fn from_checked_parts(
        #[cfg(feature = "transparent-inputs")] transparent: Option<
            ::transparent::keys::AccountPubKey,
        >,
        #[cfg(feature = "sapling")] sapling: Option<sapling::DiversifiableFullViewingKey>,
        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::FullViewingKey>,
        unknown: Vec<(u32, Vec<u8>)>,
    ) -> Result<UnifiedFullViewingKey, DerivationError> {
        // Verify that IVK derivation succeeds; we don't want to construct a UFVK
        // that can't derive transparent addresses.
        #[cfg(feature = "transparent-inputs")]
        let _ = transparent
            .as_ref()
            .map(|t| t.derive_external_ivk())
            .transpose()?;

        Ok(UnifiedFullViewingKey {
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            unknown,
        })
    }

    /// Parses a `UnifiedFullViewingKey` from its [ZIP 316] string encoding.
    ///
    /// [ZIP 316]: https://zips.z.cash/zip-0316
    pub fn decode<P: consensus::Parameters>(params: &P, encoding: &str) -> Result<Self, String> {
        let (net, ufvk) = unified::Ufvk::decode(encoding).map_err(|e| e.to_string())?;
        let expected_net = params.network_type();
        if net != expected_net {
            return Err(format!(
                "UFVK is for network {net:?} but we expected {expected_net:?}",
            ));
        }

        Self::parse(&ufvk).map_err(|e| e.to_string())
    }

    /// Parses a `UnifiedFullViewingKey` from its [ZIP 316] string encoding.
    ///
    /// [ZIP 316]: https://zips.z.cash/zip-0316
    pub fn parse(ufvk: &Ufvk) -> Result<Self, DecodingError> {
        #[cfg(feature = "orchard")]
        let mut orchard = None;
        #[cfg(feature = "sapling")]
        let mut sapling = None;
        #[cfg(feature = "transparent-inputs")]
        let mut transparent = None;

        // We can use as-parsed order here for efficiency, because we're breaking out the
        // receivers we support from the unknown receivers.
        let unknown = ufvk
            .items_as_parsed()
            .iter()
            .filter_map(|receiver| match receiver {
                #[cfg(feature = "orchard")]
                unified::Fvk::Orchard(data) => orchard::keys::FullViewingKey::from_bytes(data)
                    .ok_or(DecodingError::KeyDataInvalid(Typecode::Orchard))
                    .map(|addr| {
                        orchard = Some(addr);
                        None
                    })
                    .transpose(),
                #[cfg(not(feature = "orchard"))]
                unified::Fvk::Orchard(data) => Some(Ok::<_, DecodingError>((
                    u32::from(unified::Typecode::Orchard),
                    data.to_vec(),
                ))),
                #[cfg(feature = "sapling")]
                unified::Fvk::Sapling(data) => {
                    sapling::DiversifiableFullViewingKey::from_bytes(data)
                        .ok_or(DecodingError::KeyDataInvalid(Typecode::Sapling))
                        .map(|pa| {
                            sapling = Some(pa);
                            None
                        })
                        .transpose()
                }
                #[cfg(not(feature = "sapling"))]
                unified::Fvk::Sapling(data) => Some(Ok::<_, DecodingError>((
                    u32::from(unified::Typecode::Sapling),
                    data.to_vec(),
                ))),
                #[cfg(feature = "transparent-inputs")]
                unified::Fvk::P2pkh(data) => ::transparent::keys::AccountPubKey::deserialize(data)
                    .map_err(|_| DecodingError::KeyDataInvalid(Typecode::P2pkh))
                    .map(|tfvk| {
                        transparent = Some(tfvk);
                        None
                    })
                    .transpose(),
                #[cfg(not(feature = "transparent-inputs"))]
                unified::Fvk::P2pkh(data) => Some(Ok::<_, DecodingError>((
                    u32::from(unified::Typecode::P2pkh),
                    data.to_vec(),
                ))),
                unified::Fvk::Unknown { typecode, data } => Some(Ok((*typecode, data.clone()))),
            })
            .collect::<Result<_, _>>()?;

        Self::from_checked_parts(
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            unknown,
        )
        .map_err(|_| DecodingError::KeyDataInvalid(Typecode::P2pkh))
    }

    /// Returns the string encoding of this `UnifiedFullViewingKey` for the given network.
    pub fn encode<P: consensus::Parameters>(&self, params: &P) -> String {
        self.to_ufvk().encode(&params.network_type())
    }

    /// Returns the string encoding of this `UnifiedFullViewingKey` for the given network.
    fn to_ufvk(&self) -> Ufvk {
        let items = core::iter::empty().chain(self.unknown.iter().map(|(typecode, data)| {
            unified::Fvk::Unknown {
                typecode: *typecode,
                data: data.clone(),
            }
        }));
        #[cfg(feature = "orchard")]
        let items = items.chain(
            self.orchard
                .as_ref()
                .map(|fvk| fvk.to_bytes())
                .map(unified::Fvk::Orchard),
        );
        #[cfg(feature = "sapling")]
        let items = items.chain(
            self.sapling
                .as_ref()
                .map(|dfvk| dfvk.to_bytes())
                .map(unified::Fvk::Sapling),
        );
        #[cfg(feature = "transparent-inputs")]
        let items = items.chain(
            self.transparent
                .as_ref()
                .map(|tfvk| tfvk.serialize().try_into().unwrap())
                .map(unified::Fvk::P2pkh),
        );

        unified::Ufvk::try_from_items(items.collect())
            .expect("UnifiedFullViewingKey should only be constructed safely")
    }

    /// Derives a Unified Incoming Viewing Key from this Unified Full Viewing Key.
    pub fn to_unified_incoming_viewing_key(&self) -> UnifiedIncomingViewingKey {
        UnifiedIncomingViewingKey {
            #[cfg(feature = "transparent-inputs")]
            transparent: self.transparent.as_ref().map(|t| {
                t.derive_external_ivk()
                    .expect("Transparent IVK derivation was checked at construction.")
            }),
            #[cfg(feature = "sapling")]
            sapling: self.sapling.as_ref().map(|s| s.to_external_ivk()),
            #[cfg(feature = "orchard")]
            orchard: self.orchard.as_ref().map(|o| o.to_ivk(Scope::External)),
            unknown: Vec::new(),
        }
    }

    /// Returns the transparent component of the unified key at the
    /// BIP44 path `m/44'/<coin_type>'/<account>'`.
    #[cfg(feature = "transparent-inputs")]
    pub fn transparent(&self) -> Option<&::transparent::keys::AccountPubKey> {
        self.transparent.as_ref()
    }

    /// Returns the Sapling diversifiable full viewing key component of this unified key.
    #[cfg(feature = "sapling")]
    pub fn sapling(&self) -> Option<&sapling::DiversifiableFullViewingKey> {
        self.sapling.as_ref()
    }

    /// Returns the Orchard full viewing key component of this unified key.
    #[cfg(feature = "orchard")]
    pub fn orchard(&self) -> Option<&orchard::keys::FullViewingKey> {
        self.orchard.as_ref()
    }

    /// Returns `true` if this UFVK subsumes the given UIVK: every IVK item present in
    /// `other` has a matching item derivable from `self`. The UFVK may have additional
    /// items representing capabilities not present in the UIVK.
    pub fn subsumes_uivk(&self, other: &UnifiedIncomingViewingKey) -> bool {
        self.to_unified_incoming_viewing_key().subsumes(other)
    }

    /// Returns `true` if this UFVK subsumes `other`: every FVK item in `other` has a
    /// matching item in `self`, including both incoming and outgoing viewing capability.
    ///
    /// For unknown items, exact equality of (typecode, data) is required.
    pub fn subsumes_ufvk(&self, other: &UnifiedFullViewingKey) -> bool {
        #[cfg(feature = "orchard")]
        match (&other.orchard, &self.orchard) {
            (Some(e), Some(n)) if e != n => {
                return false;
            }
            (Some(_), None) => return false,
            _ => {}
        }

        #[cfg(feature = "sapling")]
        match (&other.sapling, &self.sapling) {
            (Some(e), Some(n)) if e != n => {
                return false;
            }
            (Some(_), None) => return false,
            _ => {}
        }

        #[cfg(feature = "transparent-inputs")]
        match (&other.transparent, &self.transparent) {
            (Some(e), Some(n)) if e != n => {
                return false;
            }
            (Some(_), None) => return false,
            _ => {}
        }

        // Every unknown item in `other` must have an identical entry in `self`.
        for item in &other.unknown {
            if !self.unknown.contains(item) {
                return false;
            }
        }

        true
    }

    /// Attempts to derive the Unified Address for the given diversifier index and receiver types.
    ///
    /// Returns `None` if the specified index does not produce a valid diversifier.
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn address(
        &self,
        j: DiversifierIndex,
        request: UnifiedAddressRequest,
    ) -> Result<UnifiedAddress, AddressGenerationError> {
        self.to_unified_incoming_viewing_key().address(j, request)
    }

    /// Searches the diversifier space starting at diversifier index `j` for one which will produce
    /// a valid diversifier, and return the Unified Address constructed using that diversifier
    /// along with the index at which the valid diversifier was found.
    ///
    /// Returns an `Err(AddressGenerationError)` if no valid diversifier exists or if the features
    /// required to satisfy the unified address request are not properly enabled.
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn find_address(
        &self,
        j: DiversifierIndex,
        request: UnifiedAddressRequest,
    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
        self.to_unified_incoming_viewing_key()
            .find_address(j, request)
    }

    /// Find the Unified Address corresponding to the smallest valid diversifier index, along with
    /// that index.
    ///
    /// Returns an `Err(AddressGenerationError)` if no valid diversifier exists or if the features
    /// required to satisfy the unified address request are not properly enabled.
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn default_address(
        &self,
        request: UnifiedAddressRequest,
    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
        self.find_address(DiversifierIndex::new(), request)
    }

    /// Returns the default external transparent address using the transparent account pubkey.
    ///
    /// See [`ExternalIvk::default_address`] for more information.
    ///
    /// [`ExternalIvk::default_address`]: ::transparent::keys::ExternalIvk::default_address
    #[cfg(all(
        feature = "transparent-inputs",
        any(test, feature = "test-dependencies")
    ))]
    pub fn default_transparent_address(
        &self,
    ) -> Option<(TransparentAddress, NonHardenedChildIndex)> {
        self.transparent().map(|k| {
            k.derive_external_ivk()
                .expect("ability to derive the external IVK was checked at construction")
                .default_address()
        })
    }

    /// Selects an outgoing viewing key for a transaction's outputs based upon the type(s) of
    /// inputs spent in the transaction.
    ///
    /// This method selects the OVK of the highest-preference item in [ZIP 316] preference order
    /// from among the item types represented by the provided input types. It will return `None` in
    /// the case that this FVK does not contain any items corresponding to the provided input
    /// sources; this should ordinarily never occur because in order to spend an input, a spending
    /// key of the appropriate type must be available and that spending key should be represented
    /// among this UFVK's items.
    pub fn select_ovk(
        &self,
        scope: zip32::Scope,
        input_sources: &NonEmpty<PoolType>,
    ) -> Option<OutgoingViewingKey> {
        #[cfg(feature = "orchard")]
        if let Some(ovk) = input_sources
            .contains(&PoolType::ORCHARD)
            .then(|| {
                self.orchard()
                    .map(|k| OutgoingViewingKey::from(k.to_ovk(scope)))
            })
            .flatten()
        {
            return Some(ovk);
        };

        #[cfg(feature = "sapling")]
        if let Some(ovk) = input_sources
            .contains(&PoolType::SAPLING)
            .then(|| {
                self.sapling()
                    .map(|k| OutgoingViewingKey::from(k.to_ovk(scope)))
            })
            .flatten()
        {
            return Some(ovk);
        }

        #[cfg(feature = "transparent-inputs")]
        if let Some(ovk) = input_sources
            .contains(&PoolType::Transparent)
            .then(|| {
                self.transparent().map(|k| {
                    OutgoingViewingKey(match scope {
                        zip32::Scope::External => k.external_ovk().as_bytes(),
                        zip32::Scope::Internal => k.internal_ovk().as_bytes(),
                    })
                })
            })
            .flatten()
        {
            return Some(ovk);
        }

        None
    }
}

/// A [ZIP 316](https://zips.z.cash/zip-0316) unified incoming viewing key.
#[derive(Clone)]
pub struct UnifiedIncomingViewingKey {
    #[cfg(feature = "transparent-inputs")]
    transparent: Option<::transparent::keys::ExternalIvk>,
    #[cfg(feature = "sapling")]
    sapling: Option<::sapling::zip32::IncomingViewingKey>,
    #[cfg(feature = "orchard")]
    orchard: Option<orchard::keys::IncomingViewingKey>,
    /// Stores the unrecognized elements of the unified encoding.
    unknown: Vec<(u32, Vec<u8>)>,
}

impl PartialEq for UnifiedIncomingViewingKey {
    fn eq(&self, other: &Self) -> bool {
        self.subsumes(other) && other.subsumes(self)
    }
}

impl Eq for UnifiedIncomingViewingKey {}

impl core::fmt::Debug for UnifiedIncomingViewingKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut d = f.debug_struct("UnifiedIncomingViewingKey");
        #[cfg(feature = "transparent-inputs")]
        d.field("transparent", &self.transparent);
        #[cfg(feature = "sapling")]
        d.field("sapling", &self.sapling.as_ref().map(|_| "..."));
        #[cfg(feature = "orchard")]
        d.field("orchard", &self.orchard.as_ref().map(|_| "..."));
        d.field(
            "unknown_typecodes",
            &self
                .unknown
                .iter()
                .map(|(typecode, _)| *typecode)
                .collect::<Vec<_>>(),
        )
        .finish()
    }
}

impl UnifiedIncomingViewingKey {
    /// Construct a new unified incoming viewing key.
    ///
    /// This method is only available when the `test-dependencies` feature is enabled,
    /// as derivation from the UFVK or deserialization from the serialized form should
    /// be used instead.
    #[cfg(any(test, feature = "test-dependencies"))]
    pub fn new(
        #[cfg(feature = "transparent-inputs")] transparent: Option<
            ::transparent::keys::ExternalIvk,
        >,
        #[cfg(feature = "sapling")] sapling: Option<::sapling::zip32::IncomingViewingKey>,
        #[cfg(feature = "orchard")] orchard: Option<orchard::keys::IncomingViewingKey>,
        // TODO: Implement construction of UIVKs with metadata items.
    ) -> UnifiedIncomingViewingKey {
        UnifiedIncomingViewingKey {
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            // We don't allow constructing new UFVKs with unknown items, but we store
            // this to allow parsing such UFVKs.
            unknown: vec![],
        }
    }

    /// Parses a `UnifiedFullViewingKey` from its [ZIP 316] string encoding.
    ///
    /// [ZIP 316]: https://zips.z.cash/zip-0316
    pub fn decode<P: consensus::Parameters>(params: &P, encoding: &str) -> Result<Self, String> {
        let (net, ufvk) = unified::Uivk::decode(encoding).map_err(|e| e.to_string())?;
        let expected_net = params.network_type();
        if net != expected_net {
            return Err(format!(
                "UIVK is for network {net:?} but we expected {expected_net:?}",
            ));
        }

        Self::parse(&ufvk).map_err(|e| e.to_string())
    }

    /// Constructs a unified incoming viewing key from a parsed unified encoding.
    fn parse(uivk: &Uivk) -> Result<Self, DecodingError> {
        #[cfg(feature = "orchard")]
        let mut orchard = None;
        #[cfg(feature = "sapling")]
        let mut sapling = None;
        #[cfg(feature = "transparent-inputs")]
        let mut transparent = None;

        let mut unknown = vec![];

        // We can use as-parsed order here for efficiency, because we're breaking out the
        // receivers we support from the unknown receivers.
        for receiver in uivk.items_as_parsed() {
            match receiver {
                unified::Ivk::Orchard(data) => {
                    #[cfg(feature = "orchard")]
                    {
                        orchard = Some(
                            Option::from(orchard::keys::IncomingViewingKey::from_bytes(data))
                                .ok_or(DecodingError::KeyDataInvalid(Typecode::Orchard))?,
                        );
                    }

                    #[cfg(not(feature = "orchard"))]
                    unknown.push((u32::from(unified::Typecode::Orchard), data.to_vec()));
                }
                unified::Ivk::Sapling(data) => {
                    #[cfg(feature = "sapling")]
                    {
                        sapling = Some(
                            Option::from(::sapling::zip32::IncomingViewingKey::from_bytes(data))
                                .ok_or(DecodingError::KeyDataInvalid(Typecode::Sapling))?,
                        );
                    }

                    #[cfg(not(feature = "sapling"))]
                    unknown.push((u32::from(unified::Typecode::Sapling), data.to_vec()));
                }
                unified::Ivk::P2pkh(data) => {
                    #[cfg(feature = "transparent-inputs")]
                    {
                        transparent = Some(
                            ::transparent::keys::ExternalIvk::deserialize(data)
                                .map_err(|_| DecodingError::KeyDataInvalid(Typecode::P2pkh))?,
                        );
                    }

                    #[cfg(not(feature = "transparent-inputs"))]
                    unknown.push((u32::from(unified::Typecode::P2pkh), data.to_vec()));
                }
                unified::Ivk::Unknown { typecode, data } => {
                    unknown.push((*typecode, data.clone()));
                }
            }
        }

        Ok(Self {
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
            unknown,
        })
    }

    /// Returns the string encoding of this `UnifiedFullViewingKey` for the given network.
    pub fn encode<P: consensus::Parameters>(&self, params: &P) -> String {
        self.render().encode(&params.network_type())
    }

    /// Converts this unified incoming viewing key to a unified encoding.
    fn render(&self) -> Uivk {
        let items = core::iter::empty().chain(self.unknown.iter().map(|(typecode, data)| {
            unified::Ivk::Unknown {
                typecode: *typecode,
                data: data.clone(),
            }
        }));
        #[cfg(feature = "orchard")]
        let items = items.chain(
            self.orchard
                .as_ref()
                .map(|ivk| ivk.to_bytes())
                .map(unified::Ivk::Orchard),
        );
        #[cfg(feature = "sapling")]
        let items = items.chain(
            self.sapling
                .as_ref()
                .map(|divk| divk.to_bytes())
                .map(unified::Ivk::Sapling),
        );
        #[cfg(feature = "transparent-inputs")]
        let items = items.chain(
            self.transparent
                .as_ref()
                .map(|tivk| tivk.serialize().try_into().unwrap())
                .map(unified::Ivk::P2pkh),
        );

        unified::Uivk::try_from_items(items.collect())
            .expect("UnifiedIncomingViewingKey should only be constructed safely.")
    }

    /// Returns whether this uivk has a transparent key item.
    ///
    /// This method is available irrespective of whether the `transparent-inputs` feature flag is enabled.
    pub fn has_transparent(&self) -> bool {
        #[cfg(not(feature = "transparent-inputs"))]
        return false;
        #[cfg(feature = "transparent-inputs")]
        return self.transparent.is_some();
    }

    /// Returns the Transparent external IVK, if present.
    #[cfg(feature = "transparent-inputs")]
    pub fn transparent(&self) -> &Option<::transparent::keys::ExternalIvk> {
        &self.transparent
    }

    /// Returns whether this uivk has a Sapling key item.
    ///
    /// This method is available irrespective of whether the `sapling` feature flag is enabled.
    pub fn has_sapling(&self) -> bool {
        #[cfg(not(feature = "sapling"))]
        return false;
        #[cfg(feature = "sapling")]
        return self.sapling.is_some();
    }

    /// Returns the Sapling IVK, if present.
    #[cfg(feature = "sapling")]
    pub fn sapling(&self) -> &Option<::sapling::zip32::IncomingViewingKey> {
        &self.sapling
    }

    /// Returns whether this uivk has an Orchard key item.
    ///
    /// This method is available irrespective of whether the `orchard` feature flag is enabled.
    pub fn has_orchard(&self) -> bool {
        #[cfg(not(feature = "orchard"))]
        return false;
        #[cfg(feature = "orchard")]
        return self.orchard.is_some();
    }

    /// Returns the Orchard IVK, if present.
    #[cfg(feature = "orchard")]
    pub fn orchard(&self) -> &Option<orchard::keys::IncomingViewingKey> {
        &self.orchard
    }

    /// Returns `true` if this UIVK subsumes `other`: every IVK item present in `other`
    /// has a matching item in `self`. This key may have additional items representing
    /// capabilities not present in `other`.
    ///
    /// For unknown items, exact equality of (typecode, data) is required. Future
    /// revisions may apply more specific semantics for known metadata typecodes.
    pub fn subsumes(&self, other: &UnifiedIncomingViewingKey) -> bool {
        #[cfg(feature = "orchard")]
        match (other.orchard(), &self.orchard) {
            (Some(e), Some(n)) if e != n => {
                return false;
            }
            (Some(_), None) => return false,
            _ => {}
        }

        #[cfg(feature = "sapling")]
        match (other.sapling(), &self.sapling) {
            (Some(e), Some(n)) if e != n => {
                return false;
            }
            (Some(_), None) => return false,
            _ => {}
        }

        #[cfg(feature = "transparent-inputs")]
        match (other.transparent(), &self.transparent) {
            (Some(e), Some(n)) if e != n => {
                return false;
            }
            (Some(_), None) => return false,
            _ => {}
        }

        // Every unknown item in `other` must have an identical entry in `self`.
        for item in &other.unknown {
            if !self.unknown.contains(item) {
                return false;
            }
        }

        true
    }

    /// Attempts to derive the Unified Address for the given diversifier index and receiver types.
    ///
    /// Returns an error if the this key does not produce a valid receiver for a required receiver
    /// type at the given diversifier index.
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn address(
        &self,
        _j: DiversifierIndex,
        request: UnifiedAddressRequest,
    ) -> Result<UnifiedAddress, AddressGenerationError> {
        use ReceiverRequirement::*;

        let request = self
            .receiver_requirements(request)
            .map_err(|_| AddressGenerationError::ShieldedReceiverRequired)?;

        // If we need to generate a transparent receiver, check that the user has not
        // specified an invalid transparent child index, from which we can never search to
        // find a valid index.
        #[cfg(feature = "transparent-inputs")]
        if request.p2pkh == ReceiverRequirement::Require
            && self.transparent.is_some()
            && to_transparent_child_index(_j).is_none()
        {
            return Err(AddressGenerationError::InvalidTransparentChildIndex(_j));
        }

        #[cfg(feature = "orchard")]
        let mut orchard = None;
        if request.orchard != Omit {
            #[cfg(not(feature = "orchard"))]
            if request.orchard == Require {
                return Err(AddressGenerationError::ReceiverTypeNotSupported(
                    Typecode::Orchard,
                ));
            }

            #[cfg(feature = "orchard")]
            if let Some(oivk) = &self.orchard {
                let orchard_j = orchard::keys::DiversifierIndex::from(*_j.as_bytes());
                orchard = Some(oivk.address_at(orchard_j))
            } else if request.orchard == Require {
                return Err(AddressGenerationError::KeyNotAvailable(Typecode::Orchard));
            }
        }

        #[cfg(feature = "sapling")]
        let mut sapling = None;
        if request.sapling != Omit {
            #[cfg(not(feature = "sapling"))]
            if request.sapling == Require {
                return Err(AddressGenerationError::ReceiverTypeNotSupported(
                    Typecode::Sapling,
                ));
            }

            #[cfg(feature = "sapling")]
            if let Some(divk) = &self.sapling {
                // If a Sapling receiver type is requested, we must be able to construct an
                // address; if we're unable to do so, then no Unified Address exists at this
                // diversifier and we use `?` to early-return from this method.
                sapling = match (request.sapling, divk.address_at(_j)) {
                    (Require | Allow, Some(addr)) => Ok(Some(addr)),
                    (Require, None) => {
                        Err(AddressGenerationError::InvalidSaplingDiversifierIndex(_j))
                    }
                    _ => Ok(None),
                }?;
            } else if request.sapling == Require {
                return Err(AddressGenerationError::KeyNotAvailable(Typecode::Sapling));
            }
        }

        #[cfg(feature = "transparent-inputs")]
        let mut transparent = None;
        if request.p2pkh != Omit {
            #[cfg(not(feature = "transparent-inputs"))]
            if request.p2pkh == Require {
                return Err(AddressGenerationError::ReceiverTypeNotSupported(
                    Typecode::P2pkh,
                ));
            }

            #[cfg(feature = "transparent-inputs")]
            if let Some(tivk) = self.transparent.as_ref() {
                // If a transparent receiver type is requested, we must be able to construct an
                // address; if we're unable to do so, then no Unified Address exists at this
                // diversifier.
                let j = to_transparent_child_index(_j);

                transparent = match (request.p2pkh, j.and_then(|j| tivk.derive_address(j).ok())) {
                    (Require | Allow, Some(addr)) => Ok(Some(addr)),
                    (Require, None) => {
                        Err(AddressGenerationError::InvalidTransparentChildIndex(_j))
                    }
                    _ => Ok(None),
                }?;
            } else if request.p2pkh == Require {
                return Err(AddressGenerationError::KeyNotAvailable(Typecode::P2pkh));
            }
        }
        #[cfg(not(feature = "transparent-inputs"))]
        let transparent = None;

        UnifiedAddress::from_receivers(
            #[cfg(feature = "orchard")]
            orchard,
            #[cfg(feature = "sapling")]
            sapling,
            transparent,
        )
        .ok_or(AddressGenerationError::ShieldedReceiverRequired)
    }

    /// Searches the diversifier space starting at diversifier index `j` for one which will produce
    /// a valid address that conforms to the provided request, and returns that Unified Address
    /// along with the index at which the valid diversifier was found.
    ///
    /// If [`None`] is specified for the `request` parameter, a default request that [`Require`]s a
    /// receiver be present for each key item enabled by the feature flags in use will be used to
    /// search the diversifier space.
    ///
    /// Returns an `Err(AddressGenerationError)` if no valid diversifier exists or if the features
    /// required to satisfy the unified address request are not enabled.
    ///
    /// [`Require`]: ReceiverRequirement::Require
    #[allow(unused_mut)]
    #[cfg_attr(not(feature = "sapling"), allow(clippy::never_loop))]
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn find_address(
        &self,
        mut j: DiversifierIndex,
        request: UnifiedAddressRequest,
    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
        // Find a working diversifier and construct the associated address.
        loop {
            let res = self.address(j, request);
            match res {
                Ok(ua) => {
                    return Ok((ua, j));
                }
                #[cfg(feature = "sapling")]
                Err(AddressGenerationError::InvalidSaplingDiversifierIndex(_)) => {
                    if j.increment().is_err() {
                        return Err(AddressGenerationError::DiversifierSpaceExhausted);
                    }
                }
                Err(other) => {
                    return Err(other);
                }
            }
        }
    }

    /// Find the Unified Address corresponding to the smallest valid diversifier index, along with
    /// that index.
    ///
    /// Returns an error if the this key does not produce a valid receiver for a required receiver
    /// type at any diversifier index.
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn default_address(
        &self,
        request: UnifiedAddressRequest,
    ) -> Result<(UnifiedAddress, DiversifierIndex), AddressGenerationError> {
        self.find_address(DiversifierIndex::new(), request)
    }

    /// Attempts to recover a diversifier index for each of the receivers of the given
    /// [`crate::address::UnifiedAddress`].
    ///
    /// Returns the empty set if no shielded receiver of `ua` can be attributed to this key.
    /// Transparent receivers are not considered here, as recovering a diversifier index from a
    /// transparent receiver alone is not possible without additional context.
    #[cfg(feature = "zip32-addresses")]
    #[cfg_attr(docsrs, doc(cfg(feature = "zip32-addresses")))]
    pub fn decrypt_diversifiers(&self, ua: &UnifiedAddress) -> BTreeSet<DiversifierIndex> {
        #[cfg(not(feature = "sapling"))]
        let sapling_di: Option<DiversifierIndex> = None;

        #[cfg(feature = "sapling")]
        let sapling_di = ua
            .sapling()
            .zip(self.sapling().as_ref())
            .and_then(|(receiver, ivk)| ivk.decrypt_diversifier(receiver));

        #[cfg(not(feature = "orchard"))]
        let orchard_di: Option<DiversifierIndex> = None;

        #[cfg(feature = "orchard")]
        let orchard_di = ua
            .orchard()
            .zip(self.orchard().as_ref())
            .and_then(|(receiver, ivk)| ivk.diversifier_index(receiver));

        sapling_di.into_iter().chain(orchard_di).collect()
    }

    /// Convenience method for choosing a set of receiver requirements based upon the given unified
    /// address request and the available items of this key.
    ///
    /// Returns an error if the provided request cannot be satisfied in address generation using
    /// this key.
    pub fn receiver_requirements(
        &self,
        request: UnifiedAddressRequest,
    ) -> Result<ReceiverRequirements, AddressGenerationError> {
        use ReceiverRequirement::*;
        match request {
            UnifiedAddressRequest::AllAvailableKeys => self
                .to_receiver_requirements()
                .map_err(|_| AddressGenerationError::ShieldedReceiverRequired),
            UnifiedAddressRequest::Custom(req) => {
                if req.orchard() == Require && !self.has_orchard() {
                    return Err(AddressGenerationError::ReceiverTypeNotSupported(
                        Typecode::Orchard,
                    ));
                }

                if req.sapling() == Require && !self.has_sapling() {
                    return Err(AddressGenerationError::ReceiverTypeNotSupported(
                        Typecode::Sapling,
                    ));
                }

                if req.p2pkh() == Require && !self.has_transparent() {
                    return Err(AddressGenerationError::ReceiverTypeNotSupported(
                        Typecode::P2pkh,
                    ));
                }

                Ok(req)
            }
        }
    }

    /// Constructs the [`ReceiverRequirements`] that requires a receiver for each data item of this UIVK.
    ///
    /// Returns an error if the resulting request would not include a shielded receiver.
    #[allow(unused_mut)]
    pub fn to_receiver_requirements(
        &self,
    ) -> Result<ReceiverRequirements, ReceiverRequirementError> {
        use ReceiverRequirement::*;

        let mut orchard = Omit;
        #[cfg(feature = "orchard")]
        if self.orchard.is_some() {
            orchard = Require;
        }

        let mut sapling = Omit;
        #[cfg(feature = "sapling")]
        if self.sapling.is_some() {
            sapling = Require;
        }

        let mut p2pkh = Omit;
        #[cfg(feature = "transparent-inputs")]
        if self.transparent.is_some() {
            p2pkh = Require;
        }

        ReceiverRequirements::new(orchard, sapling, p2pkh)
    }

    /// Returns the default external transparent address using the transparent account pubkey.
    ///
    /// See [`ExternalIvk::default_address`] for more information.
    ///
    /// [`ExternalIvk::default_address`]: ::transparent::keys::ExternalIvk::default_address
    #[cfg(all(
        feature = "transparent-inputs",
        any(test, feature = "test-dependencies")
    ))]
    pub fn default_transparent_address(
        &self,
    ) -> Option<(TransparentAddress, NonHardenedChildIndex)> {
        self.transparent.as_ref().map(|k| k.default_address())
    }
}

#[cfg(any(test, feature = "test-dependencies"))]
pub mod testing {
    use proptest::prelude::*;

    use super::UnifiedSpendingKey;
    use zcash_protocol::consensus::Network;
    use zip32::AccountId;

    pub fn arb_unified_spending_key(params: Network) -> impl Strategy<Value = UnifiedSpendingKey> {
        prop::array::uniform32(prop::num::u8::ANY).prop_flat_map(move |seed| {
            prop::num::u32::ANY
                .prop_map(move |account| {
                    UnifiedSpendingKey::from_seed(
                        &params,
                        &seed,
                        AccountId::try_from(account & ((1 << 31) - 1)).unwrap(),
                    )
                })
                .prop_filter("seeds must generate valid USKs", |v| v.is_ok())
                .prop_map(|v| v.unwrap())
        })
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::proptest;

    use zcash_protocol::consensus::MAIN_NETWORK;
    use zip32::AccountId;

    #[cfg(any(feature = "sapling", feature = "orchard"))]
    use {
        super::{UnifiedFullViewingKey, UnifiedIncomingViewingKey},
        zcash_address::unified::{Encoding, Uivk},
    };

    #[cfg(feature = "orchard")]
    use zip32::Scope;

    #[cfg(feature = "sapling")]
    use super::sapling;

    #[cfg(feature = "transparent-inputs")]
    use {
        crate::encoding::AddressCodec,
        ::transparent::keys::{AccountPrivKey, IncomingViewingKey},
        alloc::string::ToString,
        alloc::vec::Vec,
    };

    #[cfg(all(
        feature = "zip32-addresses",
        feature = "transparent-inputs",
        any(feature = "orchard", feature = "sapling")
    ))]
    use {crate::address::Address, zcash_address::test_vectors, zip32::DiversifierIndex};

    #[cfg(feature = "unstable")]
    use super::{Era, UnifiedSpendingKey, testing::arb_unified_spending_key};

    #[cfg(all(feature = "orchard", feature = "unstable"))]
    use subtle::ConstantTimeEq;

    #[cfg(feature = "transparent-inputs")]
    fn seed() -> Vec<u8> {
        let seed_hex = "6ef5f84def6f4b9d38f466586a8380a38593bd47c8cda77f091856176da47f26b5bd1c8d097486e5635df5a66e820d28e1d73346f499801c86228d43f390304f";
        hex::decode(seed_hex).unwrap()
    }

    #[test]
    #[should_panic]
    #[cfg(feature = "sapling")]
    fn spending_key_panics_on_short_seed() {
        let _ = sapling::spending_key(&[0; 31][..], 0, AccountId::ZERO);
    }

    #[cfg(feature = "transparent-inputs")]
    #[test]
    fn pk_to_taddr() {
        use ::transparent::keys::NonHardenedChildIndex;

        let taddr = AccountPrivKey::from_seed(&MAIN_NETWORK, &seed(), AccountId::ZERO)
            .unwrap()
            .to_account_pubkey()
            .derive_external_ivk()
            .unwrap()
            .derive_address(NonHardenedChildIndex::ZERO)
            .unwrap()
            .encode(&MAIN_NETWORK);
        assert_eq!(taddr, "t1PKtYdJJHhc3Pxowmznkg7vdTwnhEsCvR4".to_string());
    }

    #[test]
    #[cfg(any(feature = "orchard", feature = "sapling"))]
    fn ufvk_round_trip() {
        #[cfg(feature = "orchard")]
        let orchard = {
            let sk =
                orchard::keys::SpendingKey::from_zip32_seed(&[0; 32], 0, AccountId::ZERO).unwrap();
            Some(orchard::keys::FullViewingKey::from(&sk))
        };

        #[cfg(feature = "sapling")]
        let sapling = {
            let extsk = sapling::spending_key(&[0; 32], 0, AccountId::ZERO);
            Some(extsk.to_diversifiable_full_viewing_key())
        };

        #[cfg(feature = "transparent-inputs")]
        let transparent = {
            let privkey =
                AccountPrivKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
            Some(privkey.to_account_pubkey())
        };

        let ufvk = UnifiedFullViewingKey::new(
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
        );

        let ufvk = ufvk.expect("Orchard or Sapling fvk is present.");
        let encoded = ufvk.encode(&MAIN_NETWORK);

        // Test encoded form against known values; these test vectors contain Orchard receivers
        // that will be treated as unknown if the `orchard` feature is not enabled.
        let encoded_with_t = "uview1tg6rpjgju2s2j37gkgjq79qrh5lvzr6e0ed3n4sf4hu5qd35vmsh7avl80xa6mx7ryqce9hztwaqwrdthetpy4pc0kce25x453hwcmax02p80pg5savlg865sft9reat07c5vlactr6l2pxtlqtqunt2j9gmvr8spcuzf07af80h5qmut38h0gvcfa9k4rwujacwwca9vu8jev7wq6c725huv8qjmhss3hdj2vh8cfxhpqcm2qzc34msyrfxk5u6dqttt4vv2mr0aajreww5yufpk0gn4xkfm888467k7v6fmw7syqq6cceu078yw8xja502jxr0jgum43lhvpzmf7eu5dmnn6cr6f7p43yw8znzgxg598mllewnx076hljlvynhzwn5es94yrv65tdg3utuz2u3sras0wfcq4adxwdvlk387d22g3q98t5z74quw2fa4wed32escx8dwh4mw35t4jwf35xyfxnu83mk5s4kw2glkgsshmxk";
        let _encoded_no_t = "uview12z384wdq76ceewlsu0esk7d97qnd23v2qnvhujxtcf2lsq8g4hwzpx44fwxssnm5tg8skyh4tnc8gydwxefnnm0hd0a6c6etmj0pp9jqkdsllkr70u8gpf7ndsfqcjlqn6dec3faumzqlqcmtjf8vp92h7kj38ph2786zx30hq2wru8ae3excdwc8w0z3t9fuw7mt7xy5sn6s4e45kwm0cjp70wytnensgdnev286t3vew3yuwt2hcz865y037k30e428dvgne37xvyeal2vu8yjnznphf9t2rw3gdp0hk5zwq00ws8f3l3j5n3qkqgsyzrwx4qzmgq0xwwk4vz2r6vtsykgz089jncvycmem3535zjwvvtvjw8v98y0d5ydwte575gjm7a7k";

        // We test the full roundtrip only with the `sapling` and `orchard` features enabled,
        // because we will not generate these parts of the encoding if the UFVK does not have an
        // these parts.
        #[cfg(all(feature = "sapling", feature = "orchard"))]
        {
            #[cfg(feature = "transparent-inputs")]
            assert_eq!(encoded, encoded_with_t);
            #[cfg(not(feature = "transparent-inputs"))]
            assert_eq!(encoded, _encoded_no_t);
        }

        let decoded = UnifiedFullViewingKey::decode(&MAIN_NETWORK, &encoded).unwrap();
        let reencoded = decoded.encode(&MAIN_NETWORK);
        assert_eq!(encoded, reencoded);

        #[cfg(feature = "transparent-inputs")]
        assert_eq!(
            decoded.transparent.map(|t| t.serialize()),
            ufvk.transparent.as_ref().map(|t| t.serialize()),
        );
        #[cfg(feature = "sapling")]
        assert_eq!(
            decoded.sapling.map(|s| s.to_bytes()),
            ufvk.sapling.map(|s| s.to_bytes()),
        );
        #[cfg(feature = "orchard")]
        assert_eq!(
            decoded.orchard.map(|o| o.to_bytes()),
            ufvk.orchard.map(|o| o.to_bytes()),
        );

        let decoded_with_t = UnifiedFullViewingKey::decode(&MAIN_NETWORK, encoded_with_t).unwrap();
        #[cfg(feature = "transparent-inputs")]
        assert_eq!(
            decoded_with_t.transparent.map(|t| t.serialize()),
            ufvk.transparent.as_ref().map(|t| t.serialize()),
        );

        // Both Orchard and Sapling enabled
        #[cfg(all(
            feature = "orchard",
            feature = "sapling",
            feature = "transparent-inputs"
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 0);
        #[cfg(all(
            feature = "orchard",
            feature = "sapling",
            not(feature = "transparent-inputs")
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 1);

        // Orchard enabled
        #[cfg(all(
            feature = "orchard",
            not(feature = "sapling"),
            feature = "transparent-inputs"
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 1);
        #[cfg(all(
            feature = "orchard",
            not(feature = "sapling"),
            not(feature = "transparent-inputs")
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 2);

        // Sapling enabled
        #[cfg(all(
            not(feature = "orchard"),
            feature = "sapling",
            feature = "transparent-inputs"
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 1);
        #[cfg(all(
            not(feature = "orchard"),
            feature = "sapling",
            not(feature = "transparent-inputs")
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 2);
    }

    #[test]
    #[cfg(all(
        feature = "transparent-inputs",
        any(feature = "orchard", feature = "sapling")
    ))]
    #[cfg(feature = "zip32-addresses")]
    fn ufvk_derivation() {
        use crate::keys::UnifiedAddressRequest;

        use super::{ReceiverRequirement::*, UnifiedSpendingKey};

        for tv in test_vectors::UNIFIED {
            let usk = UnifiedSpendingKey::from_seed(
                &MAIN_NETWORK,
                &tv.root_seed,
                AccountId::try_from(tv.account).unwrap(),
            )
            .expect("seed produced a valid unified spending key");

            let d_idx = DiversifierIndex::from(tv.diversifier_index);
            let ufvk = usk.to_unified_full_viewing_key();

            // The test vectors contain some diversifier indices that do not generate
            // valid Sapling addresses, so skip those.
            #[cfg(feature = "sapling")]
            if ufvk.sapling().unwrap().address(d_idx).is_none() {
                continue;
            }

            let ua = ufvk
                .address(
                    d_idx,
                    UnifiedAddressRequest::unsafe_custom(Omit, Require, Require),
                )
                .unwrap_or_else(|err| {
                    panic!(
                        "unified address generation failed for account {}: {:?}",
                        tv.account, err
                    )
                });

            match Address::decode(&MAIN_NETWORK, tv.unified_addr) {
                Some(Address::Unified(tvua)) => {
                    // We always derive transparent and Sapling receivers, but not
                    // every value in the test vectors has these present.
                    if tvua.has_transparent() {
                        assert_eq!(tvua.transparent(), ua.transparent());
                    }
                    #[cfg(feature = "sapling")]
                    if tvua.has_sapling() {
                        assert_eq!(tvua.sapling(), ua.sapling());
                    }
                }
                _other => {
                    panic!(
                        "{} did not decode to a valid unified address",
                        tv.unified_addr
                    );
                }
            }
        }
    }

    #[test]
    #[cfg(any(feature = "orchard", feature = "sapling"))]
    fn uivk_round_trip() {
        use zcash_protocol::consensus::NetworkType;

        #[cfg(feature = "orchard")]
        let orchard = {
            let sk =
                orchard::keys::SpendingKey::from_zip32_seed(&[0; 32], 0, AccountId::ZERO).unwrap();
            Some(orchard::keys::FullViewingKey::from(&sk).to_ivk(Scope::External))
        };

        #[cfg(feature = "sapling")]
        let sapling = {
            let extsk = sapling::spending_key(&[0; 32], 0, AccountId::ZERO);
            Some(extsk.to_diversifiable_full_viewing_key().to_external_ivk())
        };

        #[cfg(feature = "transparent-inputs")]
        let transparent = {
            let privkey =
                AccountPrivKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
            Some(privkey.to_account_pubkey().derive_external_ivk().unwrap())
        };

        let uivk = UnifiedIncomingViewingKey::new(
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
        );

        let encoded = uivk.render().encode(&NetworkType::Main);

        // Test encoded form against known values; these test vectors contain Orchard receivers
        // that will be treated as unknown if the `orchard` feature is not enabled.
        let encoded_with_t = "uivk1z28yg638vjwusmf0zc9ad2j0mpv6s42wc5kqt004aaqfu5xxxgu7mdcydn9qf723fnryt34s6jyxyw0jt7spq04c3v9ze6qe9gjjc5aglz8zv5pqtw58czd0actynww5n85z3052kzgy6cu0fyjafyp4sr4kppyrrwhwev2rr0awq6m8d66esvk6fgacggqnswg5g9gkv6t6fj9ajhyd0gmel4yzscprpzduncc0e2lywufup6fvzf6y8cefez2r99pgge5yyfuus0r60khgu895pln5e7nn77q6s9kh2uwf6lrfu06ma2kd7r05jjvl4hn6nupge8fajh0cazd7mkmz23t79w";
        let _encoded_no_t = "uivk1020vq9j5zeqxh303sxa0zv2hn9wm9fev8x0p8yqxdwyzde9r4c90fcglc63usj0ycl2scy8zxuhtser0qrq356xfy8x3vyuxu7f6gas75svl9v9m3ctuazsu0ar8e8crtx7x6zgh4kw8xm3q4rlkpm9er2wefxhhf9pn547gpuz9vw27gsdp6c03nwlrxgzhr2g6xek0x8l5avrx9ue9lf032tr7kmhqf3nfdxg7ldfgx6yf09g";

        // We test the full roundtrip only with the `sapling` and `orchard` features enabled,
        // because we will not generate these parts of the encoding if the UIVK does not have an
        // these parts.
        #[cfg(all(feature = "sapling", feature = "orchard"))]
        {
            #[cfg(feature = "transparent-inputs")]
            assert_eq!(encoded, encoded_with_t);
            #[cfg(not(feature = "transparent-inputs"))]
            assert_eq!(encoded, _encoded_no_t);
        }

        let decoded = UnifiedIncomingViewingKey::parse(&Uivk::decode(&encoded).unwrap().1).unwrap();
        let reencoded = decoded.render().encode(&NetworkType::Main);
        assert_eq!(encoded, reencoded);

        #[cfg(feature = "transparent-inputs")]
        assert_eq!(
            decoded.transparent.map(|t| t.serialize()),
            uivk.transparent.as_ref().map(|t| t.serialize()),
        );
        #[cfg(feature = "sapling")]
        assert_eq!(
            decoded.sapling.map(|s| s.to_bytes()),
            uivk.sapling.map(|s| s.to_bytes()),
        );
        #[cfg(feature = "orchard")]
        assert_eq!(
            decoded.orchard.map(|o| o.to_bytes()),
            uivk.orchard.map(|o| o.to_bytes()),
        );

        let decoded_with_t =
            UnifiedIncomingViewingKey::parse(&Uivk::decode(encoded_with_t).unwrap().1).unwrap();
        #[cfg(feature = "transparent-inputs")]
        assert_eq!(
            decoded_with_t.transparent.map(|t| t.serialize()),
            uivk.transparent.as_ref().map(|t| t.serialize()),
        );

        // Both Orchard and Sapling enabled
        #[cfg(all(
            feature = "orchard",
            feature = "sapling",
            feature = "transparent-inputs"
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 0);
        #[cfg(all(
            feature = "orchard",
            feature = "sapling",
            not(feature = "transparent-inputs")
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 1);

        // Orchard enabled
        #[cfg(all(
            feature = "orchard",
            not(feature = "sapling"),
            feature = "transparent-inputs"
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 1);
        #[cfg(all(
            feature = "orchard",
            not(feature = "sapling"),
            not(feature = "transparent-inputs")
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 2);

        // Sapling enabled
        #[cfg(all(
            not(feature = "orchard"),
            feature = "sapling",
            feature = "transparent-inputs"
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 1);
        #[cfg(all(
            not(feature = "orchard"),
            feature = "sapling",
            not(feature = "transparent-inputs")
        ))]
        assert_eq!(decoded_with_t.unknown.len(), 2);
    }

    #[test]
    #[cfg(all(
        feature = "transparent-inputs",
        any(feature = "orchard", feature = "sapling")
    ))]
    #[cfg(feature = "zip32-addresses")]
    fn uivk_derivation() {
        use crate::keys::UnifiedAddressRequest;

        use super::{ReceiverRequirement::*, UnifiedSpendingKey};

        for tv in test_vectors::UNIFIED {
            let usk = UnifiedSpendingKey::from_seed(
                &MAIN_NETWORK,
                &tv.root_seed,
                AccountId::try_from(tv.account).unwrap(),
            )
            .expect("seed produced a valid unified spending key");

            let d_idx = DiversifierIndex::from(tv.diversifier_index);
            let uivk = usk
                .to_unified_full_viewing_key()
                .to_unified_incoming_viewing_key();

            // The test vectors contain some diversifier indices that do not generate
            // valid Sapling addresses, so skip those.
            #[cfg(feature = "sapling")]
            if uivk.sapling().as_ref().unwrap().address_at(d_idx).is_none() {
                continue;
            }

            let ua = uivk
                .address(
                    d_idx,
                    UnifiedAddressRequest::unsafe_custom(Omit, Require, Require),
                )
                .unwrap_or_else(|err| {
                    panic!(
                        "unified address generation failed for account {}: {:?}",
                        tv.account, err
                    )
                });

            match Address::decode(&MAIN_NETWORK, tv.unified_addr) {
                Some(Address::Unified(tvua)) => {
                    // We always derive transparent and Sapling receivers, but not
                    // every value in the test vectors has these present.
                    if tvua.has_transparent() {
                        assert_eq!(tvua.transparent(), ua.transparent());
                    }
                    #[cfg(feature = "sapling")]
                    if tvua.has_sapling() {
                        assert_eq!(tvua.sapling(), ua.sapling());
                    }
                }
                _other => {
                    panic!(
                        "{} did not decode to a valid unified address",
                        tv.unified_addr
                    );
                }
            }
        }
    }

    proptest! {
        #[test]
        #[cfg(feature = "unstable")]
        fn prop_usk_roundtrip(usk in arb_unified_spending_key(zcash_protocol::consensus::Network::MainNetwork)) {
            let encoded = usk.to_bytes(Era::Orchard);

            #[allow(clippy::let_and_return)]
            let encoded_len = {
                let len = 4;

                #[cfg(feature = "orchard")]
                let len = len + 2 + 32;

                let len = len + 2 + 169;

                // Transparent part is an `xprv` transparent extended key deserialized
                // into bytes from Base58, minus the 4 prefix bytes.
                #[cfg(feature = "transparent-inputs")]
                let len = len + 2 + 74;

                #[allow(clippy::let_and_return)]
                len
            };
            assert_eq!(encoded.len(), encoded_len);

            let decoded = UnifiedSpendingKey::from_bytes(Era::Orchard, &encoded);
            let decoded = decoded.unwrap_or_else(|e| panic!("Error decoding USK: {:?}", e));

            #[cfg(feature = "orchard")]
            assert!(bool::from(decoded.orchard().ct_eq(usk.orchard())));

            assert_eq!(decoded.sapling(), usk.sapling());

            #[cfg(feature = "transparent-inputs")]
            assert_eq!(decoded.transparent().to_bytes(), usk.transparent().to_bytes());
        }
    }

    #[test]
    #[cfg(all(
        feature = "sapling",
        feature = "orchard",
        feature = "transparent-inputs"
    ))]
    #[cfg(feature = "zip32-addresses")]
    fn uivk_decrypt_diversifier_matches_own_ua_and_rejects_foreign() {
        use crate::address::UnifiedAddress;
        use crate::keys::{UnifiedAddressRequest, UnifiedSpendingKey};

        let ufvk_a = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &[1u8; 32], AccountId::ZERO)
            .unwrap()
            .to_unified_full_viewing_key();
        let ufvk_b = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &[2u8; 32], AccountId::ZERO)
            .unwrap()
            .to_unified_full_viewing_key();

        let (ua_a, mut di_a) = ufvk_a
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .unwrap();

        // The UIVK for A recovers the diversifier index used to derive A's own UA.
        let uivk_a = ufvk_a.to_unified_incoming_viewing_key();
        let ua_a_dis = uivk_a.decrypt_diversifiers(&ua_a);
        assert_eq!(ua_a_dis.len(), 1);
        assert_eq!(ua_a_dis.first(), Some(di_a).as_ref());

        // The UIVK for B, which did not derive A's UA, returns None.
        let uivk_b = ufvk_b.to_unified_incoming_viewing_key();
        assert_eq!(uivk_b.decrypt_diversifiers(&ua_a).len(), 0);

        // A frankenstein UA combining A's Sapling receiver with B's Orchard receiver is
        // attributed to A (matched via Sapling, tried first).
        let (ua_b, di_b) = ufvk_b
            .default_address(UnifiedAddressRequest::AllAvailableKeys)
            .unwrap();
        let franken = UnifiedAddress::from_receivers(
            Some(*ua_b.orchard().unwrap()),
            Some(*ua_a.sapling().unwrap()),
            None,
        )
        .unwrap();

        let franken_dis_a = uivk_a.decrypt_diversifiers(&franken);
        assert_eq!(franken_dis_a.len(), 1);
        assert_eq!(franken_dis_a.first(), Some(di_a).as_ref());

        let franken_dis_b = uivk_b.decrypt_diversifiers(&franken);
        assert_eq!(franken_dis_b.len(), 1);
        assert_eq!(franken_dis_b.first(), Some(di_b).as_ref());

        di_a.increment()
            .expect("diversifier space is not exhausted");
        let (next_ua_a, _) = ufvk_a
            .find_address(di_a, UnifiedAddressRequest::AllAvailableKeys)
            .unwrap();
        let mixed_ua = UnifiedAddress::from_receivers(
            Some(*ua_a.orchard().unwrap()),
            Some(*next_ua_a.sapling().unwrap()),
            None,
        )
        .unwrap();
        let mixed_dis_a = uivk_a.decrypt_diversifiers(&mixed_ua);
        assert_eq!(mixed_dis_a.len(), 2);
    }

    #[cfg(feature = "unstable")]
    #[test]
    fn usk_debug_redaction() {
        let seed = [0u8; 64];
        let usk = UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
        assert!(format!("{usk:?}").contains("\"...\""));
    }

    #[test]
    #[cfg(any(feature = "orchard", feature = "sapling"))]
    fn ufvk_debug_redaction() {
        #[cfg(feature = "orchard")]
        let orchard = {
            let sk =
                orchard::keys::SpendingKey::from_zip32_seed(&[0; 32], 0, AccountId::ZERO).unwrap();
            Some(orchard::keys::FullViewingKey::from(&sk))
        };

        #[cfg(feature = "sapling")]
        let sapling = {
            let extsk = sapling::spending_key(&[0; 32], 0, AccountId::ZERO);
            Some(extsk.to_diversifiable_full_viewing_key())
        };

        #[cfg(feature = "transparent-inputs")]
        let transparent = {
            let privkey =
                AccountPrivKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
            Some(privkey.to_account_pubkey())
        };

        let ufvk = UnifiedFullViewingKey::new(
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
        )
        .unwrap();

        let debug_str = format!("{ufvk:?}");
        #[cfg(feature = "transparent-inputs")]
        assert!(debug_str.contains("transparent: Some(\"...\")"));
        #[cfg(feature = "sapling")]
        assert!(debug_str.contains("sapling: Some(\"...\")"));
        #[cfg(feature = "orchard")]
        assert!(debug_str.contains("orchard: Some(\"...\")"));
    }

    #[test]
    #[cfg(any(feature = "orchard", feature = "sapling"))]
    fn uivk_debug_redaction() {
        #[cfg(feature = "orchard")]
        let orchard = {
            let sk =
                orchard::keys::SpendingKey::from_zip32_seed(&[0; 32], 0, AccountId::ZERO).unwrap();
            Some(orchard::keys::FullViewingKey::from(&sk).to_ivk(Scope::External))
        };

        #[cfg(feature = "sapling")]
        let sapling = {
            let extsk = sapling::spending_key(&[0; 32], 0, AccountId::ZERO);
            Some(extsk.to_diversifiable_full_viewing_key().to_external_ivk())
        };

        #[cfg(feature = "transparent-inputs")]
        let transparent = {
            let privkey =
                AccountPrivKey::from_seed(&MAIN_NETWORK, &[0; 32], AccountId::ZERO).unwrap();
            Some(privkey.to_account_pubkey().derive_external_ivk().unwrap())
        };

        let uivk = UnifiedIncomingViewingKey::new(
            #[cfg(feature = "transparent-inputs")]
            transparent,
            #[cfg(feature = "sapling")]
            sapling,
            #[cfg(feature = "orchard")]
            orchard,
        );

        let debug_str = format!("{uivk:?}");
        #[cfg(feature = "sapling")]
        assert!(debug_str.contains("sapling: Some(\"...\")"));
        #[cfg(feature = "orchard")]
        assert!(debug_str.contains("orchard: Some(\"...\")"));
    }

    #[test]
    fn ovk_debug_redaction() {
        assert_eq!(
            format!("{:?}", super::OutgoingViewingKey::from([0u8; 32])),
            "OutgoingViewingKey(\"...\")"
        );
    }

    #[cfg(any(feature = "sapling", feature = "orchard"))]
    #[test]
    fn subsumes_ufvk_same_key() {
        let seed = vec![0u8; 32];
        let usk =
            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
        let ufvk = usk.to_unified_full_viewing_key();

        // A UFVK subsumes itself.
        assert!(ufvk.subsumes_ufvk(&ufvk));
    }

    #[cfg(any(feature = "sapling", feature = "orchard"))]
    #[test]
    fn subsumes_uivk_from_same_ufvk() {
        let seed = vec![0u8; 32];
        let usk =
            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
        let ufvk = usk.to_unified_full_viewing_key();
        let uivk = ufvk.to_unified_incoming_viewing_key();

        // A UFVK subsumes the UIVK derived from it.
        assert!(ufvk.subsumes_uivk(&uivk));
    }

    #[cfg(all(feature = "sapling", feature = "orchard"))]
    #[test]
    fn subsumes_ufvk_subset() {
        let seed = vec![0u8; 32];
        let usk =
            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed, AccountId::ZERO).unwrap();
        let ufvk = usk.to_unified_full_viewing_key();

        // A UFVK with all components subsumes one with fewer components.
        let subset_ufvk = UnifiedFullViewingKey::new(
            #[cfg(feature = "transparent-inputs")]
            None,
            ufvk.sapling().cloned(),
            None, // no Orchard
        )
        .unwrap();
        assert!(ufvk.subsumes_ufvk(&subset_ufvk));
        // The subset does not subsume the full key.
        assert!(!subset_ufvk.subsumes_ufvk(&ufvk));
    }

    #[cfg(any(feature = "sapling", feature = "orchard"))]
    #[test]
    fn subsumes_ufvk_different_keys() {
        let seed0 = vec![0u8; 32];
        let seed1 = vec![1u8; 32];
        let usk0 =
            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed0, AccountId::ZERO).unwrap();
        let usk1 =
            super::UnifiedSpendingKey::from_seed(&MAIN_NETWORK, &seed1, AccountId::ZERO).unwrap();
        let ufvk0 = usk0.to_unified_full_viewing_key();
        let ufvk1 = usk1.to_unified_full_viewing_key();

        // UFVKs from different seeds do not subsume each other.
        assert!(!ufvk0.subsumes_ufvk(&ufvk1));
        assert!(!ufvk1.subsumes_ufvk(&ufvk0));
    }
}