pepper-sync 0.7.0

Pepper-sync is a crate providing a sync engine for the zcash network.
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
//! Module for wallet structs and types generated by the sync engine from block chain data or to track the wallet's
//! sync status.
//! The structs will be (or be transposed into) the fundamental wallet components for the wallet interfacing with this
//! sync engine.

use std::{
    collections::{BTreeMap, BTreeSet},
    convert::Infallible,
    fmt::Debug,
    marker::PhantomData,
    ops::Range,
    sync::atomic::{self, AtomicU8},
};

use incrementalmerkletree::Position;
use orchard::tree::MerkleHashOrchard;
use shardtree::{ShardTree, store::memory::MemoryShardStore};
use tokio::sync::mpsc;
use zcash_address::unified::ParseError;
use zcash_keys::{address::UnifiedAddress, encoding::encode_payment_address};
use zcash_primitives::{block::BlockHash, transaction::TxId};
use zcash_protocol::{
    PoolType, ShieldedPool,
    consensus::{self, BlockHeight},
    memo::Memo,
    value::Zatoshis,
};
use zcash_transparent::address::Script;
use zcash_transparent::bundle::OutPoint;

use zingo_netutils::lightwallet_protocol::CompactBlock;
use zingo_status::confirmation_status::ConfirmationStatus;

use crate::{
    client::FetchRequest,
    error::{ServerError, SyncModeError},
    keys::{self, KeyId, transparent::TransparentAddressId},
    scan::compact_blocks::calculate_block_tree_bounds,
    shardtree_ext::{CheckpointAppendOutcome, ShardTreeExt as _},
    sync::{SHARDTREE_CHECKPOINT_ROLLING_WINDOW_SIZE, ScanPriority, ScanRange},
    utils::{block, transaction},
    witness,
};

pub mod traits;

#[cfg(feature = "wallet_essentials")]
pub mod serialization;

/// A block, or a transaction in it, that scanning must reach. A target names a block height and, when a particular
/// transaction is wanted, its txid. Two targets naming the same block height and txid are the same target.
///
/// The blocks around a target are prioritised for scanning: a narrow range by default, and the whole shard of each
/// pool the target's transaction was found to hold notes of, so those notes become spendable.
#[derive(Debug, Clone, Copy)]
pub struct ScanTarget {
    block_height: BlockHeight,
    txid: Option<TxId>,
    pools: ScanTargetPools,
    origin: ScanTargetOrigin,
}

// Where a scan target came from, which decides what a transaction the server does not serve means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ScanTargetOrigin {
    // Trial decryption, spend detection or transparent address discovery. A transaction the server does not serve
    // is an inconsistency in the served data.
    Internal,
    // `crate::add_scan_targets`. A transaction the server does not serve, or a block height outside the chain, is a
    // consumer error and the target is dropped.
    External,
}

// The shielded pools a scan target's transaction was found to hold notes of, as bits of a byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct ScanTargetPools(u8);

impl ScanTargetPools {
    const ALL_POOLS: [ShieldedPool; 3] = [
        ShieldedPool::Sapling,
        ShieldedPool::Orchard,
        ShieldedPool::Ironwood,
    ];

    const fn bit(pool: ShieldedPool) -> u8 {
        match pool {
            ShieldedPool::Sapling => 1,
            ShieldedPool::Orchard => 1 << 1,
            ShieldedPool::Ironwood => 1 << 2,
        }
    }

    #[cfg(feature = "wallet_essentials")]
    pub(crate) fn from_bits(bits: u8) -> Option<Self> {
        let known = Self::ALL_POOLS
            .into_iter()
            .fold(0, |known, pool| known | Self::bit(pool));
        (bits & !known == 0).then_some(Self(bits))
    }

    #[cfg(feature = "wallet_essentials")]
    pub(crate) fn bits(self) -> u8 {
        self.0
    }

    pub(crate) fn with(self, pool: ShieldedPool) -> Self {
        Self(self.0 | Self::bit(pool))
    }

    pub(crate) fn is_empty(self) -> bool {
        self.0 == 0
    }

    pub(crate) fn iter(self) -> impl Iterator<Item = ShieldedPool> {
        Self::ALL_POOLS
            .into_iter()
            .filter(move |&pool| self.0 & Self::bit(pool) != 0)
    }
}

impl ScanTarget {
    /// A target to add through [`crate::add_scan_targets`]. The blocks around `block_height` are prioritised for
    /// scanning, and the transaction `txid` is scanned there when given.
    #[must_use]
    pub fn new(block_height: BlockHeight, txid: Option<TxId>) -> Self {
        Self {
            block_height,
            txid,
            pools: ScanTargetPools::default(),
            origin: ScanTargetOrigin::External,
        }
    }

    pub(crate) fn internal(block_height: BlockHeight, txid: TxId) -> Self {
        Self {
            block_height,
            txid: Some(txid),
            pools: ScanTargetPools::default(),
            origin: ScanTargetOrigin::Internal,
        }
    }

    /// The block height of the target.
    #[must_use]
    pub fn block_height(&self) -> BlockHeight {
        self.block_height
    }

    /// The txid of the transaction to scan at the target's block height, when a particular one is wanted.
    #[must_use]
    pub fn txid(&self) -> Option<TxId> {
        self.txid
    }

    pub(crate) fn pools(&self) -> ScanTargetPools {
        self.pools
    }

    pub(crate) fn origin(&self) -> ScanTargetOrigin {
        self.origin
    }

    pub(crate) fn with_pool(self, pool: ShieldedPool) -> Self {
        Self {
            pools: self.pools.with(pool),
            ..self
        }
    }

    // The target that stands for both `self` and `other`, which name the same block height and txid: it holds the
    // pools of both, and it is internal where either is.
    fn merge(mut self, other: Self) -> Self {
        self.pools.0 |= other.pools.0;
        if other.origin == ScanTargetOrigin::Internal {
            self.origin = ScanTargetOrigin::Internal;
        }
        self
    }

    fn key(&self) -> (BlockHeight, Option<TxId>) {
        (self.block_height, self.txid)
    }
}

impl PartialEq for ScanTarget {
    fn eq(&self, other: &Self) -> bool {
        self.key() == other.key()
    }
}

impl Eq for ScanTarget {}

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

impl Ord for ScanTarget {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.key().cmp(&other.key())
    }
}

/// Initial sync state.
///
/// All fields will be reset when a new sync session starts.
#[derive(Debug, Clone)]
pub struct InitialSyncState {
    /// One block above the fully scanned wallet height at start of sync session.
    ///
    /// If chain height is not larger than fully scanned height when sync is called, this value will be set to chain
    /// height instead.
    pub(crate) sync_start_height: BlockHeight,
    /// The tree sizes of the fully scanned height and chain tip at start of sync session.
    pub(crate) wallet_tree_bounds: TreeBounds,
    /// Total number of blocks scanned in previous sync sessions.
    pub(crate) previously_scanned_blocks: u32,
    /// Total number of sapling outputs scanned in previous sync sessions.
    pub(crate) previously_scanned_sapling_outputs: u32,
    /// Total number of orchard outputs scanned in previous sync sessions.
    pub(crate) previously_scanned_orchard_outputs: u32,
    /// Total number of ironwood outputs scanned in previous sync sessions.
    pub(crate) previously_scanned_ironwood_outputs: u32,
}

impl InitialSyncState {
    /// Create new `InitialSyncState`
    #[must_use]
    pub fn new() -> Self {
        InitialSyncState {
            sync_start_height: 0.into(),
            wallet_tree_bounds: TreeBounds {
                sapling_initial_tree_size: 0,
                sapling_final_tree_size: 0,
                orchard_initial_tree_size: 0,
                orchard_final_tree_size: 0,
                ironwood_initial_tree_size: 0,
                ironwood_final_tree_size: 0,
            },
            previously_scanned_blocks: 0,
            previously_scanned_sapling_outputs: 0,
            previously_scanned_orchard_outputs: 0,
            previously_scanned_ironwood_outputs: 0,
        }
    }
}

impl Default for InitialSyncState {
    fn default() -> Self {
        Self::new()
    }
}

