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
//! Types related to the construction and evaluation of transaction proposals.
use std::{
collections::{BTreeMap, BTreeSet},
fmt::{self, Debug, Display},
};
use nonempty::NonEmpty;
use zcash_primitives::transaction::{TxId, TxVersion};
use zcash_protocol::{
PoolType, ShieldedPool,
consensus::{BlockHeight, BranchId},
value::Zatoshis,
};
use zip321::{TransactionRequest, Zip321Error};
#[cfg(feature = "orchard")]
use {
zcash_primitives::transaction::builder::BundlePadding,
zcash_protocol::zip318::PoolMigrationConstants,
};
use crate::{
data_api::wallet::{ConfirmationsPolicy, TargetHeight},
fees::TransactionBalance,
wallet::{Note, OutputRef, ReceivedNote, WalletTransparentOutput},
};
/// Errors that can occur in construction of a [`Step`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ProposalError {
/// The total output value of the transaction request is not a valid Zcash amount.
RequestTotalInvalid,
/// The total of transaction inputs overflows the valid range of Zcash values.
Overflow,
/// The input total and output total of the payment request are not equal to one another. The
/// sum of transaction outputs, change, and fees is required to be exactly equal to the value
/// of provided inputs.
BalanceError {
input_total: Zatoshis,
output_total: Zatoshis,
},
/// The `is_shielding` flag may only be set to `true` under the following conditions:
/// * The total of transparent inputs is nonzero
/// * There exist no Sapling inputs
/// * There provided transaction request is empty; i.e. the only output values specified
/// are change and fee amounts.
ShieldingInvalid,
/// No anchor information could be obtained for the specified block height.
AnchorNotFound(BlockHeight),
/// A proposal step produces a shielded bundle — it spends shielded notes, pays to a shielded
/// pool, or returns shielded change — but does not specify an anchor height against which its
/// shielded-tree lookups are performed. Only a purely transparent step may omit its anchor.
MissingShieldedAnchor,
/// A reference to the output of a prior step is invalid.
ReferenceError(StepOutput),
/// An attempted double-spend of a prior step output was detected.
StepDoubleSpend(StepOutput),
/// An attempted double-spend of an output belonging to the wallet was detected.
ChainDoubleSpend(OutputRef),
/// An input selected by the proposal could not be locked, because a concurrent
/// proposal or PCZT already holds a lock on it.
///
/// This is a transient condition, not a defect in the proposal itself: the wrapped
/// output was spendable when it was selected, but another in-flight proposal locked
/// it first. Callers should treat this as "the account is busy" and retry proposal
/// creation; the retry will select around the locked output (or fail with an
/// insufficient-funds error if no other outputs are available).
InputsLocked(OutputRef),
/// There was a mismatch between the payments in the proposal's transaction request
/// and the payment pool selection values.
PaymentPoolsMismatch,
/// The proposal tried to spend a change output. Mark the `ChangeValue` as ephemeral if this is intended.
SpendsChange(StepOutput),
/// The proposal results in an invalid payment request according to ZIP-321.
Zip321(Zip321Error),
/// The ZIP 321 payment request at the wrapped index lacked payment amount information.
PaymentAmountMissing(usize),
/// A proposal step created an ephemeral output that was not spent in any later step.
#[cfg(feature = "transparent-inputs")]
EphemeralOutputLeftUnspent(StepOutput),
/// The proposal included a payment to a TEX address and a spend from a shielded input in the same step.
#[cfg(feature = "transparent-inputs")]
PaysTexFromShielded,
/// The change strategy provided to input selection failed to correctly generate an ephemeral
/// change output when needed for sending to a TEX address.
#[cfg(feature = "transparent-inputs")]
EphemeralOutputsInvalid,
/// The requested proposal would link activity on an ephemeral address to other wallet
/// activity.
#[cfg(feature = "transparent-inputs")]
EphemeralAddressLinkability,
/// A shielding proposal was constructed with a destination address that has no shielded
/// receiver. Shielding requires the destination to be able to receive shielded value.
#[cfg(feature = "transparent-inputs")]
ShieldingRequiresShieldedRecipient,
/// The transaction version requested is not compatible with the consensus branch for which the
/// transaction is intended.
IncompatibleTxVersion(BranchId),
/// After NU6.3 activation, a payment to an Orchard receiver must be delivered through the
/// Ironwood pool, which requires a version 6 transaction. The explicitly-requested transaction
/// version has no Ironwood bundle, so it cannot carry the payment. (The Orchard turnstile is a
/// consensus rule after NU6.3: no payment may add value to the Orchard pool, so such a payment
/// cannot be delivered as a plain Orchard output either.)
OrchardReceiverRequiresIronwood(TxVersion),
/// After Ironwood activation, a proposal step would create value in the Orchard pool.
/// The turnstile only permits value to leave the pool: a step may return change to it
/// only when strictly less value returns than the step's Orchard inputs remove.
/// (Payments may never be directed to the Orchard pool after Ironwood activation;
/// payment classification maintains that invariant, and step construction enforces it
/// via [`ProposalError::OrchardPoolPayment`].)
#[cfg(feature = "orchard")]
OrchardPoolValueCreation {
/// The total value of the Orchard notes spent by the step.
input_total: Zatoshis,
/// The total value of the Orchard-pool change outputs created by the step.
output_total: Zatoshis,
},
/// After Ironwood activation, the payment at the wrapped index of the step's
/// transaction request was directed to the Orchard pool. The turnstile only permits
/// value to leave the pool, so no payment may be directed to it; payment
/// classification routes Orchard-receiver payments to the Ironwood pool instead.
#[cfg(feature = "orchard")]
OrchardPoolPayment(usize),
}
impl Display for ProposalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProposalError::RequestTotalInvalid => write!(
f,
"The total requested output value is not a valid Zcash amount."
),
ProposalError::Overflow => write!(
f,
"The total of transaction inputs overflows the valid range of Zcash values."
),
ProposalError::BalanceError {
input_total,
output_total,
} => write!(
f,
"Balance error: the output total {} was not equal to the input total {}",
u64::from(*output_total),
u64::from(*input_total)
),
ProposalError::ShieldingInvalid => write!(
f,
"The proposal violates the rules for a shielding transaction."
),
ProposalError::AnchorNotFound(h) => {
write!(f, "Unable to compute anchor for block height {h:?}")
}
ProposalError::MissingShieldedAnchor => write!(
f,
"A proposal step that produces a shielded bundle must specify an anchor height."
),
ProposalError::ReferenceError(r) => {
write!(f, "No prior step output found for reference {r:?}")
}
ProposalError::StepDoubleSpend(r) => write!(
f,
"The proposal uses the output of step {r:?} in more than one place."
),
ProposalError::ChainDoubleSpend(output_ref) => write!(
f,
"The proposal attempts to spend the same output twice: {}, {}, {}",
output_ref.pool(),
output_ref.txid(),
output_ref.output_index()
),
ProposalError::InputsLocked(output_ref) => write!(
f,
"A selected input is locked by a concurrent proposal (retry later): {}, {}, {}",
output_ref.pool(),
output_ref.txid(),
output_ref.output_index()
),
ProposalError::PaymentPoolsMismatch => write!(
f,
"The chosen payment pools did not match the payments of the transaction request."
),
ProposalError::SpendsChange(r) => write!(
f,
"The proposal attempts to spends the change output created at step {r:?}.",
),
ProposalError::Zip321(r) => {
write!(f, "The proposal results in an invalid payment {r:?}.",)
}
ProposalError::PaymentAmountMissing(idx) => {
write!(
f,
"Payment amount not specified for requested payment at index {idx}."
)
}
#[cfg(feature = "transparent-inputs")]
ProposalError::EphemeralOutputLeftUnspent(r) => write!(
f,
"The proposal created an ephemeral output at step {r:?} that was not spent in any later step.",
),
#[cfg(feature = "transparent-inputs")]
ProposalError::PaysTexFromShielded => write!(
f,
"The proposal included a payment to a TEX address and a spend from a shielded input in the same step.",
),
#[cfg(feature = "transparent-inputs")]
ProposalError::EphemeralOutputsInvalid => write!(
f,
"The proposal generator failed to correctly generate an ephemeral change output when needed for sending to a TEX address."
),
#[cfg(feature = "transparent-inputs")]
ProposalError::EphemeralAddressLinkability => write!(
f,
"The proposal requested spending funds in a way that would link activity on an ephemeral address to other wallet activity."
),
#[cfg(feature = "transparent-inputs")]
ProposalError::ShieldingRequiresShieldedRecipient => write!(
f,
"A shielding proposal's destination must have a shielded receiver."
),
#[cfg(feature = "orchard")]
ProposalError::OrchardPoolValueCreation {
input_total,
output_total,
} => write!(
f,
"After Ironwood activation, a step that spends {} zatoshis from the Orchard pool may not return {} zatoshis to it.",
u64::from(*input_total),
u64::from(*output_total),
),
#[cfg(feature = "orchard")]
ProposalError::OrchardPoolPayment(index) => write!(
f,
"After Ironwood activation, no payment may be directed to the Orchard pool (payment index {index})."
),
ProposalError::IncompatibleTxVersion(branch_id) => write!(
f,
"The requested transaction version is incompatible with consensus branch {branch_id:?}"
),
ProposalError::OrchardReceiverRequiresIronwood(version) => write!(
f,
"After NU6.3 activation, a payment to an Orchard receiver requires a version 6 (Ironwood) transaction, but version {version:?} was requested."
),
}
}
}
impl std::error::Error for ProposalError {}
/// The Sapling inputs to a proposed transaction.
#[derive(Clone, PartialEq, Eq)]
pub struct ShieldedInputs<NoteRef> {
notes: NonEmpty<ReceivedNote<NoteRef, Note>>,
}
impl<NoteRef> ShieldedInputs<NoteRef> {
/// Constructs a [`ShieldedInputs`] from its constituent parts.
pub fn from_parts(notes: NonEmpty<ReceivedNote<NoteRef, Note>>) -> Self {
Self { notes }
}
/// Returns the list of Sapling notes to be used as inputs to the proposed transaction.
pub fn notes(&self) -> &NonEmpty<ReceivedNote<NoteRef, Note>> {
&self.notes
}
}
/// A proposal for a series of transactions to be created.
///
/// Each step of the proposal represents a separate transaction to be created. At present, only
/// transparent outputs of earlier steps may be spent in later steps; the ability to chain shielded
/// transaction steps may be added in a future update.
#[derive(Clone, PartialEq, Eq)]
pub struct Proposal<FeeRuleT, NoteRef> {
fee_rule: FeeRuleT,
min_target_height: TargetHeight,
/// The confirmations policy under which the proposal was constructed. It is used to resolve
/// the anchor for a step that carries no explicit anchor height (a purely transparent step;
/// see [`Step::anchor_height`]).
confirmations_policy: ConfirmationsPolicy,
steps: NonEmpty<Step<NoteRef>>,
/// The transaction version explicitly requested when the proposal was constructed, if any.
/// When `None`, the transaction is built at the version implied by the target height (version 6
/// from NU6.3 onward).
proposed_version: Option<TxVersion>,
}
impl<FeeRuleT, NoteRef> Proposal<FeeRuleT, NoteRef> {
/// Constructs a validated multi-step [`Proposal`].
///
/// This operation validates the proposal for agreement between outputs and inputs
/// in the case of multi-step proposals, and ensures that no double-spends are being
/// proposed.
///
/// Parameters:
/// * `fee_rule`: The fee rule observed by the proposed transaction.
/// * `min_target_height`: The minimum block height at which the transaction may be created.
/// * `steps`: A vector of steps that make up the proposal.
pub fn multi_step(
fee_rule: FeeRuleT,
min_target_height: TargetHeight,
confirmations_policy: ConfirmationsPolicy,
steps: NonEmpty<Step<NoteRef>>,
) -> Result<Self, ProposalError> {
let mut consumed_chain_inputs: BTreeSet<OutputRef> = BTreeSet::new();
let mut consumed_prior_inputs: BTreeSet<StepOutput> = BTreeSet::new();
for (i, step) in steps.iter().enumerate() {
for prior_ref in step.prior_step_inputs() {
// check that there are no forward references
if prior_ref.step_index() >= i {
return Err(ProposalError::ReferenceError(*prior_ref));
}
// check that the reference is valid
let prior_step = &steps[prior_ref.step_index()];
match prior_ref.output_index() {
StepOutputIndex::Payment(idx) => {
if prior_step.transaction_request().payments().len() <= idx {
return Err(ProposalError::ReferenceError(*prior_ref));
}
}
StepOutputIndex::Change(idx) => {
if prior_step.balance().proposed_change().len() <= idx {
return Err(ProposalError::ReferenceError(*prior_ref));
}
}
}
// check that there are no double-spends
if !consumed_prior_inputs.insert(*prior_ref) {
return Err(ProposalError::StepDoubleSpend(*prior_ref));
}
}
for t_out in step.transparent_inputs() {
let output_ref = OutputRef::new(
TxId::from_bytes(*t_out.outpoint().hash()),
PoolType::TRANSPARENT,
t_out.outpoint().n(),
);
if !consumed_chain_inputs.insert(output_ref) {
return Err(ProposalError::ChainDoubleSpend(output_ref));
}
}
for s_out in step.shielded_inputs().iter().flat_map(|i| i.notes().iter()) {
let output_ref = OutputRef::new(
*s_out.txid(),
PoolType::Shielded(s_out.note().pool()),
s_out.output_index().into(),
);
if !consumed_chain_inputs.insert(output_ref) {
return Err(ProposalError::ChainDoubleSpend(output_ref));
}
}
}
Ok(Self {
fee_rule,
min_target_height,
confirmations_policy,
proposed_version: None,
steps,
})
}
/// Constructs a validated [`Proposal`] having only a single step from its constituent parts.
///
/// This operation validates the proposal for balance consistency and agreement between
/// the `is_shielding` flag and the structure of the proposal.
///
/// Parameters:
/// * `transaction_request`: The ZIP 321 transaction request describing the payments to be
/// made.
/// * `payment_pools`: A map from payment index to pool type.
/// * `transparent_inputs`: The set of previous transparent outputs to be spent.
/// * `shielded_inputs`: The sets of previous shielded outputs to be spent.
/// * `anchor_height`: See [`Step::from_parts`].
/// * `balance`: The change outputs to be added the transaction and the fee to be paid.
/// * `fee_rule`: The fee rule observed by the proposed transaction.
/// * `min_target_height`: The minimum block height at which the transaction may be created.
/// * `is_shielding`: A flag that identifies whether this is a wallet-internal shielding
/// transaction.
/// * `ironwood_active`: See [`Step::from_parts`].
#[allow(clippy::too_many_arguments)]
pub fn single_step(
transaction_request: TransactionRequest,
payment_pools: BTreeMap<usize, PoolType>,
transparent_inputs: Vec<WalletTransparentOutput<()>>,
shielded_inputs: Option<ShieldedInputs<NoteRef>>,
anchor_height: BlockHeight,
balance: TransactionBalance,
fee_rule: FeeRuleT,
min_target_height: TargetHeight,
confirmations_policy: ConfirmationsPolicy,
is_shielding: bool,
#[cfg(feature = "orchard")] ironwood_active: bool,
) -> Result<Self, ProposalError> {
Ok(Self {
fee_rule,
min_target_height,
confirmations_policy,
proposed_version: None,
steps: NonEmpty::singleton(Step::from_parts(
&[],
transaction_request,
payment_pools,
transparent_inputs,
shielded_inputs,
Some(anchor_height),
vec![],
balance,
is_shielding,
#[cfg(feature = "orchard")]
ironwood_active,
)?),
})
}
/// Returns the fee rule to be used by the transaction builder.
pub fn fee_rule(&self) -> &FeeRuleT {
&self.fee_rule
}
/// Returns the target height for which the proposal was prepared.
///
/// The chain must contain at least this many blocks in order for the proposal to
/// be executed.
pub fn min_target_height(&self) -> TargetHeight {
self.min_target_height
}
/// Returns the confirmations policy under which the proposal was constructed. It is used to
/// resolve the anchor for a step that carries no explicit anchor height (a purely transparent
/// step; see [`Step::anchor_height`]).
pub fn confirmations_policy(&self) -> ConfirmationsPolicy {
self.confirmations_policy
}
/// Returns the transaction version explicitly requested when the proposal was constructed, if
/// any. When `None`, the transaction is built at the version implied by the target height
/// (version 6 from NU6.3 onward).
pub fn proposed_version(&self) -> Option<TxVersion> {
self.proposed_version
}
/// Returns this proposal with its requested transaction version set to the given value.
///
/// This records the version passed to proposal construction so that it is carried through to
/// transaction building; it does not re-validate the proposal against the version.
pub fn with_proposed_version(mut self, proposed_version: Option<TxVersion>) -> Self {
self.proposed_version = proposed_version;
self
}
/// Returns the steps of the proposal. Each step corresponds to an independent transaction to
/// be generated as a result of this proposal.
pub fn steps(&self) -> &NonEmpty<Step<NoteRef>> {
&self.steps
}
/// Returns the total number of inputs across all steps of this proposal that belong to the
/// given pool.
///
/// For a shielded pool this is the number of spent notes of that pool (Ironwood notes are
/// counted for [`PoolType::IRONWOOD`], not [`PoolType::ORCHARD`]); for
/// [`PoolType::Transparent`] it is the number of transparent inputs. See
/// [`Step::input_count_in_pool`].
pub fn input_count_in_pool(&self, pool_type: PoolType) -> usize {
self.steps
.iter()
.map(|step| step.input_count_in_pool(pool_type))
.sum()
}
}
impl<FeeRuleT: Debug, NoteRef> Debug for Proposal<FeeRuleT, NoteRef> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Proposal")
.field("fee_rule", &self.fee_rule)
.field("min_target_height", &self.min_target_height)
.field("proposed_version", &self.proposed_version)
.field("steps", &self.steps)
.finish()
}
}
/// A reference to either a payment or change output within a step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StepOutputIndex {
Payment(usize),
Change(usize),
}
/// A reference to the output of a step in a proposal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StepOutput {
step_index: usize,
output_index: StepOutputIndex,
}
impl StepOutput {
/// Constructs a new [`StepOutput`] from its constituent parts.
pub fn new(step_index: usize, output_index: StepOutputIndex) -> Self {
Self {
step_index,
output_index,
}
}
/// Returns the step index to which this reference refers.
pub fn step_index(&self) -> usize {
self.step_index
}
/// Returns the identifier for the payment or change output within
/// the referenced step.
pub fn output_index(&self) -> StepOutputIndex {
self.output_index
}
}
/// The inputs to be consumed and outputs to be produced in a proposed transaction.
#[derive(Clone, PartialEq, Eq)]
pub struct Step<NoteRef> {
transaction_request: TransactionRequest,
payment_pools: BTreeMap<usize, PoolType>,
transparent_inputs: Vec<WalletTransparentOutput<()>>,
shielded_inputs: Option<ShieldedInputs<NoteRef>>,
/// The anchor height that binds every shielded-tree lookup performed while building this
/// step's transaction — both shielded-input witnesses and shielded-output anchors.
///
/// This is `Some` for any step that produces a shielded bundle — one that spends shielded
/// notes, pays to a shielded pool, or returns shielded change. The anchor is selected from the
/// wallet's checkpoints at proposal construction time and applied to every shielded-tree
/// lookup, so a transaction with only routed shielded outputs (for example an Orchard-receiver
/// payment routed into the Ironwood bundle post-NU6.3) remains indistinguishable from one that
/// spends real shielded notes. Only a purely transparent step may carry `None`.
anchor_height: Option<BlockHeight>,
prior_step_inputs: Vec<StepOutput>,
balance: TransactionBalance,
is_shielding: bool,
}
/// Returns whether a step produces any shielded bundle — it spends shielded notes, pays to a
/// shielded pool, or returns change to a shielded pool. Such a step performs shielded-tree lookups
/// (including the dummy spends that pad an output-only bundle so it is indistinguishable from one
/// that spends real notes), so it must bind a concrete anchor against which those lookups are made.
pub(crate) fn produces_shielded_bundle(
has_shielded_inputs: bool,
payment_pools: &BTreeMap<usize, PoolType>,
balance: &TransactionBalance,
) -> bool {
has_shielded_inputs
|| payment_pools
.values()
.any(|pool| matches!(pool, PoolType::Shielded(_)))
|| balance
.proposed_change()
.iter()
.any(|change| matches!(change.output_pool(), PoolType::Shielded(_)))
}
impl<NoteRef> Step<NoteRef> {
/// Constructs a validated [`Step`] from its constituent parts.
///
/// This operation validates the proposal for balance consistency and agreement between
/// the `is_shielding` flag and the structure of the proposal.
///
/// Parameters:
/// * `transaction_request`: The ZIP 321 transaction request describing the payments
/// to be made.
/// * `payment_pools`: A map from payment index to pool type. The set of payment indices
/// provided here must exactly match the set of payment indices in the [`TransactionRequest`],
/// and the selected pool for an index must correspond to a valid receiver of the
/// address at that index (or the address itself in the case of bare transparent or Sapling
/// addresses).
/// * `transparent_inputs`: The set of previous transparent outputs to be spent.
/// * `shielded_inputs`: The sets of previous shielded outputs to be spent.
/// * `anchor_height`: The anchor height that binds every shielded-tree lookup performed
/// while building this step's transaction — both shielded-input witnesses and
/// shielded-output anchors. A step that produces a shielded bundle (spends shielded notes,
/// pays to a shielded pool, or returns shielded change) must provide `Some`; only a purely
/// transparent step may pass `None`.
/// * `balance`: The change outputs to be added the transaction and the fee to be paid.
/// * `is_shielding`: A flag that identifies whether this is a wallet-internal shielding
/// transaction.
/// * `ironwood_active`: Whether the Ironwood pool is active at the target height for
/// which this step is proposed. When active, the step is checked against the
/// Orchard turnstile: no payment may be directed to the Orchard pool, and change
/// may be returned to it only when strictly less value returns than the step's
/// Orchard inputs remove.
#[allow(clippy::too_many_arguments)]
pub fn from_parts(
prior_steps: &[Step<NoteRef>],
transaction_request: TransactionRequest,
payment_pools: BTreeMap<usize, PoolType>,
transparent_inputs: Vec<WalletTransparentOutput<()>>,
shielded_inputs: Option<ShieldedInputs<NoteRef>>,
anchor_height: Option<BlockHeight>,
prior_step_inputs: Vec<StepOutput>,
balance: TransactionBalance,
is_shielding: bool,
#[cfg(feature = "orchard")] ironwood_active: bool,
) -> Result<Self, ProposalError> {
// Verify that the set of payment pools matches exactly a set of valid payment recipients
if transaction_request.payments().len() != payment_pools.len() {
return Err(ProposalError::PaymentPoolsMismatch);
}
for (idx, pool) in &payment_pools {
if let Some(payment) = transaction_request.payments().get(idx) {
// Ironwood notes are Orchard-shaped and delivered to the recipient's Orchard
// receiver, so an Ironwood-pool payment is valid whenever the recipient can
// receive Orchard.
let deliverable = payment.recipient_address().can_receive_as(*pool)
|| (*pool == PoolType::IRONWOOD
&& payment
.recipient_address()
.can_receive_as(PoolType::ORCHARD));
if !deliverable {
return Err(ProposalError::PaymentPoolsMismatch);
}
if payment.amount().is_none() {
return Err(ProposalError::PaymentAmountMissing(*idx));
}
} else {
return Err(ProposalError::PaymentPoolsMismatch);
}
}
let transparent_input_total = transparent_inputs
.iter()
.map(|out| out.txout().value())
.try_fold(Zatoshis::ZERO, |acc, a| {
(acc + a).ok_or(ProposalError::Overflow)
})?;
let shielded_input_total = shielded_inputs
.iter()
.flat_map(|s_in| s_in.notes().iter())
.map(|out| out.note().value())
.try_fold(Zatoshis::ZERO, |acc, a| acc + a)
.ok_or(ProposalError::Overflow)?;
let prior_step_input_total = prior_step_inputs
.iter()
.map(|s_ref| {
let step = prior_steps
.get(s_ref.step_index)
.ok_or(ProposalError::ReferenceError(*s_ref))?;
Ok(match s_ref.output_index {
StepOutputIndex::Payment(i) => step
.transaction_request
.payments()
.get(&i)
.ok_or(ProposalError::ReferenceError(*s_ref))?
.amount()
.ok_or(ProposalError::PaymentAmountMissing(i))?,
StepOutputIndex::Change(i) => step
.balance
.proposed_change()
.get(i)
.ok_or(ProposalError::ReferenceError(*s_ref))?
.value(),
})
})
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.try_fold(Zatoshis::ZERO, |acc, a| acc + a)
.ok_or(ProposalError::Overflow)?;
let input_total = (transparent_input_total + shielded_input_total + prior_step_input_total)
.ok_or(ProposalError::Overflow)?;
let request_total = transaction_request
.total()
.map_err(|_| ProposalError::RequestTotalInvalid)?
.expect("all payments previously checked to have amount values");
let output_total = (request_total + balance.total()).ok_or(ProposalError::Overflow)?;
if is_shielding
&& (transparent_input_total == Zatoshis::ZERO
|| shielded_input_total > Zatoshis::ZERO
|| request_total > Zatoshis::ZERO)
{
return Err(ProposalError::ShieldingInvalid);
}
// After Ironwood activation, the Orchard turnstile only permits value to leave
// the pool: payments may not be directed to the Orchard pool, and change may be
// returned to it only when strictly less value returns than the step's Orchard
// inputs remove.
#[cfg(feature = "orchard")]
if ironwood_active {
// With Ironwood active, payment classification routes every Orchard-receiver
// payment to the Ironwood pool before a step is constructed, so a payment
// directed to the Orchard pool here can only arise through direct misuse of
// this public constructor; reject it rather than construct a step whose
// transaction could never be mined. The only Orchard-pool outputs a step may
// create are change, which is validated below. The untrusted decode path
// rejects such a payment pool before calling `from_parts` (see
// `try_into_standard_proposal`).
if let Some((index, _)) = payment_pools
.iter()
.find(|(_, pool)| **pool == PoolType::ORCHARD)
{
return Err(ProposalError::OrchardPoolPayment(*index));
}
let orchard_input_total = shielded_inputs
.iter()
.flat_map(|s_in| s_in.notes().iter())
.filter(|n| n.note().pool() == ShieldedPool::Orchard)
.map(|n| n.note().value())
.try_fold(Zatoshis::ZERO, |acc, a| acc + a)
.ok_or(ProposalError::Overflow)?;
let orchard_change_total = balance
.proposed_change()
.iter()
.filter(|c| c.output_pool() == PoolType::ORCHARD)
.map(|c| c.value())
.try_fold(Zatoshis::ZERO, |acc, a| acc + a)
.ok_or(ProposalError::Overflow)?;
if orchard_change_total.is_positive() && orchard_change_total >= orchard_input_total {
return Err(ProposalError::OrchardPoolValueCreation {
input_total: orchard_input_total,
output_total: orchard_change_total,
});
}
}
// A step that produces any shielded bundle must bind a concrete anchor: every shielded-tree
// lookup it performs — including the dummy spends that pad an output-only bundle so it is
// indistinguishable from one that spends real notes — is made against that anchor. Only a
// purely transparent step may omit it. The untrusted decode path rejects this same
// combination at the parse boundary (see `try_into_standard_proposal`).
if anchor_height.is_none()
&& produces_shielded_bundle(shielded_inputs.is_some(), &payment_pools, &balance)
{
return Err(ProposalError::MissingShieldedAnchor);
}
if input_total == output_total {
Ok(Self {
transaction_request,
payment_pools,
transparent_inputs,
shielded_inputs,
anchor_height,
prior_step_inputs,
balance,
is_shielding,
})
} else {
Err(ProposalError::BalanceError {
input_total,
output_total,
})
}
}
/// Returns the transaction request that describes the payments to be made.
pub fn transaction_request(&self) -> &TransactionRequest {
&self.transaction_request
}
/// Returns the map from payment index to the pool that has been selected
/// for the output that will fulfill that payment.
pub fn payment_pools(&self) -> &BTreeMap<usize, PoolType> {
&self.payment_pools
}
/// Returns the transparent inputs that have been selected to fund the transaction.
pub fn transparent_inputs(&self) -> &[WalletTransparentOutput<()>] {
&self.transparent_inputs
}
/// Returns the shielded inputs that have been selected to fund the transaction.
pub fn shielded_inputs(&self) -> Option<&ShieldedInputs<NoteRef>> {
self.shielded_inputs.as_ref()
}
/// Returns the anchor height that binds every shielded-tree lookup performed while building
/// this step's transaction, or `None` for a purely transparent step that performs no such
/// lookup.
pub fn anchor_height(&self) -> Option<BlockHeight> {
self.anchor_height
}
/// Returns the inputs that should be obtained from the outputs of the transaction
/// created to satisfy a previous step of the proposal.
pub fn prior_step_inputs(&self) -> &[StepOutput] {
self.prior_step_inputs.as_ref()
}
/// Returns the change outputs to be added to the transaction and the fee to be paid.
pub fn balance(&self) -> &TransactionBalance {
&self.balance
}
/// Returns a flag indicating whether or not the proposed transaction
/// is exclusively wallet-internal (if it does not involve any external
/// recipients).
pub fn is_shielding(&self) -> bool {
self.is_shielding
}
/// Returns whether or not this proposal requires interaction with the specified pool.
pub fn involves(&self, pool_type: PoolType) -> bool {
self.input_in_pool(pool_type)
|| self.output_in_pool(pool_type)
|| self.change_in_pool(pool_type)
}
/// Returns whether or not this step spends any inputs from the given pool.
///
/// For a shielded pool this is true when a note of that protocol is spent; for
/// [`PoolType::Transparent`] it is true when the step is a shielding step or has any
/// transparent inputs.
pub fn input_in_pool(&self, pool_type: PoolType) -> bool {
match pool_type {
PoolType::Transparent => self.is_shielding() || !self.transparent_inputs().is_empty(),
PoolType::SAPLING => self.shielded_inputs().iter().any(|s_in| {
s_in.notes()
.iter()
.any(|note| matches!(note.note().pool(), ShieldedPool::Sapling))
}),
PoolType::ORCHARD => self.shielded_inputs().iter().any(|s_in| {
s_in.notes()
.iter()
.any(|note| matches!(note.note().pool(), ShieldedPool::Orchard))
}),
PoolType::IRONWOOD => self.shielded_inputs().iter().any(|s_in| {
s_in.notes()
.iter()
.any(|note| matches!(note.note().pool(), ShieldedPool::Ironwood))
}),
}
}
/// Returns whether or not this step directs any payment output to the given pool.
///
/// This does not consider change outputs; use [`Step::change_in_pool`] for those.
pub fn output_in_pool(&self, pool_type: PoolType) -> bool {
self.payment_pools().values().any(|pool| *pool == pool_type)
}
/// Returns whether or not this step directs any change output to the given pool.
pub fn change_in_pool(&self, pool_type: PoolType) -> bool {
self.balance()
.proposed_change()
.iter()
.any(|c| c.output_pool() == pool_type)
}
/// Returns the number of inputs to this step that belong to the given pool.
///
/// For a shielded pool this is the number of spent notes of that protocol; for
/// [`PoolType::Transparent`] it is the number of transparent inputs.
pub fn input_count_in_pool(&self, pool_type: PoolType) -> usize {
match pool_type {
PoolType::Transparent => self.transparent_inputs().len(),
PoolType::SAPLING => self
.shielded_inputs()
.iter()
.flat_map(|s_in| s_in.notes())
.filter(|note| note.note().pool() == ShieldedPool::Sapling)
.count(),
PoolType::ORCHARD => self
.shielded_inputs()
.iter()
.flat_map(|s_in| s_in.notes())
.filter(|note| note.note().pool() == ShieldedPool::Orchard)
.count(),
PoolType::IRONWOOD => self
.shielded_inputs()
.iter()
.flat_map(|s_in| s_in.notes())
.filter(|note| note.note().pool() == ShieldedPool::Ironwood)
.count(),
}
}
/// Returns the number of payment outputs of this step that are directed to the given pool.
///
/// This does not include change outputs; use [`Step::change_count_in_pool`] for those.
pub fn output_count_in_pool(&self, pool_type: PoolType) -> usize {
self.payment_pools()
.values()
.filter(|pool| **pool == pool_type)
.count()
}
/// Returns the number of change outputs of this step that are directed to the given pool.
pub fn change_count_in_pool(&self, pool_type: PoolType) -> usize {
self.balance()
.proposed_change()
.iter()
.filter(|c| c.output_pool() == pool_type)
.count()
}
/// The value of this step's sole Ironwood PAYMENT output, or `None` when the step has any
/// number of Ironwood payment outputs other than exactly one, or when that output's value is
/// not determined (a ZIP 321 payment may carry no amount).
///
/// Change is deliberately not considered. The fee model must reach the same verdict as
/// [`Step::is_canonical_crossing`] from the same data, and at the point it decides an Ironwood
/// change value is precisely the unknown it is solving for. That costs nothing: a step with
/// Ironwood change alongside an Ironwood payment has two real Ironwood outputs, so its bundle
/// already meets the default action floor and the padding makes no difference.
#[cfg(feature = "orchard")]
fn sole_ironwood_payment_value(&self) -> Option<Zatoshis> {
let mut payments = self
.payment_pools()
.iter()
.filter(|(_, pool)| **pool == PoolType::IRONWOOD)
.map(|(index, _)| {
self.transaction_request()
.payments()
.get(index)
.and_then(|payment| payment.amount())
});
match (payments.next(), payments.next()) {
(Some(value), None) => value,
_ => None,
}
}
/// Returns whether this step is a *canonical crossing*: a step whose whole shape is
/// indistinguishable from a [ZIP 318] migration transfer, and which is therefore built with a
/// single unpadded Ironwood action so that it joins that anonymity set. See
/// [`Step::ironwood_bundle_padding`].
///
/// A migration transfer spends one Orchard note, pads its Orchard bundle to the default
/// two-action floor (the spend plus its change, or a dummy when the note's value exactly
/// covers the crossing and its fee), outputs one canonical denomination into the Ironwood
/// pool, and is proved against a boundary of the anchor bucket grid. Every one of those is
/// required here:
///
/// - exactly one Orchard input and at most one Orchard change output, so that the Orchard
/// bundle is exactly two actions;
/// - no change in any other pool;
/// - no Ironwood spends, a step funded from Ironwood crossing nothing;
/// - no Ironwood change, leaving a single Ironwood output;
/// - that output's value is a canonical denomination under `params`;
/// - the step's anchor lies on `params`' anchor bucket grid;
/// - the fee equals `canonical_fee`, which the caller obtains from
/// [`fees::canonical_crossing_fee`] for the consensus parameters and target height the
/// transaction will actually be built against.
///
/// [`fees::canonical_crossing_fee`]: crate::fees::canonical_crossing_fee
///
/// Dropping the Ironwood padding without the rest would not buy anonymity but destroy it: an
/// unpadded Ironwood bundle beside an Orchard bundle of the wrong size, or against a
/// chain-tip anchor, is a shape nothing else on the network emits — a fingerprint rather than
/// a disguise.
///
/// [ZIP 318]: https://zips.z.cash/zip-0318
#[cfg(feature = "orchard")]
pub fn is_canonical_crossing<P: PoolMigrationConstants>(
&self,
params: &P,
canonical_fee: Zatoshis,
) -> bool {
self.input_count_in_pool(PoolType::ORCHARD) == 1
&& self.input_count_in_pool(PoolType::IRONWOOD) == 0
&& self.change_count_in_pool(PoolType::IRONWOOD) == 0
// At most ONE Orchard change output. The Orchard bundle must be exactly two actions,
// and from NU6.3 a spend and an output no longer share one, so its count is
// `spends + outputs`: a second change output makes three. A multi-output change
// strategy produces exactly that from a single large note.
&& self.change_count_in_pool(PoolType::ORCHARD) <= 1
// Change anywhere else adds a bundle no migration transfer carries.
&& self.change_count_in_pool(PoolType::SAPLING) == 0
&& self.change_count_in_pool(PoolType::TRANSPARENT) == 0
&& self
.sole_ironwood_payment_value()
.is_some_and(|value| params.is_canonical_denomination(value))
&& self
.anchor_height()
.is_some_and(|anchor| params.anchor_bucket_interval().is_boundary(anchor))
// ZIP 318 forbids a non-standard fee, which would partition the anonymity set as
// surely as a non-standard shape. A `ChangeStrategy` may be built on any fee rule,
// including a fixed non-standard one, so a structurally perfect crossing can still
// carry a distinguishing fee.
//
// This condition is deliberately absent from `ironwood_bundle_padding`: the fee model
// decides that padding WHILE computing the fee, so it cannot test the result against a
// target. Keeping the fee here makes this predicate a gate on whether to keep a
// proposal at all, rather than an input the builder must reproduce.
&& self.balance().fee_required() == canonical_fee
}
/// The transactional bundle padding the transaction builder must use for this step's Ironwood
/// bundle: the padding the [`ChangeStrategy`] recorded when it computed the fee.
///
/// This is READ, not re-derived. The builder must produce exactly the action count the fee was
/// charged against, and a second derivation could disagree with the first — which is precisely
/// what happens for a condition only one of them can evaluate, such as whether the resulting
/// fee is itself canonical.
///
/// [`ChangeStrategy`]: crate::fees::ChangeStrategy
#[cfg(feature = "orchard")]
pub fn ironwood_bundle_padding(&self) -> BundlePadding {
let Some(dummy_outputs) = self.balance().dummy_outputs() else {
return BundlePadding::DEFAULT;
};
let real_outputs = self.output_count_in_pool(PoolType::IRONWOOD)
+ self.change_count_in_pool(PoolType::IRONWOOD);
let target_actions = real_outputs + dummy_outputs.ironwood();
// `pad_to_minimum` is only an 8-bit floor. If the requested transaction is larger than
// that, its real spends and outputs already force the required action count, so no floor
// is needed.
u8::try_from(target_actions).map_or(BundlePadding::UNPADDED, |minimum| BundlePadding {
bundle_required: target_actions > 0
&& self.input_count_in_pool(PoolType::IRONWOOD) == 0
&& real_outputs == 0,
pad_to_minimum: Some(minimum.max(1)),
})
}
#[cfg(feature = "orchard")]
fn orchard_style_action_count(
&self,
pool_type: PoolType,
padding: BundlePadding,
bundle_version: ::orchard::bundle::BundleVersion,
) -> Result<usize, &'static str> {
crate::fees::orchard::transactional_action_count(
padding.bundle_type(),
bundle_version,
self.input_count_in_pool(pool_type),
self.output_count_in_pool(pool_type) + self.change_count_in_pool(pool_type),
)
}
/// Returns the number of actions the transaction builder will produce for this step's
/// Orchard-pool bundle, given the bundle padding and version it will be configured with.
///
/// The count depends upon the bundle version: prior to NU6.3, an action may carry both a
/// spend and an output, so a bundle requires `max(spends, outputs)` actions; from NU6.3
/// onwards the Orchard pool disables cross-address transfers, and each requested spend and
/// output is instead paired with a fabricated zero-valued counterpart, so a bundle requires
/// `spends + outputs` actions. The padding determines the floor applied on top of that count.
///
/// The caller must pass the same padding and version the transaction builder will be
/// configured with, otherwise the count will not match the bundle that is built.
/// [`bundle_version_for_branch`] returns the version applicable to a given consensus branch
/// and pool. The Orchard bundle is always padded to the default floor; only the Ironwood
/// bundle's padding varies, and [`Step::ironwood_bundle_padding`] derives it.
///
/// A step describes a wallet spend, which is never a coinbase transaction, so this takes a
/// [`BundlePadding`] rather than a full bundle type: coinbase construction is a property of the
/// whole transaction and is not representable here.
///
/// # Errors
///
/// Returns an error if this step's Orchard spend and output counts are incompatible with
/// the given padding and version.
///
/// [`bundle_version_for_branch`]: zcash_primitives::transaction::components::orchard::bundle_version_for_branch
#[cfg(feature = "orchard")]
pub fn orchard_action_count(
&self,
padding: BundlePadding,
bundle_version: ::orchard::bundle::BundleVersion,
) -> Result<usize, &'static str> {
self.orchard_style_action_count(PoolType::ORCHARD, padding, bundle_version)
}
/// Returns the number of actions the transaction builder will produce for this step's
/// Ironwood-pool bundle, given the bundle padding and version it will be configured with.
///
/// See [`Step::orchard_action_count`] for how the count is determined; the Ironwood pool
/// permits cross-address transfers, so an Ironwood bundle requires
/// `max(spends, outputs)` actions before padding.
///
/// # Errors
///
/// Returns an error if this step's Ironwood spend and output counts are incompatible with
/// the given padding and version.
#[cfg(feature = "orchard")]
pub fn ironwood_action_count(
&self,
padding: BundlePadding,
bundle_version: ::orchard::bundle::BundleVersion,
) -> Result<usize, &'static str> {
self.orchard_style_action_count(PoolType::IRONWOOD, padding, bundle_version)
}
}
impl<NoteRef> Debug for Step<NoteRef> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Step")
.field("transaction_request", &self.transaction_request)
.field("transparent_inputs", &self.transparent_inputs)
.field(
"shielded_inputs",
&self.shielded_inputs().map(|i| i.notes.len()),
)
.field("prior_step_inputs", &self.prior_step_inputs)
.field("anchor_height", &self.anchor_height)
.field("balance", &self.balance)
.field("is_shielding", &self.is_shielding)
.finish_non_exhaustive()
}
}
#[cfg(all(test, feature = "orchard"))]
mod tests {
use std::collections::BTreeMap;
use zcash_keys::address::{Address, UnifiedAddress};
use incrementalmerkletree::Position;
use nonempty::NonEmpty;
use zcash_address::ZcashAddress;
use zcash_primitives::transaction::{
TxId,
builder::BundlePadding,
components::orchard::{ACTION_SIZE, bundle_version_for_branch},
};
use crate::{
data_api::{
anchor_retention::{AnchorRetentionInterval, PoolMigrationParams},
wallet::{ConfirmationsPolicy, TargetHeight},
},
fees::{ChangeValue, DummyOutputCounts, TransactionBalance},
wallet::Note,
};
use zcash_protocol::{
PoolType, ShieldedPool,
consensus::{BlockHeight, BranchId, Network, NetworkUpgrade, Parameters},
constants::MAX_BLOCK_BYTES,
value::{COIN, Zatoshis},
zip318::PoolMigrationConstants,
};
use zip321::{Payment, TransactionRequest};
use orchard::{
ValuePool,
bundle::BundleVersion,
keys::{FullViewingKey, SpendingKey},
note::{Note as OrchardNote, NoteVersion, RandomSeed, Rho},
value::NoteValue,
};
use proptest::prelude::*;
use super::{Proposal, ProposalError, ShieldedInputs, Step};
// Builds an Orchard note of the given version and value. The recipient, rho, and rseed are
// fixed; only the version and value vary, which is all `Note::pool`/`Note::protocol` depend on.
fn orchard_note(value: u64, version: NoteVersion) -> Option<OrchardNote> {
let sk: SpendingKey = Option::from(SpendingKey::from_bytes([0x2a; 32]))?;
let recipient = FullViewingKey::from(&sk).address_at(0u32, zip32::Scope::External);
let rho = Option::from(Rho::from_bytes(&[0; 32]))?;
let rseed = Option::from(RandomSeed::from_bytes([0x1b; 32], &rho))?;
Option::from(OrchardNote::from_parts(
recipient,
NoteValue::from_raw(value),
rho,
rseed,
version,
))
}
// Wraps a list of notes as the shielded inputs of a step.
fn shielded_inputs_for(notes: Vec<Note>) -> Option<ShieldedInputs<u32>> {
let received = notes
.into_iter()
.enumerate()
.map(|(i, note)| {
crate::wallet::ReceivedNote::from_parts(
i as u32,
TxId::from_bytes([0; 32]),
i as u16,
note,
zip32::Scope::External,
Position::from(i as u64),
Some(BlockHeight::from_u32(100)),
None,
)
})
.collect::<Vec<_>>();
NonEmpty::from_vec(received).map(ShieldedInputs::from_parts)
}
// Wraps a list of notes into a single `Step` whose only inputs are those shielded notes.
fn step_with_notes(notes: Vec<Note>) -> Step<u32> {
step_with_notes_and_change(notes, vec![])
}
// Wraps a list of notes into a single `Step` spending those shielded notes and returning the
// given change outputs. The step is constructed directly rather than via `Step::from_parts`,
// so the change values need not be covered by the input values.
fn step_with_notes_and_change(notes: Vec<Note>, change: Vec<ChangeValue>) -> Step<u32> {
let shielded_inputs = shielded_inputs_for(notes);
Step {
transaction_request: TransactionRequest::empty(),
payment_pools: BTreeMap::new(),
transparent_inputs: vec![],
shielded_inputs,
anchor_height: Some(BlockHeight::from_u32(100)),
prior_step_inputs: vec![],
balance: TransactionBalance::new(change, Zatoshis::ZERO).unwrap(),
is_shielding: false,
}
}
// Constructs a validated step spending the given notes, with no payments.
fn validated_step(
notes: Vec<Note>,
balance: TransactionBalance,
ironwood_active: bool,
) -> Result<Step<u32>, ProposalError> {
Step::from_parts(
&[],
TransactionRequest::empty(),
BTreeMap::new(),
vec![],
shielded_inputs_for(notes),
Some(BlockHeight::from_u32(100)),
vec![],
balance,
false,
ironwood_active,
)
}
/// The canonical crossing fee under the mainnet parameters these tests use.
fn canonical_fee() -> Zatoshis {
crate::fees::canonical_crossing_fee(
&zcash_protocol::consensus::MAIN_NETWORK,
BlockHeight::from_u32(2_000_000),
)
.expect("the canonical shape is a valid input to the ZIP 317 rule")
}
/// The ZIP 318 parameters a wallet retaining the specified grid would report. Tests take their
/// parameters from a wallet-shaped value, as production code does; there is deliberately no
/// implementation of `PoolMigrationConstants` for a network type.
fn zip318() -> PoolMigrationParams {
PoolMigrationParams::new(AnchorRetentionInterval::ZIP_318)
}
fn shielded_change(pool: ShieldedPool, value: u64) -> ChangeValue {
ChangeValue::shielded(pool, Zatoshis::const_from_u64(value), None)
}
// A step paying `value` into the Ironwood pool: one payment, routed to Ironwood, funded by
// Orchard notes, with the given change. This is the shape of an ordinary post-NU6.3 payment
// to an Orchard receiver, which is delivered through the Ironwood bundle.
fn ironwood_payment_step(value: u64, change: Vec<ChangeValue>) -> Step<u32> {
let recipient: ZcashAddress =
"u1qpatys4zruk99pg59gcscrt7y6akvl9vrhcfyhm9yxvxz7h87q6n8cgrzzpe9zru68uq39uhmlpp5uefxu0su5uqyqfe5zp3tycn0ecl"
.parse()
.expect("a valid unified address");
let request = TransactionRequest::new(vec![Payment::without_memo(
recipient,
Zatoshis::const_from_u64(value),
)])
.expect("a valid transaction request");
Step {
transaction_request: request,
payment_pools: BTreeMap::from([(0usize, PoolType::IRONWOOD)]),
transparent_inputs: vec![],
shielded_inputs: shielded_inputs_for(orchard_and_ironwood_notes(
(1, value + 100_000),
(0, 0),
)),
// A boundary of the ZIP 318 grid: a canonical crossing must be anchored to one.
anchor_height: Some(BlockHeight::from_u32(144)),
prior_step_inputs: vec![],
balance: TransactionBalance::new(change, canonical_fee())
.unwrap()
.with_dummy_outputs(DummyOutputCounts::new(0, 0, 0)),
is_shielding: false,
}
}
/// A crossing whose value is a canonical ZIP 318 denomination is built with a single unpadded
/// Ironwood action, matching the shape of a migration transfer.
#[test]
fn canonical_crossing_is_unpadded() {
for value in [COIN, COIN / 2, COIN / 100, 20 * COIN, 10_000 * COIN] {
let step = ironwood_payment_step(value, vec![]);
assert!(
step.is_canonical_crossing(&zip318(), canonical_fee()),
"{value} zatoshi should be a canonical crossing"
);
assert_eq!(step.ironwood_bundle_padding(), BundlePadding::UNPADDED);
assert_eq!(
step.ironwood_action_count(
step.ironwood_bundle_padding(),
BundleVersion::ironwood_v3()
),
Ok(1)
);
}
}
/// One zatoshi off a canonical denomination, or outside the ZIP's bounds, is not a canonical
/// crossing: it stays padded, since it would join no migration anonymity set.
#[test]
fn near_canonical_crossing_stays_padded() {
for value in [COIN + 1, COIN - 1, 3 * COIN, 100_000, 20_000 * COIN] {
let step = ironwood_payment_step(value, vec![]);
assert!(
!step.is_canonical_crossing(&zip318(), canonical_fee()),
"{value} zatoshi should not be a canonical crossing"
);
assert_eq!(
step.ironwood_action_count(BundlePadding::DEFAULT, BundleVersion::ironwood_v3()),
Ok(2)
);
}
}
/// Ironwood change alongside a canonical payment is NOT a canonical crossing. The fee model
/// cannot see a change value at the point it decides padding — that value is what it is
/// solving for — so including change here would let the two disagree and break the builder's
/// exact-balance check. It costs nothing: two real outputs already meet the default floor.
#[test]
fn ironwood_change_is_not_a_canonical_crossing() {
let step = ironwood_payment_step(COIN, vec![shielded_change(ShieldedPool::Ironwood, 5000)]);
assert!(!step.is_canonical_crossing(&zip318(), canonical_fee()));
}
/// A payment funded from Ironwood notes crosses nothing, so it is never a canonical crossing
/// however canonical its value. Its bundle has two real actions regardless.
#[test]
fn ironwood_funded_payment_is_not_a_canonical_crossing() {
let mut step = ironwood_payment_step(COIN, vec![]);
step.shielded_inputs =
shielded_inputs_for(orchard_and_ironwood_notes((0, 0), (1, 2 * COIN)));
assert!(!step.is_canonical_crossing(&zip318(), canonical_fee()));
}
/// An anchor off the bucket grid is not a canonical crossing, however canonical the value and
/// however migration-shaped the bundles. Unpadding here would produce an "unpadded Ironwood
/// against a fresh anchor" shape that no migration transfer emits, which is a fingerprint
/// rather than a disguise.
#[test]
fn unbucketed_anchor_is_not_a_canonical_crossing() {
let mut step = ironwood_payment_step(COIN, vec![]);
for height in [143u32, 145, 1, 2_000_000] {
step.anchor_height = Some(BlockHeight::from_u32(height));
assert!(
!step.is_canonical_crossing(&zip318(), canonical_fee()),
"anchor {height} is not a grid boundary"
);
}
// The neighbouring boundaries are.
for height in [144u32, 288, 1_999_872] {
step.anchor_height = Some(BlockHeight::from_u32(height));
assert!(step.is_canonical_crossing(&zip318(), canonical_fee()));
}
}
/// A migration transfer spends exactly one Orchard note. A payment drawing on more leaves an
/// Orchard bundle of the wrong size, so unpadding its Ironwood bundle would not resemble a
/// migration transfer.
#[test]
fn multiple_orchard_inputs_are_not_a_canonical_crossing() {
let mut step = ironwood_payment_step(COIN, vec![]);
assert!(step.is_canonical_crossing(&zip318(), canonical_fee()));
step.shielded_inputs = shielded_inputs_for(orchard_and_ironwood_notes((3, COIN), (0, 0)));
assert!(!step.is_canonical_crossing(&zip318(), canonical_fee()));
}
/// Overridden ZIP 318 parameters narrow which crossings are canonical, and the padding follows.
#[test]
fn canonical_crossing_respects_overridden_parameters() {
#[derive(Clone)]
struct SmallCap;
impl PoolMigrationConstants for SmallCap {
fn denomination_cap(&self) -> Zatoshis {
Zatoshis::const_from_u64(COIN)
}
}
let step = ironwood_payment_step(2 * COIN, vec![]);
assert!(step.is_canonical_crossing(&zip318(), canonical_fee()));
assert!(!step.is_canonical_crossing(&SmallCap, canonical_fee()));
}
/// A step that produces any shielded bundle must bind a concrete anchor. Passing `None` (the
/// decoded state of the wire-format zero sentinel) for such a step is rejected, whether the
/// shielded bundle comes from spent notes or from shielded outputs. Only a purely transparent
/// step may carry `None`.
#[test]
fn shielded_step_requires_anchor() {
// A step that spends shielded notes with no anchor is rejected.
assert_matches!(
Step::from_parts(
&[],
TransactionRequest::empty(),
BTreeMap::new(),
vec![],
shielded_inputs_for(orchard_and_ironwood_notes((1, 10_000), (0, 0))),
None,
vec![],
TransactionBalance::new(vec![], Zatoshis::const_from_u64(10_000)).unwrap(),
false,
false,
),
Err(ProposalError::MissingShieldedAnchor)
);
// A step with a shielded output but no shielded inputs must also bind an anchor: the dummy
// spends padding the output bundle commit to it.
assert_matches!(
Step::from_parts(
&[],
TransactionRequest::empty(),
BTreeMap::new(),
vec![],
None::<ShieldedInputs<u32>>,
None,
vec![],
TransactionBalance::new(
vec![shielded_change(ShieldedPool::Orchard, 10_000)],
Zatoshis::ZERO,
)
.unwrap(),
false,
false,
),
Err(ProposalError::MissingShieldedAnchor)
);
// A purely transparent step may carry no anchor.
assert_matches!(
Step::from_parts(
&[],
TransactionRequest::empty(),
BTreeMap::new(),
vec![],
None::<ShieldedInputs<u32>>,
None,
vec![],
TransactionBalance::new(vec![], Zatoshis::ZERO).unwrap(),
false,
false,
),
Ok(step) if step.anchor_height().is_none()
);
}
/// Proposal construction conserves value: the total output value of a step (payments +
/// change + fee) may never exceed its total input value. A step whose outputs exceed its
/// inputs is rejected with [`ProposalError::BalanceError`] rather than being constructed.
/// This is the value-conservation floor that pool-selection policy builds on: no selection
/// of inputs can ever be assembled into a proposal that spends more than it takes in.
#[test]
fn proposal_construction_conserves_value() {
// Inputs: one 10_000 Orchard note. Outputs: 8_000 change + 4_000 fee = 12_000, which
// exceeds the 10_000 of input value. (ironwood_active = false so the balance check,
// not the turnstile, is what rejects this.)
assert_matches!(
validated_step(
orchard_and_ironwood_notes((1, 10_000), (0, 0)),
TransactionBalance::new(
vec![shielded_change(ShieldedPool::Orchard, 8_000)],
Zatoshis::const_from_u64(4_000),
)
.unwrap(),
false,
),
Err(ProposalError::BalanceError {
input_total,
output_total,
}) if input_total == Zatoshis::const_from_u64(10_000)
&& output_total == Zatoshis::const_from_u64(12_000)
);
// The matching balanced step (6_000 change + 4_000 fee == 10_000 input) is accepted,
// confirming the rejection above is due to the value imbalance and not some unrelated
// constraint.
assert_matches!(
validated_step(
orchard_and_ironwood_notes((1, 10_000), (0, 0)),
TransactionBalance::new(
vec![shielded_change(ShieldedPool::Orchard, 6_000)],
Zatoshis::const_from_u64(4_000),
)
.unwrap(),
false,
),
Ok(_)
);
}
#[test]
fn orchard_turnstile_permits_only_strict_pool_balance_decrease() {
// Post-activation, change may return to Orchard when strictly less value returns
// than the step's Orchard inputs remove: 6_000 change < 10_000 input.
assert_matches!(
validated_step(
orchard_and_ironwood_notes((1, 10_000), (0, 0)),
TransactionBalance::new(
vec![shielded_change(ShieldedPool::Orchard, 6_000)],
Zatoshis::const_from_u64(4_000),
)
.unwrap(),
true,
),
Ok(_)
);
// Post-activation, Orchard change equal to the Orchard input total would leave the
// pool balance unchanged, which the turnstile forbids.
assert_matches!(
validated_step(
orchard_and_ironwood_notes((1, 10_000), (1, 20_000)),
TransactionBalance::new(
vec![
shielded_change(ShieldedPool::Orchard, 10_000),
shielded_change(ShieldedPool::Ironwood, 16_000),
],
Zatoshis::const_from_u64(4_000),
)
.unwrap(),
true,
),
Err(ProposalError::OrchardPoolValueCreation {
input_total,
output_total,
}) if input_total == Zatoshis::const_from_u64(10_000)
&& output_total == Zatoshis::const_from_u64(10_000)
);
// Post-activation, a step that spends no Orchard notes may not create Orchard
// change at all.
assert_matches!(
validated_step(
orchard_and_ironwood_notes((0, 0), (1, 20_000)),
TransactionBalance::new(
vec![shielded_change(ShieldedPool::Orchard, 16_000)],
Zatoshis::const_from_u64(4_000),
)
.unwrap(),
true,
),
Err(ProposalError::OrchardPoolValueCreation {
input_total,
output_total,
}) if input_total == Zatoshis::ZERO
&& output_total == Zatoshis::const_from_u64(16_000)
);
// Before activation, value may freely enter the Orchard pool: the same step is
// valid.
assert_matches!(
validated_step(
orchard_and_ironwood_notes((0, 0), (1, 20_000)),
TransactionBalance::new(
vec![shielded_change(ShieldedPool::Orchard, 16_000)],
Zatoshis::const_from_u64(4_000),
)
.unwrap(),
false,
),
Ok(_)
);
}
// Constructs a step that spends a 10_000-zatoshi Orchard note to pay 6_000 zatoshis to
// an Orchard receiver, with the payment assigned to the given pool.
fn orchard_payment_step(
pool: PoolType,
ironwood_active: bool,
) -> Result<Step<u32>, ProposalError> {
let sk: SpendingKey = Option::from(SpendingKey::from_bytes([0x2a; 32])).unwrap();
let recipient = FullViewingKey::from(&sk).address_at(0u32, zip32::Scope::External);
let ua = UnifiedAddress::from_receivers(Some(recipient), None, None).unwrap();
let to = Address::Unified(ua).to_zcash_address(&Network::TestNetwork);
let request = TransactionRequest::new(vec![
zip321::Payment::new(
to,
Some(Zatoshis::const_from_u64(6_000)),
None,
None,
None,
vec![],
)
.unwrap(),
])
.unwrap();
Step::from_parts(
&[],
request,
BTreeMap::from([(0usize, pool)]),
vec![],
shielded_inputs_for(orchard_and_ironwood_notes((1, 10_000), (0, 0))),
Some(BlockHeight::from_u32(100)),
vec![],
TransactionBalance::new(vec![], Zatoshis::const_from_u64(4_000)).unwrap(),
false,
ironwood_active,
)
}
#[test]
fn orchard_turnstile_permits_routed_and_pre_activation_payments() {
// A payment routed through the Ironwood bundle (the post-activation representation
// of an Orchard-receiver payment) is valid.
assert_matches!(orchard_payment_step(PoolType::IRONWOOD, true), Ok(_));
// Before activation, an Orchard-pool payment is valid.
assert_matches!(orchard_payment_step(PoolType::ORCHARD, false), Ok(_));
}
// Post-activation, payment classification never assigns a payment to the Orchard pool,
// so a step constructed with one can only arise through direct misuse of the public
// constructor, which rejects it.
#[test]
fn orchard_pool_payment_with_ironwood_active_is_an_error() {
assert_matches!(
orchard_payment_step(PoolType::ORCHARD, true),
Err(ProposalError::OrchardPoolPayment(0))
);
}
// Builds `orchard.0` version-2 (Orchard) notes of value `orchard.1`, followed by `ironwood.0`
// version-3 (Ironwood) notes of value `ironwood.1`.
//
// Every note of a given pool is identical, so each is derived once and cloned: deriving a full
// viewing key per note makes the large-transaction cases below cost seconds rather than
// milliseconds. Only the count and the pool of each note matter to an action count.
fn orchard_and_ironwood_notes(
(n, orchard_value): (usize, u64),
(m, ironwood_value): (usize, u64),
) -> Vec<Note> {
let mut notes = Vec::with_capacity(n + m);
if n > 0 {
let note = Note::Orchard {
note: orchard_note(orchard_value, NoteVersion::V2).unwrap(),
pool: ValuePool::Orchard,
};
notes.extend(std::iter::repeat_n(note, n));
}
if m > 0 {
let note = Note::Orchard {
note: orchard_note(ironwood_value, NoteVersion::V3).unwrap(),
pool: ValuePool::Ironwood,
};
notes.extend(std::iter::repeat_n(note, m));
}
notes
}
// Note and change values, spanning a zero-valued note through a large one. An action count is a
// function of how many notes and outputs a step has in each pool, never of what they are worth,
// so every value here must give the same answer. The upper bound keeps the total value of even
// the largest generated step well inside `MAX_MONEY`, so that `TransactionBalance` construction
// cannot fail for a reason these tests are not about.
fn arb_note_value() -> impl Strategy<Value = u64> {
prop_oneof![
1 => Just(0u64),
8 => 1u64..1_000_000_000,
]
}
// An upper bound on the actions a single bundle can contain on-chain: a transaction may not
// exceed a block, and each action costs at least its action description. The true ceiling is
// lower, since `ACTION_SIZE` excludes each action's spend authorization signature and the
// bundle's proof, but an over-estimate is what these tests want: it exercises counts at least
// as large as anything buildable.
const MAX_ACTIONS_PER_BUNDLE: usize = MAX_BLOCK_BYTES / ACTION_SIZE;
// Spend and output counts spanning what a wallet can actually produce: ordinary payments, large
// note-consolidation transactions, and bundles at the block ceiling. Each side is capped at
// half the ceiling, because from NU6.3 an Orchard spend and an output no longer share an
// action, so `spends + outputs` must itself fit. Small counts are weighted heavily: that is
// where the padding floor binds, and where real transactions live.
fn arb_note_count() -> impl Strategy<Value = usize> {
prop_oneof![
6 => 0usize..8,
2 => 8usize..100,
1 => 100usize..=MAX_ACTIONS_PER_BUNDLE / 2,
]
}
// The network upgrades at which the Orchard pool exists but still permits cross-address
// transfers, so that a requested spend and a requested output may share an action.
fn arb_pre_nu6_3_upgrade() -> impl Strategy<Value = NetworkUpgrade> {
prop::sample::select(vec![
NetworkUpgrade::Nu5,
NetworkUpgrade::Nu6,
NetworkUpgrade::Nu6_1,
NetworkUpgrade::Nu6_2,
])
}
// The network upgrades from which the Orchard pool disables cross-address transfers. `Nu7` is
// excluded: it has no activation height on any network yet, so no bundle can be built for it.
fn arb_nu6_3_or_later_upgrade() -> impl Strategy<Value = NetworkUpgrade> {
prop::sample::select(vec![NetworkUpgrade::Nu6_3])
}
// Resolves the bundle version applicable to a pool at an upgrade's testnet activation height,
// the way the fee and builder paths do: height -> consensus branch -> `BundleVersion`.
fn bundle_version_at(upgrade: NetworkUpgrade, pool: ValuePool) -> BundleVersion {
let height = Network::TestNetwork.activation_height(upgrade).unwrap();
bundle_version_for_branch(BranchId::for_height(&Network::TestNetwork, height), pool)
.unwrap()
}
// A step that requires no actions in a pool produces no bundle in that pool, so it is charged
// nothing, no matter how much padding the bundle type would otherwise apply. The exception is
// a bundle type that requires a bundle: the builder then produces one consisting entirely of
// dummy actions, padded to the type's minimum.
#[test]
fn uninvolved_pool_is_charged_nothing_unless_a_bundle_is_required() {
let step = step_with_notes(vec![]);
for bundle_type in [BundlePadding::DEFAULT, BundlePadding::UNPADDED] {
assert_eq!(
step.orchard_action_count(bundle_type, BundleVersion::orchard_v3()),
Ok(0)
);
assert_eq!(
step.ironwood_action_count(bundle_type, BundleVersion::ironwood_v3()),
Ok(0)
);
}
// `bundle_required` guarantees a bundle exists, padded to the type's minimum: two
// all-dummy actions by default, or one when the type opts out of the default padding.
let required = BundlePadding {
bundle_required: true,
pad_to_minimum: None,
};
assert_eq!(
step.orchard_action_count(required, BundleVersion::orchard_v3()),
Ok(2)
);
let required_unpadded = BundlePadding {
bundle_required: true,
pad_to_minimum: Some(1),
};
assert_eq!(
step.orchard_action_count(required_unpadded, BundleVersion::orchard_v3()),
Ok(1)
);
// A zero floor cannot suppress a required bundle: a bundle must contain at least one
// action to exist at all, so the required-but-unpadded-to-zero case still yields one.
let required_zero_floor = BundlePadding {
bundle_required: true,
pad_to_minimum: Some(0),
};
assert_eq!(
step.orchard_action_count(required_zero_floor, BundleVersion::orchard_v3()),
Ok(1)
);
// Without `bundle_required`, a zero floor leaves an uninvolved pool with no bundle.
let zero_floor = BundlePadding {
bundle_required: false,
pad_to_minimum: Some(0),
};
assert_eq!(
step.orchard_action_count(zero_floor, BundleVersion::orchard_v3()),
Ok(0)
);
}
// `spends_cannot_be_charged_to_a_coinbase_bundle` used to live here, asserting that a step
// which spends notes is rejected when charged to a coinbase bundle of that pool. The action
// counters now take a `BundlePadding`, which has no coinbase variant, so that case is
// unrepresentable rather than merely rejected: a step describes a wallet spend, and a wallet
// spend is never a coinbase transaction.
// What NU6.3 costs a large transaction depends on its shape, and a wallet estimating fees at
// scale has to get the difference right.
#[test]
fn nu6_3_action_growth_at_scale_depends_on_step_shape() {
let balanced = |n| {
step_with_notes_and_change(
orchard_and_ironwood_notes((n, 10_000), (0, 0)),
std::iter::repeat_n(shielded_change(ShieldedPool::Orchard, 10_000), n).collect(),
)
};
// A consolidation -- sweeping many notes into a single change output -- pays for that
// output's fabricated spend and nothing else: one extra action, however large it is.
let consolidation = step_with_notes_and_change(
orchard_and_ironwood_notes((MAX_ACTIONS_PER_BUNDLE, 10_000), (0, 0)),
vec![shielded_change(ShieldedPool::Orchard, 10_000)],
);
// 2439 actions: the change output rides along in a spend's action, exactly filling a block.
assert_eq!(
consolidation
.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v2()),
Ok(MAX_ACTIONS_PER_BUNDLE)
);
// 2440 from NU6.3: one action over the ceiling, so the same sweep no longer fits.
assert_eq!(
consolidation
.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v3()),
Ok(MAX_ACTIONS_PER_BUNDLE + 1)
);
// A balanced step -- as many outputs as spends -- doubles instead, so the largest one that
// fits in a block halves at NU6.3: 2439 spends paired with 2439 outputs before, 1219 of
// each after. This is why `arb_note_count` caps each side at half the ceiling.
let half = MAX_ACTIONS_PER_BUNDLE / 2;
assert_eq!(
balanced(MAX_ACTIONS_PER_BUNDLE)
.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v2()),
Ok(MAX_ACTIONS_PER_BUNDLE)
);
// 2438: the largest balanced step that still fits.
assert_eq!(
balanced(half)
.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v3()),
Ok(2 * half)
);
// 2440: one note more on each side and it does not.
assert_eq!(
balanced(half + 1)
.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v3()),
Ok(2 * half + 2)
);
}
// A `Step` does not necessarily come from this wallet's own input selection: a proposal crosses
// a trust boundary as a serialized message (see `proposal.proto` and
// `Proposal::try_into_standard_proposal`), so a step's output and change counts are
// attacker-influenced. A step claiming far more outputs than could ever fit on-chain must still
// be counted exactly, so that the fee rule is handed an unaffordable action count and rejects
// it, rather than a small wrapped-around one it would accept.
//
// The counts themselves cannot overflow `usize`: each is the length of an in-memory collection,
// so reaching `usize::MAX` would require more notes than could be addressed.
#[test]
fn counts_beyond_the_block_limit_are_counted_exactly() {
let spends = 4 * MAX_ACTIONS_PER_BUNDLE;
let change = 4 * MAX_ACTIONS_PER_BUNDLE;
let step = step_with_notes_and_change(
orchard_and_ironwood_notes((spends, 10_000), (0, 0)),
std::iter::repeat_n(shielded_change(ShieldedPool::Orchard, 10_000), change).collect(),
);
// Roughly eight times what a block can hold, reported exactly.
assert!(spends + change > 8 * MAX_ACTIONS_PER_BUNDLE - 1);
assert_eq!(
step.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v3()),
Ok(spends + change)
);
// Pre-NU6.3 the same step pairs, so it is charged half as much -- still far past the
// ceiling, and still counted exactly.
assert_eq!(
step.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v2()),
Ok(spends.max(change))
);
// Padding a step this size cannot reduce it, and the ZIP 317 floor is irrelevant here.
assert_eq!(
step.orchard_action_count(BundlePadding::DEFAULT, BundleVersion::orchard_v3()),
Ok(spends + change)
);
}
// A payment output counts towards the action count of the pool it is directed to, exactly as
// a change output does. `orchard_payment_step` spends one Orchard note to make one payment.
#[test]
fn action_count_includes_payment_outputs() {
// Pre-activation, the payment is an Orchard-pool output: one spend and one output share
// an action, because the pre-NU6.3 Orchard bundle version permits cross-address transfers.
let step = orchard_payment_step(PoolType::ORCHARD, false).unwrap();
assert_eq!(
step.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v2()),
Ok(1)
);
assert_eq!(
step.ironwood_action_count(BundlePadding::UNPADDED, BundleVersion::ironwood_v3()),
Ok(0)
);
// Post-activation, the payment is routed to the Ironwood pool: the Orchard note spend is
// charged to the Orchard bundle and the payment output to the Ironwood bundle, so neither
// pool can pair them into one action.
let step = orchard_payment_step(PoolType::IRONWOOD, true).unwrap();
assert_eq!(
step.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v3()),
Ok(1)
);
assert_eq!(
step.ironwood_action_count(BundlePadding::UNPADDED, BundleVersion::ironwood_v3()),
Ok(1)
);
}
proptest! {
// The number of actions a step's Orchard-pool bundle requires depends upon the bundle
// version: the pre-NU6.3 versions permit cross-address transfers, so a spend and an
// output may share an action (`max(spends, outputs)`), while from NU6.3 onwards the
// Orchard pool disables them, so each spend and output is paired with a fabricated
// counterpart and occupies its own action (`spends + outputs`). The Ironwood pool
// permits cross-address transfers at every version, so it always pairs.
#[test]
fn action_count_pairs_spends_and_outputs_only_when_cross_address_is_permitted(
orchard_spends in arb_note_count(),
ironwood_spends in arb_note_count(),
orchard_change in arb_note_count(),
ironwood_change in arb_note_count(),
orchard_value in arb_note_value(),
ironwood_value in arb_note_value(),
change_value in arb_note_value(),
) {
let change = std::iter::repeat_n(ShieldedPool::Orchard, orchard_change)
.chain(std::iter::repeat_n(ShieldedPool::Ironwood, ironwood_change))
.map(|pool| shielded_change(pool, change_value))
.collect();
let step = step_with_notes_and_change(
orchard_and_ironwood_notes((orchard_spends, orchard_value), (ironwood_spends, ironwood_value)),
change,
);
// `UNPADDED` pads only to the one-action consensus minimum, so for a non-empty
// bundle its action count is exactly the number of requested actions.
for version in [BundleVersion::orchard_insecure_v1(), BundleVersion::orchard_v2()] {
prop_assert_eq!(
step.orchard_action_count(BundlePadding::UNPADDED, version),
Ok(orchard_spends.max(orchard_change))
);
}
prop_assert_eq!(
step.orchard_action_count(BundlePadding::UNPADDED, BundleVersion::orchard_v3()),
Ok(orchard_spends + orchard_change)
);
prop_assert_eq!(
step.ironwood_action_count(BundlePadding::UNPADDED, BundleVersion::ironwood_v3()),
Ok(ironwood_spends.max(ironwood_change))
);
// The bundle type governs padding on top of that count: `DEFAULT` pads a non-empty
// bundle up to the ZIP 317 two-action floor, and produces no bundle at all when the
// step requires no actions in that pool.
let pad = |requested: usize| if requested == 0 { 0 } else { requested.max(2) };
prop_assert_eq!(
step.orchard_action_count(BundlePadding::DEFAULT, BundleVersion::orchard_v3()),
Ok(pad(orchard_spends + orchard_change))
);
prop_assert_eq!(
step.ironwood_action_count(BundlePadding::DEFAULT, BundleVersion::ironwood_v3()),
Ok(pad(ironwood_spends.max(ironwood_change)))
);
}
// The action count a caller obtains for a real target height, resolving the bundle
// version the way the fee and builder paths do: height -> consensus branch ->
// `BundleVersion`. This is the scenario the legacy hardcoded `max(spends, outputs)`
// formula got wrong: at a post-NU6.3 height it understated the Orchard action count
// whenever a step had both spends and outputs, and so understated the ZIP 317 fee.
#[test]
fn orchard_action_count_grows_at_nu6_3_activation_height(
spends in arb_note_count(),
change in arb_note_count(),
note_value in arb_note_value(),
change_value in arb_note_value(),
pre_nu6_3 in arb_pre_nu6_3_upgrade(),
nu6_3_or_later in arb_nu6_3_or_later_upgrade(),
) {
let orchard_step = step_with_notes_and_change(
orchard_and_ironwood_notes((spends, note_value), (0, 0)),
std::iter::repeat_n(shielded_change(ShieldedPool::Orchard, change_value), change)
.collect(),
);
// Pre-NU6.3, each change output shares an action with a spend: max(spends, change).
prop_assert_eq!(
orchard_step.orchard_action_count(
BundlePadding::UNPADDED,
bundle_version_at(pre_nu6_3, ValuePool::Orchard),
),
Ok(spends.max(change))
);
// From NU6.3, the Orchard pool disables cross-address transfers: a change output's
// corresponding dummy input must be signed with the spending key for the internal
// IVK the change is sent to, so it cannot share an action with a spend of a note
// belonging to a different address. Hence spends + change actions.
prop_assert_eq!(
orchard_step.orchard_action_count(
BundlePadding::UNPADDED,
bundle_version_at(nu6_3_or_later, ValuePool::Orchard),
),
Ok(spends + change)
);
// The Ironwood pool retains cross-address transfers, so an equivalent Ironwood step
// still pairs at a post-NU6.3 height.
let ironwood_step = step_with_notes_and_change(
orchard_and_ironwood_notes((0, 0), (spends, note_value)),
std::iter::repeat_n(shielded_change(ShieldedPool::Ironwood, change_value), change)
.collect(),
);
prop_assert_eq!(
ironwood_step.ironwood_action_count(
BundlePadding::UNPADDED,
bundle_version_at(nu6_3_or_later, ValuePool::Ironwood),
),
Ok(spends.max(change))
);
}
// A non-empty bundle is charged the greater of the actions it requests and the bundle
// type's padding floor: padding never reduces the count, and the floor is never
// undershot. A bundle that requests nothing is not produced at all, so it is charged
// nothing however high the floor. `DEFAULT` (floor 2) and `UNPADDED` (floor 1) are the
// floors the wallet itself uses; the whole `u8` range is covered here, including the
// degenerate zero floor, since the bundle type is the caller's to choose.
#[test]
fn action_count_is_never_below_the_bundle_types_padding_floor(
spends in arb_note_count(),
change in arb_note_count(),
note_value in arb_note_value(),
change_value in arb_note_value(),
pad_to_minimum in 0u8..=u8::MAX,
) {
let step = step_with_notes_and_change(
orchard_and_ironwood_notes((spends, note_value), (0, 0)),
std::iter::repeat_n(shielded_change(ShieldedPool::Orchard, change_value), change)
.collect(),
);
let bundle_type = BundlePadding {
bundle_required: false,
pad_to_minimum: Some(pad_to_minimum),
};
// Post-NU6.3, so the requested count is `spends + change`.
let requested = spends + change;
let expected = if requested == 0 {
0
} else {
requested.max(usize::from(pad_to_minimum))
};
prop_assert_eq!(
step.orchard_action_count(bundle_type, BundleVersion::orchard_v3()),
Ok(expected)
);
}
// `Note::pool` reports the `ValuePool` recorded alongside an Orchard note.
#[test]
fn note_pool_reports_stored_value_pool(
value in 1u64..1_000_000_000u64,
is_ironwood in any::<bool>(),
) {
let (version, pool, expected) = if is_ironwood {
(NoteVersion::V3, ValuePool::Ironwood, ShieldedPool::Ironwood)
} else {
(NoteVersion::V2, ValuePool::Orchard, ShieldedPool::Orchard)
};
let Some(note) = orchard_note(value, version) else {
// A handful of (value, rho, rseed) combinations do not form a valid note; skip them.
return Err(TestCaseError::reject("invalid orchard note"));
};
let note = Note::Orchard { note, pool };
prop_assert_eq!(note.pool(), expected);
}
// `Step::input_count_in_pool` returns the number of selected notes in each pool, splitting
// Orchard (version 2) from Ironwood (version 3); Sapling is zero here. `input_in_pool`
// agrees with `input_count_in_pool > 0`, and `Proposal::input_count_in_pool` sums the
// per-step counts.
#[test]
fn step_and_proposal_input_counts_match_constructed_notes(
n_orchard in 0usize..5,
n_ironwood in 0usize..5,
m_orchard in 0usize..5,
m_ironwood in 0usize..5,
) {
let step1 = step_with_notes(orchard_and_ironwood_notes((n_orchard, 10_000), (n_ironwood, 20_000)));
prop_assert_eq!(step1.input_count_in_pool(PoolType::SAPLING), 0);
prop_assert_eq!(step1.input_count_in_pool(PoolType::ORCHARD), n_orchard);
prop_assert_eq!(step1.input_count_in_pool(PoolType::IRONWOOD), n_ironwood);
for pool in [ShieldedPool::Sapling, ShieldedPool::Orchard, ShieldedPool::Ironwood] {
let pool_type = PoolType::Shielded(pool);
prop_assert_eq!(
step1.input_in_pool(pool_type),
step1.input_count_in_pool(pool_type) > 0
);
}
let step2 = step_with_notes(orchard_and_ironwood_notes((m_orchard, 10_000), (m_ironwood, 20_000)));
let proposal = Proposal::<(), u32> {
fee_rule: (),
min_target_height: TargetHeight::from(100u32),
confirmations_policy: ConfirmationsPolicy::default(),
proposed_version: None,
steps: NonEmpty::from_vec(vec![step1, step2]).unwrap(),
};
prop_assert_eq!(proposal.input_count_in_pool(PoolType::SAPLING), 0);
prop_assert_eq!(
proposal.input_count_in_pool(PoolType::ORCHARD),
n_orchard + m_orchard
);
prop_assert_eq!(
proposal.input_count_in_pool(PoolType::IRONWOOD),
n_ironwood + m_ironwood
);
}
}
}