/// Encapsulates the current state of sync
#[derive(Debug, Clone)]
pub struct SyncState {
    /// A vec of block ranges with scan priorities from wallet birthday to chain tip.
    /// In block height order with no overlaps or gaps.
    pub(crate) scan_ranges: Vec<ScanRange>,
    /// The block ranges that contain all sapling outputs of complete sapling shards.
    ///
    /// There is an edge case where a range may include two (or more) shards. However, this only occurs when the lower
    /// shards are already scanned so will cause no issues when punching in the higher scan priorites.
    pub(crate) sapling_shard_ranges: Vec<Range<BlockHeight>>,
    /// The block ranges that contain all orchard outputs of complete orchard shards.
    ///
    /// There is an edge case where a range may include two (or more) shards. However, this only occurs when the lower
    /// shards are already scanned so will cause no issues when punching in the higher scan priorites.
    pub(crate) orchard_shard_ranges: Vec<Range<BlockHeight>>,
    /// The block ranges that contain all ironwood outputs of complete ironwood shards.
    ///
    /// There is an edge case where a range may include two (or more) shards. However, this only occurs when the lower
    /// shards are already scanned so will cause no issues when punching in the higher scan priorites.
    pub(crate) ironwood_shard_ranges: Vec<Range<BlockHeight>>,
    /// Scan targets for relevant transactions to the wallet.
    pub(crate) scan_targets: BTreeSet<ScanTarget>,
    /// Initial sync state.
    pub(crate) initial_sync_state: InitialSyncState,
    /// Compact block transparent data is only scanned above this height. This includes checking transparent outputs
    /// against the wallet's in-use and gap addresses and mapping transparent inputs to the wallet's outpoint map.
    ///
    /// Set to the chain height when transparent address discovery completes at the start of a sync session, as it has
    /// located all relevant transactions at or below this height. Lowered if the wallet is truncated below this
    /// height, by a re-org or a chain height below the wallet's, as transparent address discovery does not cover the
    /// blocks scanned in place of the truncated blocks.
    ///
    /// Blocks mined during a sync session are above the floor and may still be unscanned when the session ends, so
    /// the transparent address discovery of the next sync session searches from the block above the floor.
    pub(crate) transparent_scan_floor: Option<BlockHeight>,
}

impl SyncState {
    /// Create new `SyncState`
    #[must_use]
    pub fn new() -> Self {
        SyncState {
            scan_ranges: Vec::new(),
            sapling_shard_ranges: Vec::new(),
            orchard_shard_ranges: Vec::new(),
            ironwood_shard_ranges: Vec::new(),
            scan_targets: BTreeSet::new(),
            initial_sync_state: InitialSyncState::new(),
            transparent_scan_floor: None,
        }
    }

    /// Scan ranges
    #[must_use]
    pub fn scan_ranges(&self) -> &[ScanRange] {
        &self.scan_ranges
    }

    /// Sapling shard ranges
    #[must_use]
    pub fn sapling_shard_ranges(&self) -> &[Range<BlockHeight>] {
        &self.sapling_shard_ranges
    }

    /// Orchard shard ranges
    #[must_use]
    pub fn orchard_shard_ranges(&self) -> &[Range<BlockHeight>] {
        &self.orchard_shard_ranges
    }

    /// Ironwood shard ranges
    #[must_use]
    pub fn ironwood_shard_ranges(&self) -> &[Range<BlockHeight>] {
        &self.ironwood_shard_ranges
    }

    /// The shard ranges of `pool`
    #[must_use]
    pub fn shard_ranges(&self, pool: ShieldedPool) -> &[Range<BlockHeight>] {
        match pool {
            ShieldedPool::Sapling => &self.sapling_shard_ranges,
            ShieldedPool::Orchard => &self.orchard_shard_ranges,
            ShieldedPool::Ironwood => &self.ironwood_shard_ranges,
        }
    }

    /// Returns true if all scan ranges are scanned.
    pub(crate) fn scan_complete(&self) -> bool {
        self.scan_ranges
            .iter()
            .all(|scan_range| scan_range.priority() == ScanPriority::Scanned)
    }

    /// Returns the block height at which all blocks equal to and below this height are scanned.
    /// Returns `None` if `self.scan_ranges` is empty.
    #[must_use]
    pub fn fully_scanned_height(&self) -> Option<BlockHeight> {
        if let Some(scan_range) = self
            .scan_ranges
            .iter()
            .find(|scan_range| scan_range.priority() != ScanPriority::Scanned)
        {
            Some(scan_range.block_range().start - 1)
        } else {
            self.scan_ranges
                .last()
                .map(|range| range.block_range().end - 1)
        }
    }

    /// Returns the highest block height that has been scanned.
    /// If no scan ranges have been scanned, returns the block below the wallet birthday.
    /// Returns `None` if `self.scan_ranges` is empty.
    #[must_use]
    pub fn highest_scanned_height(&self) -> Option<BlockHeight> {
        if let Some(last_scanned_range) = self.scan_ranges.iter().rfind(|scan_range| {
            scan_range.priority() == ScanPriority::Scanned
                || scan_range.priority() == ScanPriority::ScannedWithoutMapping
                || scan_range.priority() == ScanPriority::RefetchingNullifiers
        }) {
            Some(last_scanned_range.block_range().end - 1)
        } else {
            self.wallet_birthday().map(|start| start - 1)
        }
    }

    /// Returns the wallet birthday or `None` if `self.scan_ranges` is empty.
    ///
    #[must_use]
    pub fn wallet_birthday(&self) -> Option<BlockHeight> {
        self.scan_ranges
            .first()
            .map(|range| range.block_range().start)
    }

    /// - Inserts `scan_target`, merged into the target already held for the same block height and txid if any.
    pub(crate) fn insert_scan_target(&mut self, scan_target: ScanTarget) {
        let merged = self
            .scan_targets
            .take(&scan_target)
            .map_or(scan_target, |held| held.merge(scan_target));
        self.scan_targets.insert(merged);
    }

    /// Returns the last known chain height to the wallet or `None` if `self.scan_ranges` is empty.
    #[must_use]
    pub fn last_known_chain_height(&self) -> Option<BlockHeight> {
        self.scan_ranges
            .last()
            .map(|range| range.block_range().end - 1)
    }
}

impl Default for SyncState {
    fn default() -> Self {
        Self::new()
    }
}

/// Sync modes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncMode {
    /// Sync is not running.
    NotRunning,
    /// Sync is held in a paused state and the wallet guard is dropped.
    Paused,
    /// Sync is running.
    Running,
    /// Sync is shutting down.
    Shutdown,
}

impl SyncMode {
    /// Constructor from u8.
    ///
    /// Returns `None` if `mode` is not a valid enum variant.
    pub fn from_u8(mode: u8) -> Result<Self, SyncModeError> {
        match mode {
            0 => Ok(Self::NotRunning),
            1 => Ok(Self::Paused),
            2 => Ok(Self::Running),
            3 => Ok(Self::Shutdown),
            _ => Err(SyncModeError::InvalidSyncMode(mode)),
        }
    }

    /// Reads the mode held in `atomic_sync_mode`, failing when the byte is no variant of this enum.
    pub fn from_atomic_u8(atomic_sync_mode: &AtomicU8) -> Result<SyncMode, SyncModeError> {
        SyncMode::from_u8(atomic_sync_mode.load(atomic::Ordering::Acquire))
    }

    /// Returns the mode a completed scan leaves behind, which is `Shutdown` for a running engine and the same mode for every other.
    pub fn on_completion(self) -> Self {
        match self {
            Self::Running => Self::Shutdown,
            other => other,
        }
    }

    /// Replaces the mode held in `atomic_sync_mode` with `step` of it in one atomic exchange and returns the mode it replaced.
    pub fn apply(
        atomic_sync_mode: &AtomicU8,
        step: impl Fn(Self) -> Self,
    ) -> Result<Self, SyncModeError> {
        atomic_sync_mode
            .try_update(
                atomic::Ordering::AcqRel,
                atomic::Ordering::Acquire,
                |mode| Self::from_u8(mode).ok().map(|mode| step(mode) as u8),
            )
            .map_err(SyncModeError::InvalidSyncMode)
            .and_then(Self::from_u8)
    }

    /// Moves `atomic_sync_mode` from `from` to `to` when it holds `from` and returns the mode it held before.
    pub fn transition(
        atomic_sync_mode: &AtomicU8,
        from: Self,
        to: Self,
    ) -> Result<Self, SyncModeError> {
        Self::apply(
            atomic_sync_mode,
            |mode| if mode == from { to } else { mode },
        )
    }
}

/// Initial and final tree sizes.
#[derive(Debug, Clone, Copy)]
#[allow(missing_docs)]
pub struct TreeBounds {
    pub sapling_initial_tree_size: u32,
    pub sapling_final_tree_size: u32,
    pub orchard_initial_tree_size: u32,
    pub orchard_final_tree_size: u32,
    pub ironwood_initial_tree_size: u32,
    pub ironwood_final_tree_size: u32,
}

/// Output ID for a given pool type.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct OutputId {
    /// ID of associated transaction.
    txid: TxId,
    /// Index of output within the transactions bundle of the given pool type.
    output_index: u32,
}

impl OutputId {
    /// Creates new `OutputId` from parts.
    #[must_use]
    pub fn new(txid: TxId, output_index: u32) -> Self {
        OutputId { txid, output_index }
    }

    /// Transaction ID of output's associated transaction.
    #[must_use]
    pub fn txid(&self) -> TxId {
        self.txid
    }

    /// Index of output within the transactions bundle of the given pool type.
    #[must_use]
    pub fn output_index(&self) -> u32 {
        self.output_index
    }
}

impl std::fmt::Display for OutputId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{{
                txid: {}
                output index: {}
            }}",
            self.txid, self.output_index
        )
    }
}

impl From<&OutPoint> for OutputId {
    fn from(value: &OutPoint) -> Self {
        OutputId::new(*value.txid(), value.n())
    }
}

impl From<OutputId> for OutPoint {
    fn from(value: OutputId) -> Self {
        OutPoint::new(value.txid.into(), value.output_index)
    }
}

/// Binary tree map of nullifiers from transaction spends or actions
#[derive(Debug)]
pub struct NullifierMap {
    /// Sapling nullifer map
    pub sapling: BTreeMap<sapling_crypto::Nullifier, ScanTarget>,
    /// Orchard nullifer map
    pub orchard: BTreeMap<orchard::note::Nullifier, ScanTarget>,
    /// Ironwood nullifer map
    pub ironwood: BTreeMap<orchard::note::Nullifier, ScanTarget>,
}

impl NullifierMap {
    /// Construct new nullifier map.
    #[must_use]
    pub fn new() -> Self {
        Self {
            sapling: BTreeMap::new(),
            orchard: BTreeMap::new(),
            ironwood: BTreeMap::new(),
        }
    }

    /// Clear nullifier map.
    pub fn clear(&mut self) {
        self.sapling.clear();
        self.orchard.clear();
        self.ironwood.clear();
    }
}

impl Default for NullifierMap {
    fn default() -> Self {
        Self::new()
    }
}

/// Wallet block data
#[derive(Debug, Clone)]
pub struct WalletBlock {
    pub(crate) block_height: BlockHeight,
    pub(crate) block_hash: BlockHash,
    pub(crate) prev_hash: BlockHash,
    pub(crate) time: u32,
    pub(crate) txids: Vec<TxId>,
    pub(crate) tree_bounds: TreeBounds,
}

impl WalletBlock {
    pub(crate) async fn from_compact_block(
        consensus_parameters: &impl consensus::Parameters,
        fetch_request_sender: mpsc::UnboundedSender<FetchRequest>,
        block: &CompactBlock,
    ) -> Result<Self, ServerError> {
        let tree_bounds =
            calculate_block_tree_bounds(consensus_parameters, fetch_request_sender, block).await?;

        Ok(Self {
            block_height: block::get_compact_height(block),
            block_hash: block::get_compact_hash(block),
            prev_hash: block::get_compact_prev_hash(block),
            time: block.time,
            txids: block
                .vtx
                .iter()
                .map(transaction::get_compact_txid)
                .collect(),
            tree_bounds,
        })
    }

    /// Block height.
    #[must_use]
    pub fn block_height(&self) -> BlockHeight {
        self.block_height
    }

    /// Block hash.
    #[must_use]
    pub fn block_hash(&self) -> BlockHash {
        self.block_hash
    }

    /// Previous block hash.
    #[must_use]
    pub fn prev_hash(&self) -> BlockHash {
        self.prev_hash
    }

    /// Time block was mined.
    #[must_use]
    pub fn time(&self) -> u32 {
        self.time
    }

    /// Transaction IDs of transactions in the block.
    #[must_use]
    pub fn txids(&self) -> &[TxId] {
        &self.txids
    }

    /// Tree size bounds
    #[must_use]
    pub fn tree_bounds(&self) -> TreeBounds {
        self.tree_bounds
    }
}

/// Wallet transaction
pub struct WalletTransaction {
    pub(crate) txid: TxId,
    pub(crate) status: ConfirmationStatus,
    pub(crate) transaction: zcash_primitives::transaction::Transaction,
    pub(crate) datetime: u32,
    pub(crate) transparent_coins: Vec<TransparentCoin>,
    pub(crate) sapling_notes: Vec<SaplingNote>,
    pub(crate) orchard_notes: Vec<OrchardNote>,
    pub(crate) ironwood_notes: Vec<IronwoodNote>,
    pub(crate) outgoing_sapling_notes: Vec<OutgoingSaplingNote>,
    pub(crate) outgoing_orchard_notes: Vec<OutgoingOrchardNote>,
    pub(crate) outgoing_ironwood_notes: Vec<OutgoingIronwoodNote>,
}

impl WalletTransaction {
    /// Transaction ID
    #[must_use]
    pub fn txid(&self) -> TxId {
        self.txid
    }

    /// Confirmation status
    #[must_use]
    pub fn status(&self) -> ConfirmationStatus {
        self.status
    }

    /// [`zcash_primitives::transaction::Transaction`]
    #[must_use]
    pub fn transaction(&self) -> &zcash_primitives::transaction::Transaction {
        &self.transaction
    }

    /// Datetime. In form of seconds since unix epoch.
    #[must_use]
    pub fn datetime(&self) -> u32 {
        self.datetime
    }

    /// Transparent coins
    #[must_use]
    pub fn transparent_coins(&self) -> &[TransparentCoin] {
        &self.transparent_coins
    }

    /// Transparent coins mutable
    pub fn transparent_coins_mut(&mut self) -> Vec<&mut TransparentCoin> {
        self.transparent_coins.iter_mut().collect()
    }

    /// Sapling notes
    #[must_use]
    pub fn sapling_notes(&self) -> &[SaplingNote] {
        &self.sapling_notes
    }

    /// Sapling notes mutable
    pub fn sapling_notes_mut(&mut self) -> Vec<&mut SaplingNote> {
        self.sapling_notes.iter_mut().collect()
    }

    /// Orchard notes
    #[must_use]
    pub fn orchard_notes(&self) -> &[OrchardNote] {
        &self.orchard_notes
    }

    /// Orchard notes mutable
    pub fn orchard_notes_mut(&mut self) -> Vec<&mut OrchardNote> {
        self.orchard_notes.iter_mut().collect()
    }

    /// Ironwood notes
    #[must_use]
    pub fn ironwood_notes(&self) -> &[IronwoodNote] {
        &self.ironwood_notes
    }

    /// Ironwood notes mutable
    pub fn ironwood_notes_mut(&mut self) -> Vec<&mut IronwoodNote> {
        self.ironwood_notes.iter_mut().collect()
    }

    /// Outgoing sapling notes
    #[must_use]
    pub fn outgoing_sapling_notes(&self) -> &[OutgoingSaplingNote] {
        &self.outgoing_sapling_notes
    }

    /// Outgoing orchard notes
    #[must_use]
    pub fn outgoing_orchard_notes(&self) -> &[OutgoingOrchardNote] {
        &self.outgoing_orchard_notes
    }

    /// Outgoing ironwood notes
    #[must_use]
    pub fn outgoing_ironwood_notes(&self) -> &[OutgoingIronwoodNote] {
        &self.outgoing_ironwood_notes
    }

    /// Returns nullifers from sapling bundle.
    /// Returns empty vec if bundle is `None`.
    pub fn sapling_nullifiers(&self) -> Vec<&sapling_crypto::Nullifier> {
        self.transaction
            .sapling_bundle()
            .map_or_else(Vec::new, |bundle| {
                bundle
                    .shielded_spends()
                    .iter()
                    .map(|spend| spend.nullifier())
                    .collect::<Vec<_>>()
            })
    }

    /// Returns nullifers from orchard bundle.
    /// Returns empty vec if bundle is `None`.
    pub fn orchard_nullifiers(&self) -> Vec<&orchard::note::Nullifier> {
        self.transaction
            .orchard_bundle()
            .map_or_else(Vec::new, |bundle| {
                bundle
                    .actions()
                    .iter()
                    .map(orchard::Action::nullifier)
                    .collect::<Vec<_>>()
            })
    }

    /// Returns nullifers from ironwood bundle.
    /// Returns empty vec if bundle is `None`.
    pub fn ironwood_nullifiers(&self) -> Vec<&orchard::note::Nullifier> {
        self.transaction
            .ironwood_bundle()
            .map_or_else(Vec::new, |bundle| {
                bundle
                    .actions()
                    .iter()
                    .map(orchard::Action::nullifier)
                    .collect::<Vec<_>>()
            })
    }

    /// Returns outpoints from transparent bundle.
    /// Returns empty vec if bundle is `None`.
    pub fn outpoints(&self) -> Vec<&OutPoint> {
        self.transaction
            .transparent_bundle()
            .map_or_else(Vec::new, |bundle| {
                bundle
                    .vin
                    .iter()
                    .map(zcash_transparent::bundle::TxIn::prevout)
                    .collect::<Vec<_>>()
            })
    }

    /// Updates transaction status if `status` is a valid update for the current transaction status.
    /// For example, if `status` is `Mempool` but the current transaction status is `Confirmed`, the status will remain
    /// unchanged.
    /// A `Failed` transaction may return to `Mempool` status, as being observed in the mempool is
    /// proof the transaction was not rejected or expired.
    /// `datetime` refers to the time in which the status was updated, or the time the block was mined when updating
    /// to `Confirmed` status.
    /// If `fail_confirmed` is set, a confirmed transaction can be set to failed (i.e. during re-org truncation).
    pub fn update_status(
        &mut self,
        status: ConfirmationStatus,
        datetime: u32,
        fail_confirmed: bool,
    ) {
        match status {
            ConfirmationStatus::Transmitted(_)
                if matches!(self.status(), ConfirmationStatus::Calculated(_)) =>
            {
                self.status = status;
                self.datetime = datetime;
            }
            ConfirmationStatus::Mempool(_)
                if matches!(
                    self.status(),
                    ConfirmationStatus::Calculated(_)
                        | ConfirmationStatus::Transmitted(_)
                        | ConfirmationStatus::Failed(_)
                ) =>
            {
                self.status = status;
                self.datetime = datetime;
            }
            ConfirmationStatus::Confirmed(_)
                if matches!(
                    self.status(),
                    ConfirmationStatus::Calculated(_)
                        | ConfirmationStatus::Transmitted(_)
                        | ConfirmationStatus::Mempool(_)
                ) =>
            {
                self.status = status;
                self.datetime = datetime;
            }
            ConfirmationStatus::Failed(_)
                if (fail_confirmed && !matches!(self.status(), ConfirmationStatus::Failed(_)))
                    || self.status().is_pending() =>
            {
                self.status = status;
                self.datetime = datetime;
            }
            _ => (),
        }
    }
}

#[cfg(any(test, feature = "test-features"))]
impl WalletTransaction {
    /// Creates a minimal `WalletTransaction` for testing purposes.
    ///
    /// Constructs a valid v5 transaction with empty bundles and the given `txid` and `status`.
    /// The transaction's expiry height is set to 0 (never expires).
    pub fn new_for_test(txid: TxId, status: ConfirmationStatus) -> Self {
        Self::new_for_test_with_expiry(txid, status, BlockHeight::from_u32(0))
    }

    /// Creates a minimal `WalletTransaction` for testing purposes, with the given expiry height.
    ///
    /// Constructs a valid v5 transaction with empty bundles and the given `txid` and `status`.
    pub fn new_for_test_with_expiry(
        txid: TxId,
        status: ConfirmationStatus,
        expiry_height: BlockHeight,
    ) -> Self {
        use zcash_primitives::transaction::{TransactionData, TxVersion};
        use zcash_protocol::consensus::BranchId;

        let transaction = TransactionData::from_parts(
            TxVersion::V6,
            BranchId::Nu6_3,
            0,
            expiry_height,
            None,
            None,
            None,
            None,
        )
        .freeze()
        .expect("empty v5 transaction should always be valid");

        Self {
            txid,
            status,
            transaction,
            datetime: 0,
            transparent_coins: Vec::new(),
            sapling_notes: Vec::new(),
            orchard_notes: Vec::new(),
            ironwood_notes: Vec::new(),
            outgoing_sapling_notes: Vec::new(),
            outgoing_orchard_notes: Vec::new(),
            outgoing_ironwood_notes: Vec::new(),
        }
    }

    /// As [`Self::new_for_test`], with received sapling notes attached.
    #[must_use]
    pub fn with_sapling_notes_for_test(mut self, sapling_notes: Vec<SaplingNote>) -> Self {
        self.sapling_notes = sapling_notes;
        self
    }

    /// As [`Self::new_for_test`], with outgoing sapling notes attached.
    #[must_use]
    pub fn with_outgoing_sapling_notes_for_test(
        mut self,
        outgoing_sapling_notes: Vec<OutgoingSaplingNote>,
    ) -> Self {
        self.outgoing_sapling_notes = outgoing_sapling_notes;
        self
    }

    /// As [`Self::new_for_test`], with received transparent coins attached.
    #[must_use]
    pub fn with_transparent_coins_for_test(
        mut self,
        transparent_coins: Vec<TransparentCoin>,
    ) -> Self {
        self.transparent_coins = transparent_coins;
        self
    }

    /// As [`Self::new_for_test`], with received and outgoing orchard notes
    /// attached, for tests exercising summary/value-transfer derivation
    /// without a chain.
    pub fn new_for_test_with_orchard_notes(
        txid: TxId,
        status: ConfirmationStatus,
        orchard_notes: Vec<OrchardNote>,
        outgoing_orchard_notes: Vec<OutgoingOrchardNote>,
    ) -> Self {
        let mut transaction = Self::new_for_test(txid, status);
        transaction.orchard_notes = orchard_notes;
        transaction.outgoing_orchard_notes = outgoing_orchard_notes;
        transaction
    }

    /// As [`Self::new_for_test`], with received and outgoing ironwood notes
    /// attached, for tests exercising summary/value-transfer derivation
    /// without a chain.
    pub fn new_for_test_with_ironwood_notes(
        txid: TxId,
        status: ConfirmationStatus,
        ironwood_notes: Vec<IronwoodNote>,
        outgoing_ironwood_notes: Vec<OutgoingIronwoodNote>,
    ) -> Self {
        let mut transaction = Self::new_for_test(txid, status);
        transaction.ironwood_notes = ironwood_notes;
        transaction.outgoing_ironwood_notes = outgoing_ironwood_notes;
        transaction
    }
}

#[cfg(any(test, feature = "test-features"))]
impl SyncState {
    /// Creates sync state with the given scan ranges, for tests exercising
    /// spendability/witness gating without a chain.
    pub fn new_for_test(scan_ranges: Vec<ScanRange>) -> Self {
        let mut sync_state = Self::new();
        sync_state.scan_ranges = scan_ranges;
        sync_state
    }
}

#[cfg(any(test, feature = "test-features"))]
impl<N, Nf: Copy, P> WalletNote<N, Nf, P> {
    /// Creates a minimal received note for testing purposes.
    pub fn new_for_test(
        output_id: OutputId,
        account_id: zip32::AccountId,
        scope: zip32::Scope,
        note: N,
        memo: Memo,
        position: Option<Position>,
    ) -> Self {
        Self {
            output_id,
            key_id: KeyId::from_parts(account_id, scope),
            note,
            nullifier: None,
            position,
            memo,
            spending_transaction: None,
            refetch_nullifier_ranges: Vec::new(),
            marker: std::marker::PhantomData,
        }
    }

    /// Attaches a nullifier, for tests exercising spend paths, since the
    /// spendable-note filter requires a known nullifier.
    #[must_use]
    pub fn with_nullifier_for_test(mut self, nullifier: Nf) -> Self {
        self.nullifier = Some(nullifier);
        self
    }
}

#[cfg(feature = "test-features")]
impl<N, P> OutgoingNote<N, P> {
    /// Creates a minimal outgoing note for testing purposes.
    pub fn new_for_test(
        output_id: OutputId,
        account_id: zip32::AccountId,
        scope: zip32::Scope,
        note: N,
        memo: Memo,
        recipient_full_unified_address: Option<UnifiedAddress>,
    ) -> Self {
        Self {
            output_id,
            key_id: KeyId::from_parts(account_id, scope),
            note,
            memo,
            recipient_full_unified_address,
            marker: std::marker::PhantomData,
        }
    }
}

#[cfg(feature = "wallet_essentials")]
impl WalletTransaction {
    /// Returns the total value sent to receivers, excluding value sent to the wallet's own addresses.
    #[must_use]
    pub fn total_value_sent(&self) -> u64 {
        let transparent_value_sent = self
            .transaction
            .transparent_bundle()
            .map_or(0, |bundle| {
                bundle
                    .vout
                    .iter()
                    .map(|output| output.value().into_u64())
                    .sum()
            })
            .saturating_sub(self.total_output_value::<TransparentCoin>());

        let sapling_value_sent =
            self.total_external_outgoing_note_value::<OutgoingSaplingNote, SaplingNote>();
        let orchard_value_sent =
            self.total_external_outgoing_note_value::<OutgoingOrchardNote, OrchardNote>();
        let ironwood_value_sent =
            self.total_external_outgoing_note_value::<OutgoingIronwoodNote, IronwoodNote>();

        transparent_value_sent + sapling_value_sent + orchard_value_sent + ironwood_value_sent
    }

    /// Returns total sum of all output values.
    #[must_use]
    pub fn total_value_received(&self) -> u64 {
        self.total_output_value::<TransparentCoin>()
            + self.total_output_value::<SaplingNote>()
            + self.total_output_value::<OrchardNote>()
            + self.total_output_value::<IronwoodNote>()
    }

    /// Returns total sum of output values for a given pool.
    #[must_use]
    pub fn total_output_value<Op: OutputInterface>(&self) -> u64 {
        Op::transaction_outputs(self)
            .iter()
            .map(OutputInterface::value)
            .sum()
    }

    /// Returns total sum of outgoing note values for a given shielded pool.
    #[must_use]
    pub fn total_outgoing_note_value<Op: OutgoingNoteInterface>(&self) -> u64 {
        Op::transaction_outgoing_notes(self)
            .iter()
            .map(OutgoingNoteInterface::value)
            .sum()
    }

    /// Returns total sum of outgoing note values for outputs that are not wallet-owned.
    #[must_use]
    pub fn total_external_outgoing_note_value<Outgoing, Incoming>(&self) -> u64
    where
        Outgoing: OutgoingNoteInterface,
        Incoming: OutputInterface,
    {
        Outgoing::transaction_outgoing_notes(self)
            .iter()
            .filter(|outgoing_note| {
                !Incoming::transaction_outputs(self)
                    .iter()
                    .any(|wallet_note| wallet_note.output_id() == outgoing_note.output_id())
            })
            .map(OutgoingNoteInterface::value)
            .sum()
    }
}

impl std::fmt::Debug for WalletTransaction {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("WalletTransaction")
            .field("txid", &self.txid)
            .field("confirmation_status", &self.status)
            .field("datetime", &self.datetime)
            .field("transparent_coins", &self.transparent_coins)
            .field("sapling_notes", &self.sapling_notes)
            .field("orchard_notes", &self.orchard_notes)
            .field("ironwood_notes", &self.ironwood_notes)
            .field("outgoing_sapling_notes", &self.outgoing_sapling_notes)
            .field("outgoing_orchard_notes", &self.outgoing_orchard_notes)
            .field("outgoing_ironwood_notes", &self.outgoing_ironwood_notes)
            .finish()
    }
}

/// Provides a common API for all key identifiers.
pub trait KeyIdInterface {
    /// Account ID.
    fn account_id(&self) -> zip32::AccountId;
}

/// Provides a common API for all output types.
pub trait OutputInterface: Sized {
    /// Identifier for key used to decrypt output.
    type KeyId: KeyIdInterface;
    /// Transaction input type associated with spend detection of output.
    type Input: Clone + Debug + PartialEq + Eq + PartialOrd + Ord;

    /// Output's associated pool type.
    const POOL_TYPE: PoolType;

    /// Output ID.
    fn output_id(&self) -> OutputId;

    /// Identifier for key used to decrypt output.
    fn key_id(&self) -> Self::KeyId;

    /// Transaction ID of transaction this output was spent.
    /// If `None`, output is not spent.
    fn spending_transaction(&self) -> Option<TxId>;

    /// Sets spending transaction.
    fn set_spending_transaction(&mut self, spending_transaction: Option<TxId>);

    /// Note value..
    // TODO: change to Zatoshis checked type
    fn value(&self) -> u64;

    /// Returns the type used to link with transaction inputs for spend detection.
    /// Returns `None` in the case the nullifier is not available for shielded outputs.
    ///
    /// Nullifier for shielded outputs.
    /// Outpoint for transparent outputs.
    fn spend_link(&self) -> Option<Self::Input>;

    /// Inputs within `transaction` used to detect an output's spend status.
    ///
    /// Nullifiers for shielded outputs.
    /// Out points for transparent outputs.
    fn transaction_inputs(transaction: &WalletTransaction) -> Vec<&Self::Input>;

    /// Outputs within `transaction`.
    fn transaction_outputs(transaction: &WalletTransaction) -> &[Self];
}

/// Provides a common API for all shielded output types.
pub trait NoteInterface: OutputInterface {
    /// Decrypted note type.
    type ZcashNote;
    /// Nullifier type.
    type Nullifier: Copy + Clone + PartialEq + Eq + PartialOrd + Ord;

    /// Note's associated shielded protocol.
    const SHIELDED_PROTOCOL: ShieldedPool;

    /// Decrypted note with recipient and value
    fn note(&self) -> &Self::ZcashNote;

    /// Derived nullifier
    fn nullifier(&self) -> Option<Self::Nullifier>;

    /// Commitment tree leaf position
    fn position(&self) -> Option<Position>;

    /// Memo
    fn memo(&self) -> &Memo;

    /// List of block ranges where the nullifiers must be re-fetched to guarantee the note has not been spent.
    /// These scan ranges were marked `ScannedWithoutMapping` or `RefetchingNullifiers` priority before this note was
    /// scanned, meaning the nullifiers were discarded due to memory constraints and will be re-fetched later in the
    /// sync process.
    fn refetch_nullifier_ranges(&self) -> &[Range<BlockHeight>];
}

///  Transparent coin (output) with metadata relevant to the wallet.
#[derive(Debug, Clone)]
pub struct TransparentCoin {
    /// Output ID.
    pub(crate) output_id: OutputId,
    /// Identifier for key used to derive address.
    pub(crate) key_id: TransparentAddressId,
    /// Encoded transparent address.
    pub(crate) address: String,
    /// Script.
    pub(crate) script: Script,
    /// Coin value.
    pub(crate) value: Zatoshis,
    /// Transaction ID of transaction this output was spent.
    /// If `None`, output is not spent.
    pub(crate) spending_transaction: Option<TxId>,
}

#[cfg(feature = "test-features")]
impl TransparentCoin {
    /// Creates a minimal received coin for testing purposes. The script
    /// must be the real locking script for `address`: spendable-output
    /// selection reconstructs the recipient from it and silently drops
    /// coins whose script does not parse to an address.
    pub fn new_for_test(
        output_id: OutputId,
        key_id: TransparentAddressId,
        address: String,
        script: Script,
        value: Zatoshis,
    ) -> Self {
        Self {
            output_id,
            key_id,
            address,
            script,
            value,
            spending_transaction: None,
        }
    }
}

impl TransparentCoin {
    /// Address received to.
    #[must_use]
    pub fn address(&self) -> &str {
        &self.address
    }

    /// Script.
    #[must_use]
    pub fn script(&self) -> &Script {
        &self.script
    }
}

impl OutputInterface for TransparentCoin {
    type KeyId = TransparentAddressId;
    type Input = OutPoint;

    const POOL_TYPE: PoolType = PoolType::Transparent;

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> Self::KeyId {
        self.key_id
    }

    fn spending_transaction(&self) -> Option<TxId> {
        self.spending_transaction
    }

    fn set_spending_transaction(&mut self, spending_transaction: Option<TxId>) {
        self.spending_transaction = spending_transaction;
    }

    fn value(&self) -> u64 {
        self.value.into_u64()
    }

    fn spend_link(&self) -> Option<Self::Input> {
        Some(self.output_id.into())
    }

    fn transaction_inputs(transaction: &WalletTransaction) -> Vec<&Self::Input> {
        transaction.outpoints()
    }

    fn transaction_outputs(transaction: &WalletTransaction) -> &[Self] {
        &transaction.transparent_coins
    }
}

/// The network upgrade at which a shielded pool begins to exist.
///
/// This is the workspace's single pool-to-upgrade mapping: upstream
/// `zcash_protocol` deliberately ships
/// `ShieldedPool` and `NetworkUpgrade` as unrelated enums, so the mapping
/// is defined exactly once, here. Every height clamp involving a pool's
/// existence derives from it. A second mapping anywhere in the workspace
/// is a defect.
#[must_use]
pub fn pool_upgrade(pool: ShieldedPool) -> consensus::NetworkUpgrade {
    match pool {
        ShieldedPool::Sapling => consensus::NetworkUpgrade::Sapling,
        ShieldedPool::Orchard => consensus::NetworkUpgrade::Nu5,
        ShieldedPool::Ironwood => consensus::NetworkUpgrade::Nu6_3,
    }
}

/// A pool's activation height: the block height at which the pool begins
/// to exist on the chain.
///
/// The only constructor is the derivation [`PoolActivation::of`], so a
/// value of this type carries its provenance: it came from the chain's
/// consensus parameters through [`pool_upgrade`], never from arithmetic a
/// call site invented. Seams that must not run without an activation floor
/// (the migration schedule planner, for one) demand this type in their
/// signatures, making floor omission unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PoolActivation(BlockHeight);

impl PoolActivation {
    /// Derives the pool's activation height from the chain's consensus
    /// parameters. `None` when the chain never activates the pool's
    /// upgrade, a real state (regtest schedules may defer an upgrade
    /// indefinitely), in which the pool simply cannot be scheduled
    /// against.
    pub fn of(
        consensus_parameters: &impl consensus::Parameters,
        pool: ShieldedPool,
    ) -> Option<Self> {
        consensus_parameters
            .activation_height(pool_upgrade(pool))
            .map(Self)
    }

    /// The activation height.
    #[must_use]
    pub fn height(&self) -> BlockHeight {
        self.0
    }

    /// The later of the activation and `height`: the effective floor for
    /// heights that must not precede the pool's existence (a wallet
    /// Birthday clamped to the pool's activation, the lower bound of a
    /// scan range). Birthday remains a wallet property throughout. The
    /// pool contributes only its activation height.
    #[must_use]
    pub fn max_with(&self, height: BlockHeight) -> BlockHeight {
        self.0.max(height)
    }

    /// A fabricated activation for tests exercising floor arithmetic
    /// without a full parameter set. Production code has no path here:
    /// the derivation constructor is the only other way in.
    #[cfg(any(test, feature = "test-features"))]
    #[must_use]
    pub fn new_for_test(height: BlockHeight) -> Self {
        Self(height)
    }
}

/// Marker for the Sapling pool, distinguishing note types whose inner data
/// is otherwise identical.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sapling;

/// Marker for the Orchard pool, distinguishing note types whose inner data
/// is otherwise identical.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Orchard;

/// Marker for the Ironwood pool. Ironwood reuses Orchard's note and
/// nullifier types (note version V3), so without the marker its wallet note
/// type would be the same type as the Orchard one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ironwood;

/// Wallet note, shielded output with metadata relevant to the wallet. `P` is
/// the pool marker ([`Sapling`], [`Orchard`] or [`Ironwood`]).
#[derive(Debug, Clone)]
pub struct WalletNote<N, Nf: Copy, P> {
    /// Output ID.
    pub(crate) output_id: OutputId,
    /// Identifier for key used to decrypt output.
    pub(crate) key_id: KeyId,
    /// Decrypted note with recipient and value.
    pub(crate) note: N,
    /// Derived nullifier.
    pub(crate) nullifier: Option<Nf>, //TODO: syncing without nullifier deriving key
    /// Commitment tree leaf position.
    pub(crate) position: Option<Position>,
    /// Memo.
    pub(crate) memo: Memo,
    /// Transaction ID of transaction this output was spent.
    /// If `None`, output is not spent.
    pub(crate) spending_transaction: Option<TxId>,
    /// List of block ranges where the nullifiers must be re-fetched to guarantee the note has not been spent.
    /// These scan ranges were marked `ScannedWithoutMapping` or `RefetchingNullifiers` priority before this note was
    /// scanned, meaning the nullifiers were discarded due to memory constraints and will be re-fetched later in the
    /// sync process.
    pub(crate) refetch_nullifier_ranges: Vec<Range<BlockHeight>>,
    /// Pool marker.
    pub(crate) marker: PhantomData<P>,
}

/// Sapling note.
pub type SaplingNote = WalletNote<sapling_crypto::Note, sapling_crypto::Nullifier, Sapling>;

impl OutputInterface for SaplingNote {
    type KeyId = KeyId;
    type Input = sapling_crypto::Nullifier;

    const POOL_TYPE: PoolType = PoolType::Shielded(ShieldedPool::Sapling);

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> KeyId {
        self.key_id
    }

    fn spending_transaction(&self) -> Option<TxId> {
        self.spending_transaction
    }

    fn set_spending_transaction(&mut self, spending_transaction: Option<TxId>) {
        self.spending_transaction = spending_transaction;
    }

    fn value(&self) -> u64 {
        self.note.value().inner()
    }

    fn spend_link(&self) -> Option<Self::Input> {
        self.nullifier
    }

    fn transaction_inputs(transaction: &WalletTransaction) -> Vec<&Self::Input> {
        transaction.sapling_nullifiers()
    }

    fn transaction_outputs(transaction: &WalletTransaction) -> &[Self] {
        &transaction.sapling_notes
    }
}

impl NoteInterface for SaplingNote {
    type ZcashNote = sapling_crypto::Note;
    type Nullifier = Self::Input;

    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Sapling;

    fn note(&self) -> &Self::ZcashNote {
        &self.note
    }

    fn nullifier(&self) -> Option<Self::Nullifier> {
        self.nullifier
    }

    fn position(&self) -> Option<Position> {
        self.position
    }

    fn memo(&self) -> &Memo {
        &self.memo
    }

    fn refetch_nullifier_ranges(&self) -> &[Range<BlockHeight>] {
        &self.refetch_nullifier_ranges
    }
}

/// Orchard note.
pub type OrchardNote = WalletNote<orchard::Note, orchard::note::Nullifier, Orchard>;

impl OutputInterface for OrchardNote {
    type KeyId = KeyId;
    type Input = orchard::note::Nullifier;

    const POOL_TYPE: PoolType = PoolType::Shielded(ShieldedPool::Orchard);

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> KeyId {
        self.key_id
    }

    fn spending_transaction(&self) -> Option<TxId> {
        self.spending_transaction
    }

    fn set_spending_transaction(&mut self, spending_transaction: Option<TxId>) {
        self.spending_transaction = spending_transaction;
    }

    fn value(&self) -> u64 {
        self.note.value().inner()
    }

    fn spend_link(&self) -> Option<Self::Input> {
        self.nullifier
    }

    fn transaction_inputs(transaction: &WalletTransaction) -> Vec<&Self::Input> {
        transaction.orchard_nullifiers()
    }

    fn transaction_outputs(transaction: &WalletTransaction) -> &[Self] {
        &transaction.orchard_notes
    }
}

impl NoteInterface for OrchardNote {
    type ZcashNote = orchard::Note;
    type Nullifier = Self::Input;

    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Orchard;

    fn note(&self) -> &Self::ZcashNote {
        &self.note
    }

    fn nullifier(&self) -> Option<Self::Nullifier> {
        self.spend_link()
    }

    fn position(&self) -> Option<Position> {
        self.position
    }

    fn memo(&self) -> &Memo {
        &self.memo
    }

    fn refetch_nullifier_ranges(&self) -> &[Range<BlockHeight>] {
        &self.refetch_nullifier_ranges
    }
}

/// Ironwood note. Shares Orchard's note and nullifier types (version V3) but
/// belongs to the Ironwood pool with its own note commitment tree.
pub type IronwoodNote = WalletNote<orchard::Note, orchard::note::Nullifier, Ironwood>;

impl OutputInterface for IronwoodNote {
    type KeyId = KeyId;
    type Input = orchard::note::Nullifier;

    const POOL_TYPE: PoolType = PoolType::Shielded(ShieldedPool::Ironwood);

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> KeyId {
        self.key_id
    }

    fn spending_transaction(&self) -> Option<TxId> {
        self.spending_transaction
    }

    fn set_spending_transaction(&mut self, spending_transaction: Option<TxId>) {
        self.spending_transaction = spending_transaction;
    }

    fn value(&self) -> u64 {
        self.note.value().inner()
    }

    fn spend_link(&self) -> Option<Self::Input> {
        self.nullifier
    }

    fn transaction_inputs(transaction: &WalletTransaction) -> Vec<&Self::Input> {
        transaction.ironwood_nullifiers()
    }

    fn transaction_outputs(transaction: &WalletTransaction) -> &[Self] {
        &transaction.ironwood_notes
    }
}

impl NoteInterface for IronwoodNote {
    type ZcashNote = orchard::Note;
    type Nullifier = Self::Input;

    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Ironwood;

    fn note(&self) -> &Self::ZcashNote {
        &self.note
    }

    fn nullifier(&self) -> Option<Self::Nullifier> {
        self.spend_link()
    }

    fn position(&self) -> Option<Position> {
        self.position
    }

    fn memo(&self) -> &Memo {
        &self.memo
    }

    fn refetch_nullifier_ranges(&self) -> &[Range<BlockHeight>] {
        &self.refetch_nullifier_ranges
    }
}

/// Provides a common API for all outgoing note types.
pub trait OutgoingNoteInterface: Sized {
    /// Decrypted note type.
    type ZcashNote;
    /// Address type.
    type Address: Clone + Copy + Debug + PartialEq + Eq;
    /// Encoding error
    type Error: Debug + std::error::Error;

    /// Note's associated shielded protocol.
    const SHIELDED_PROTOCOL: ShieldedPool;

    /// Output ID.
    fn output_id(&self) -> OutputId;

    /// Identifier for key used to decrypt outgoing note.
    fn key_id(&self) -> KeyId;

    /// Note value.
    fn value(&self) -> u64;

    /// Decrypted note with recipient and value.
    fn note(&self) -> &Self::ZcashNote;

    /// Memo.
    fn memo(&self) -> &Memo;

    /// Recipient address.
    fn recipient(&self) -> Self::Address;

    /// Recipient unified address as given by recipient and recorded in an encoded memo (all original receivers).
    fn recipient_full_unified_address(&self) -> Option<&UnifiedAddress>;

    /// Encoded recipient address recorded in note on chain (single receiver).
    fn encoded_recipient<P>(&self, parameters: &P) -> Result<String, Self::Error>
    where
        P: consensus::Parameters + consensus::NetworkConstants;

    /// Encoded recipient unified address as given by recipient and recorded in an encoded memo (all original receivers).
    fn encoded_recipient_full_unified_address<P>(&self, consensus_parameters: &P) -> Option<String>
    where
        P: consensus::Parameters + consensus::NetworkConstants;

    /// Outgoing notes within `transaction`.
    fn transaction_outgoing_notes(transaction: &WalletTransaction) -> &[Self];
}

/// Note sent from this capability to a recipient. `P` is the pool marker
/// ([`Sapling`], [`Orchard`] or [`Ironwood`]).
#[derive(Debug, Clone, PartialEq)]
pub struct OutgoingNote<N, P> {
    /// Output ID.
    pub(crate) output_id: OutputId,
    /// Identifier for key used to decrypt output.
    pub(crate) key_id: KeyId,
    /// Decrypted note with recipient and value.
    pub(crate) note: N,
    /// Memo.
    pub(crate) memo: Memo,
    /// Recipient's full unified address from encoded memo.
    pub(crate) recipient_full_unified_address: Option<UnifiedAddress>,
    /// Pool marker.
    pub(crate) marker: PhantomData<P>,
}

/// Outgoing sapling note.
pub type OutgoingSaplingNote = OutgoingNote<sapling_crypto::Note, Sapling>;

impl OutgoingNoteInterface for OutgoingSaplingNote {
    type ZcashNote = sapling_crypto::Note;
    type Address = sapling_crypto::PaymentAddress;
    type Error = Infallible;

    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Sapling;

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> KeyId {
        self.key_id
    }

    fn value(&self) -> u64 {
        self.note.value().inner()
    }

    fn note(&self) -> &Self::ZcashNote {
        &self.note
    }

    fn memo(&self) -> &Memo {
        &self.memo
    }

    fn recipient(&self) -> Self::Address {
        self.note.recipient()
    }

    fn recipient_full_unified_address(&self) -> Option<&UnifiedAddress> {
        self.recipient_full_unified_address.as_ref()
    }

    fn encoded_recipient<P>(&self, consensus_parameters: &P) -> Result<String, Self::Error>
    where
        P: consensus::Parameters + consensus::NetworkConstants,
    {
        Ok(encode_payment_address(
            zcash_address::constants::hrp_sapling_payment_address(
                consensus_parameters.network_type(),
            ),
            &self.note().recipient(),
        ))
    }

    fn encoded_recipient_full_unified_address<P>(&self, consensus_parameters: &P) -> Option<String>
    where
        P: consensus::Parameters + consensus::NetworkConstants,
    {
        self.recipient_full_unified_address
            .as_ref()
            .map(|unified_address| unified_address.encode(consensus_parameters))
    }

    fn transaction_outgoing_notes(transaction: &WalletTransaction) -> &[Self] {
        &transaction.outgoing_sapling_notes
    }
}

/// Outgoing orchard note.
pub type OutgoingOrchardNote = OutgoingNote<orchard::Note, Orchard>;

impl OutgoingNoteInterface for OutgoingOrchardNote {
    type ZcashNote = orchard::Note;
    type Address = orchard::Address;
    type Error = ParseError;

    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Orchard;

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> KeyId {
        self.key_id
    }

    fn value(&self) -> u64 {
        self.note.value().inner()
    }

    fn note(&self) -> &Self::ZcashNote {
        &self.note
    }

    fn memo(&self) -> &Memo {
        &self.memo
    }

    fn recipient(&self) -> Self::Address {
        self.note.recipient()
    }

    fn recipient_full_unified_address(&self) -> Option<&UnifiedAddress> {
        self.recipient_full_unified_address.as_ref()
    }

    fn encoded_recipient<P>(&self, parameters: &P) -> Result<String, Self::Error>
    where
        P: consensus::Parameters + consensus::NetworkConstants,
    {
        keys::encode_orchard_receiver(parameters, &self.note().recipient())
    }

    fn encoded_recipient_full_unified_address<P>(&self, consensus_parameters: &P) -> Option<String>
    where
        P: consensus::Parameters + consensus::NetworkConstants,
    {
        self.recipient_full_unified_address
            .as_ref()
            .map(|unified_address| unified_address.encode(consensus_parameters))
    }

    fn transaction_outgoing_notes(transaction: &WalletTransaction) -> &[Self] {
        &transaction.outgoing_orchard_notes
    }
}

/// Outgoing ironwood note. Shares Orchard's note and receiver types.
pub type OutgoingIronwoodNote = OutgoingNote<orchard::Note, Ironwood>;

impl OutgoingNoteInterface for OutgoingIronwoodNote {
    type ZcashNote = orchard::Note;
    type Address = orchard::Address;
    type Error = ParseError;

    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Ironwood;

    fn output_id(&self) -> OutputId {
        self.output_id
    }

    fn key_id(&self) -> KeyId {
        self.key_id
    }

    fn value(&self) -> u64 {
        self.note.value().inner()
    }

    fn note(&self) -> &Self::ZcashNote {
        &self.note
    }

    fn memo(&self) -> &Memo {
        &self.memo
    }

    fn recipient(&self) -> Self::Address {
        self.note.recipient()
    }

    fn recipient_full_unified_address(&self) -> Option<&UnifiedAddress> {
        self.recipient_full_unified_address.as_ref()
    }

    fn encoded_recipient<P>(&self, parameters: &P) -> Result<String, Self::Error>
    where
        P: consensus::Parameters + consensus::NetworkConstants,
    {
        keys::encode_orchard_receiver(parameters, &self.note().recipient())
    }

    fn encoded_recipient_full_unified_address<P>(&self, consensus_parameters: &P) -> Option<String>
    where
        P: consensus::Parameters + consensus::NetworkConstants,
    {
        self.recipient_full_unified_address
            .as_ref()
            .map(|unified_address| unified_address.encode(consensus_parameters))
    }

    fn transaction_outgoing_notes(transaction: &WalletTransaction) -> &[Self] {
        &transaction.outgoing_ironwood_notes
    }
}

/// Reduces the wallet to what a build that never tracked `pool` would have
/// left behind: the very same scanned ranges, and none of that pool's data.
///
/// This is the state a wallet reaches by syncing across a pool's activation
/// on a build that predates the pool, which is not otherwise constructible
/// from outside. Scan-range priorities are deliberately untouched, since the
/// defect being reproduced is precisely that the ranges still claim to be
/// scanned.
#[cfg(any(test, feature = "test-features"))]
pub fn strip_pool_tracking_for_test<W>(wallet: &mut W, pool: ShieldedPool) -> Result<(), W::Error>
where
    W: traits::SyncWallet
        + traits::SyncBlocks
        + traits::SyncTransactions
        + traits::SyncNullifiers
        + traits::SyncShardTrees,
{
    for block in wallet.get_wallet_blocks_mut()?.values_mut() {
        let tree_bounds = &mut block.tree_bounds;
        match pool {
            ShieldedPool::Sapling => {
                tree_bounds.sapling_initial_tree_size = 0;
                tree_bounds.sapling_final_tree_size = 0;
            }
            ShieldedPool::Orchard => {
                tree_bounds.orchard_initial_tree_size = 0;
                tree_bounds.orchard_final_tree_size = 0;
            }
            ShieldedPool::Ironwood => {
                tree_bounds.ironwood_initial_tree_size = 0;
                tree_bounds.ironwood_final_tree_size = 0;
            }
        }
    }
    for transaction in wallet.get_wallet_transactions_mut()?.values_mut() {
        match pool {
            ShieldedPool::Sapling => {
                transaction.sapling_notes.clear();
                transaction.outgoing_sapling_notes.clear();
            }
            ShieldedPool::Orchard => {
                transaction.orchard_notes.clear();
                transaction.outgoing_orchard_notes.clear();
            }
            ShieldedPool::Ironwood => {
                transaction.ironwood_notes.clear();
                transaction.outgoing_ironwood_notes.clear();
            }
        }
    }

    let nullifiers = wallet.get_nullifiers_mut()?;
    match pool {
        ShieldedPool::Sapling => nullifiers.sapling.clear(),
        ShieldedPool::Orchard => nullifiers.orchard.clear(),
        ShieldedPool::Ironwood => nullifiers.ironwood.clear(),
    }

    let empty = ShardTrees::new();
    let shard_trees = wallet.get_shard_trees_mut()?;
    match pool {
        ShieldedPool::Sapling => shard_trees.sapling = empty.sapling,
        ShieldedPool::Orchard => shard_trees.orchard = empty.orchard,
        ShieldedPool::Ironwood => shard_trees.ironwood = empty.ironwood,
    }

    let sync_state = wallet.get_sync_state_mut()?;
    match pool {
        ShieldedPool::Sapling => sync_state.sapling_shard_ranges.clear(),
        ShieldedPool::Orchard => sync_state.orchard_shard_ranges.clear(),
        ShieldedPool::Ironwood => sync_state.ironwood_shard_ranges.clear(),
    }

    Ok(())
}

// TODO: allow consumer to define shard store. memory shard store has infallible error type but other may not so error
// handling will need to replace expects
/// Type alias for sapling memory shard store
pub type SaplingShardStore = MemoryShardStore<sapling_crypto::Node, BlockHeight>;

/// Type alias for orchard memory shard store
pub type OrchardShardStore = MemoryShardStore<MerkleHashOrchard, BlockHeight>;

/// Shard tree wallet data struct
#[derive(Debug)]
pub struct ShardTrees {
    /// Sapling shard tree
    pub sapling: ShardTree<
        SaplingShardStore,
        { sapling_crypto::NOTE_COMMITMENT_TREE_DEPTH },
        { witness::SHARD_HEIGHT },
    >,
    /// Orchard shard tree
    pub orchard: ShardTree<
        OrchardShardStore,
        { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 },
        { witness::SHARD_HEIGHT },
    >,
    /// Ironwood shard tree. Ironwood reuses the Orchard note commitment tree
    /// structure (same hash and depth), so it has the same shape as `orchard`.
    pub ironwood: ShardTree<
        OrchardShardStore,
        { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 },
        { witness::SHARD_HEIGHT },
    >,
}

impl ShardTrees {
    /// Create new `ShardTrees`
    #[must_use]
    pub fn new() -> Self {
        Self {
            sapling: empty_shard_tree(),
            orchard: empty_shard_tree(),
            ironwood: empty_shard_tree(),
        }
    }

    /// Replaces one pool's shard tree with an empty tree, leaving the other
    /// pools alone.
    ///
    /// The empty tree is that pool's correct state at its own activation, so
    /// this is the rollback a pool needs when its recorded history cannot be
    /// trusted and no checkpoint survives to roll back to.
    pub(crate) fn clear_pool(&mut self, pool: ShieldedPool) {
        tracing::info!("Clearing {pool:?} shard tree.");
        match pool {
            ShieldedPool::Sapling => self.sapling = empty_shard_tree(),
            ShieldedPool::Orchard => self.orchard = empty_shard_tree(),
            ShieldedPool::Ironwood => self.ironwood = empty_shard_tree(),
        }
    }
}

impl Default for ShardTrees {
    fn default() -> Self {
        Self::new()
    }
}

/// An empty shard tree with the crate's standard checkpoint retention and
/// the zero-height checkpoint that every fresh tree must carry.
pub(crate) fn empty_shard_tree<H, const DEPTH: u8, const SHARD_HEIGHT: u8>()
-> ShardTree<MemoryShardStore<H, BlockHeight>, DEPTH, SHARD_HEIGHT>
where
    H: incrementalmerkletree::Hashable + Clone + PartialEq,
{
    let mut tree = ShardTree::new(
        MemoryShardStore::empty(),
        SHARDTREE_CHECKPOINT_ROLLING_WINDOW_SIZE as usize,
    );

    // `NotAboveNewest` is impossible on an empty checkpoint store.
    assert_eq!(
        tree.append_checkpoint(BlockHeight::from_u32(0))
            .expect("should never fail"),
        CheckpointAppendOutcome::Appended
    );

    tree
}

use shardtree::store::ShardStore;

pub(crate) trait SyncDomain {
    const SHIELDED_PROTOCOL: ShieldedPool;

    type Note: NoteInterface;
    type ShardStore: ShardStore<CheckpointId = BlockHeight>;

    fn notes_mut(wallet_transaction: &mut WalletTransaction) -> Vec<&mut Self::Note>;
}

impl SyncDomain for Sapling {
    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Sapling;

    type Note = SaplingNote;
    type ShardStore = SaplingShardStore;

    fn notes_mut(wallet_transaction: &mut WalletTransaction) -> Vec<&mut Self::Note> {
        wallet_transaction.sapling_notes_mut()
    }
}

impl SyncDomain for Orchard {
    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Orchard;

    type Note = OrchardNote;
    type ShardStore = OrchardShardStore;

    fn notes_mut(wallet_transaction: &mut WalletTransaction) -> Vec<&mut Self::Note> {
        wallet_transaction.orchard_notes_mut()
    }
}

impl SyncDomain for Ironwood {
    const SHIELDED_PROTOCOL: ShieldedPool = ShieldedPool::Ironwood;

    type Note = IronwoodNote;
    // Ironwood reuses the Orchard note commitment tree hash, so the same
    // store type serves its (separate) tree.
    type ShardStore = OrchardShardStore;

    fn notes_mut(wallet_transaction: &mut WalletTransaction) -> Vec<&mut Self::Note> {
        wallet_transaction.ironwood_notes_mut()
    }
}

#[cfg(test)]
mod test {
    use zcash_protocol::TxId;
    use zcash_protocol::consensus::BlockHeight;
    use zingo_status::confirmation_status::ConfirmationStatus;

    use super::WalletTransaction;

    fn transaction_with_status(status: ConfirmationStatus) -> WalletTransaction {
        WalletTransaction::new_for_test(TxId::from_bytes([0; 32]), status)
    }

    #[test]
    fn update_status_follows_transaction_lifecycle() {
        let mut transaction =
            transaction_with_status(ConfirmationStatus::Calculated(BlockHeight::from_u32(10)));

        transaction.update_status(
            ConfirmationStatus::Transmitted(BlockHeight::from_u32(10)),
            1,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Transmitted(_)
        ));

        transaction.update_status(
            ConfirmationStatus::Mempool(BlockHeight::from_u32(11)),
            2,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Mempool(_)
        ));

        transaction.update_status(
            ConfirmationStatus::Confirmed(BlockHeight::from_u32(11)),
            3,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Confirmed(_)
        ));
    }

    #[test]
    fn update_status_failed_returns_to_mempool() {
        let mut transaction =
            transaction_with_status(ConfirmationStatus::Failed(BlockHeight::from_u32(10)));

        transaction.update_status(
            ConfirmationStatus::Mempool(BlockHeight::from_u32(11)),
            1,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Mempool(_)
        ));
    }

    #[test]
    fn update_status_failed_is_not_directly_confirmable() {
        // confirming a failed transaction is handled by replacing the whole record during block
        // scanning, not by a status update.
        let mut transaction =
            transaction_with_status(ConfirmationStatus::Failed(BlockHeight::from_u32(10)));

        transaction.update_status(
            ConfirmationStatus::Confirmed(BlockHeight::from_u32(11)),
            1,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Failed(_)
        ));
    }

    #[test]
    fn update_status_confirmed_is_terminal() {
        let mut transaction =
            transaction_with_status(ConfirmationStatus::Confirmed(BlockHeight::from_u32(10)));

        transaction.update_status(
            ConfirmationStatus::Mempool(BlockHeight::from_u32(11)),
            1,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Confirmed(_)
        ));

        transaction.update_status(
            ConfirmationStatus::Failed(BlockHeight::from_u32(11)),
            2,
            false,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Confirmed(_)
        ));
    }

    #[test]
    fn update_status_forces_confirmed_to_fail() {
        let mut transaction =
            transaction_with_status(ConfirmationStatus::Confirmed(BlockHeight::from_u32(10)));

        transaction.update_status(
            ConfirmationStatus::Failed(BlockHeight::from_u32(11)),
            2,
            true,
        );
        assert!(matches!(
            transaction.status(),
            ConfirmationStatus::Failed(_)
        ));
    }
}