1use alloc::vec::Vec;
6use core::cmp::max;
7
8use ::transparent::bundle::OutPoint;
9use zcash_protocol::{
10 consensus::{self, BlockHeight, NetworkType, NetworkUpgrade},
11 value::{BalanceError, Zatoshis},
12};
13
14use crate::transaction::fees::transparent;
15
16#[deprecated(
21 since = "0.32.0",
22 note = "Use `zip317::marginal_fee(params, target_height)` for the marginal fee in effect at the height a transaction is expected to be mined."
23)]
24pub const MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(5_000);
25
26const REVISION_2_MARGINAL_FEE: Zatoshis = Zatoshis::const_from_u64(1_000);
31
32const MAINNET_FEE_REDUCTION_HEIGHT: BlockHeight = BlockHeight::from_u32(3_590_000);
36
37const TESTNET_FEE_REDUCTION_HEIGHT: BlockHeight = BlockHeight::from_u32(4_465_026);
39
40fn revision_2_height<P: consensus::Parameters>(params: &P) -> Option<BlockHeight> {
43 match params.network_type() {
44 NetworkType::Main => Some(MAINNET_FEE_REDUCTION_HEIGHT),
45 NetworkType::Test => Some(TESTNET_FEE_REDUCTION_HEIGHT),
46 NetworkType::Regtest => params.activation_height(NetworkUpgrade::Nu7),
47 }
48}
49
50pub fn marginal_fee<P: consensus::Parameters>(params: &P, target_height: BlockHeight) -> Zatoshis {
61 #[allow(deprecated)]
63 let pre_revision_2 = MARGINAL_FEE;
64 if revision_2_height(params).is_some_and(|h| h <= target_height) {
65 REVISION_2_MARGINAL_FEE
66 } else {
67 pre_revision_2
68 }
69}
70
71pub fn minimum_fee<P: consensus::Parameters>(params: &P, target_height: BlockHeight) -> Zatoshis {
76 (marginal_fee(params, target_height) * GRACE_ACTIONS)
79 .expect("MARGINAL_FEE * GRACE_ACTIONS is below MAX_MONEY")
80}
81
82pub const GRACE_ACTIONS: usize = 2;
86
87pub const P2PKH_STANDARD_INPUT_SIZE: usize = 150;
91
92pub const P2PKH_STANDARD_OUTPUT_SIZE: usize = 34;
96
97pub const MAX_TRANSPARENT_INPUT_SIZE: usize = 36 + 9 + 10_000 + 4;
102
103pub const TRANSPARENT_BUNDLE_OVERHEAD: usize = 18;
106
107pub const TX_HEADER_SIZE: usize = 32;
111
112#[deprecated(
118 since = "0.32.0",
119 note = "Use `zip317::minimum_fee(params, target_height)` for the minimum conventional fee in effect at the height a transaction is expected to be mined."
120)]
121pub const MINIMUM_FEE: Zatoshis = Zatoshis::const_from_u64(10_000);
122
123#[derive(Clone, Debug)]
136pub struct FeeRule {
137 marginal_fee: MarginalFee,
138 grace_actions: usize,
139 p2pkh_standard_input_size: usize,
140 p2pkh_standard_output_size: usize,
141}
142
143#[derive(Clone, Debug)]
145enum MarginalFee {
146 Standard,
148 #[cfg(feature = "non-standard-fees")]
150 Fixed(Zatoshis),
151}
152
153impl FeeRule {
154 pub fn standard() -> Self {
159 Self {
160 marginal_fee: MarginalFee::Standard,
161 grace_actions: GRACE_ACTIONS,
162 p2pkh_standard_input_size: P2PKH_STANDARD_INPUT_SIZE,
163 p2pkh_standard_output_size: P2PKH_STANDARD_OUTPUT_SIZE,
164 }
165 }
166
167 #[cfg(feature = "non-standard-fees")]
180 pub fn non_standard(
181 marginal_fee: Zatoshis,
182 grace_actions: usize,
183 p2pkh_standard_input_size: usize,
184 p2pkh_standard_output_size: usize,
185 ) -> Option<Self> {
186 if p2pkh_standard_input_size == 0 || p2pkh_standard_output_size == 0 {
187 None
188 } else {
189 Some(Self {
190 marginal_fee: MarginalFee::Fixed(marginal_fee),
191 grace_actions,
192 p2pkh_standard_input_size,
193 p2pkh_standard_output_size,
194 })
195 }
196 }
197
198 pub fn marginal_fee<P: consensus::Parameters>(
201 &self,
202 params: &P,
203 target_height: BlockHeight,
204 ) -> Zatoshis {
205 match self.marginal_fee {
206 MarginalFee::Standard => marginal_fee(params, target_height),
207 #[cfg(feature = "non-standard-fees")]
208 MarginalFee::Fixed(fee) => fee,
209 }
210 }
211 pub fn grace_actions(&self) -> usize {
213 self.grace_actions
214 }
215 pub fn p2pkh_standard_input_size(&self) -> usize {
217 self.p2pkh_standard_input_size
218 }
219 pub fn p2pkh_standard_output_size(&self) -> usize {
221 self.p2pkh_standard_output_size
222 }
223}
224
225#[derive(Clone, Debug, PartialEq, Eq)]
227pub enum FeeError {
228 Balance(BalanceError),
230 UnknownP2shInputs(Vec<OutPoint>),
233}
234
235impl From<BalanceError> for FeeError {
236 fn from(err: BalanceError) -> Self {
237 FeeError::Balance(err)
238 }
239}
240
241impl core::fmt::Display for FeeError {
242 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
243 match &self {
244 FeeError::Balance(e) => write!(
245 f,
246 "A balance calculation violated amount validity bounds: {e}."
247 ),
248 FeeError::UnknownP2shInputs(_) => {
249 write!(f, "Only P2PKH or known-P2SH inputs are supported.")
250 }
251 }
252 }
253}
254
255impl super::FeeRule for FeeRule {
256 type Error = FeeError;
257
258 fn fee_required<P: consensus::Parameters>(
259 &self,
260 params: &P,
261 target_height: BlockHeight,
262 transparent_input_sizes: impl IntoIterator<Item = transparent::InputSize>,
263 transparent_output_sizes: impl IntoIterator<Item = usize>,
264 sapling_input_count: usize,
265 sapling_output_count: usize,
266 orchard_action_count: usize,
267 ironwood_action_count: usize,
268 ) -> Result<Zatoshis, Self::Error> {
269 let mut t_in_total_size: usize = 0;
270 let mut unknown_p2sh_outpoints = vec![];
271 for sz in transparent_input_sizes.into_iter() {
272 match sz {
273 transparent::InputSize::Known(s) => {
274 t_in_total_size += s;
275 }
276 transparent::InputSize::Unknown(outpoint) => {
277 unknown_p2sh_outpoints.push(outpoint.clone());
278 }
279 }
280 }
281
282 if !unknown_p2sh_outpoints.is_empty() {
283 return Err(FeeError::UnknownP2shInputs(unknown_p2sh_outpoints));
284 }
285
286 let t_out_total_size = transparent_output_sizes.into_iter().sum();
287
288 let ceildiv = |num: usize, den: usize| num.div_ceil(den);
289
290 let logical_actions = max(
291 ceildiv(t_in_total_size, self.p2pkh_standard_input_size),
292 ceildiv(t_out_total_size, self.p2pkh_standard_output_size),
293 ) + max(sapling_input_count, sapling_output_count)
294 + orchard_action_count
295 + ironwood_action_count;
296
297 (self.marginal_fee(params, target_height) * max(self.grace_actions, logical_actions))
298 .ok_or_else(|| BalanceError::Overflow.into())
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 #![allow(deprecated)]
306
307 use core::iter;
308
309 use zcash_protocol::{
310 consensus::{BlockHeight, MAIN_NETWORK, NetworkUpgrade, Parameters, TEST_NETWORK},
311 local_consensus::LocalNetwork,
312 value::Zatoshis,
313 };
314
315 use super::{
316 FeeRule, GRACE_ACTIONS, MAINNET_FEE_REDUCTION_HEIGHT, MARGINAL_FEE, MINIMUM_FEE,
317 REVISION_2_MARGINAL_FEE, TESTNET_FEE_REDUCTION_HEIGHT, marginal_fee, minimum_fee,
318 revision_2_height,
319 };
320 use crate::transaction::fees::{FeeRule as _, transparent::InputSize};
321
322 #[cfg(feature = "non-standard-fees")]
323 use super::{P2PKH_STANDARD_INPUT_SIZE, P2PKH_STANDARD_OUTPUT_SIZE};
324
325 const REGTEST_NU7_HEIGHT: BlockHeight = BlockHeight::from_u32(10);
327
328 fn regtest(nu7: Option<BlockHeight>) -> LocalNetwork {
329 LocalNetwork {
330 overwinter: None,
331 sapling: None,
332 blossom: None,
333 heartwood: None,
334 canopy: None,
335 nu5: None,
336 nu6: None,
337 nu6_1: None,
338 nu6_2: None,
339 nu6_3: None,
340 nu7,
341 #[cfg(zcash_unstable = "nutachyon")]
342 nu_tachyon: None,
343 }
344 }
345
346 fn fee_for(orchard_action_count: usize, ironwood_action_count: usize) -> Zatoshis {
347 FeeRule::standard()
348 .fee_required(
349 &MAIN_NETWORK,
350 BlockHeight::from_u32(1_000_000),
351 iter::empty::<InputSize>(),
352 iter::empty::<usize>(),
353 0,
354 0,
355 orchard_action_count,
356 ironwood_action_count,
357 )
358 .unwrap()
359 }
360
361 fn fee_at<P: Parameters>(
364 rule: &FeeRule,
365 params: &P,
366 height: BlockHeight,
367 orchard_action_count: usize,
368 ) -> Zatoshis {
369 rule.fee_required(
370 params,
371 height,
372 iter::empty::<InputSize>(),
373 iter::empty::<usize>(),
374 0,
375 0,
376 orchard_action_count,
377 0,
378 )
379 .unwrap()
380 }
381
382 fn assert_fees_at<P: Parameters>(params: &P, height: BlockHeight, expected: Zatoshis) {
384 assert_eq!(marginal_fee(params, height), expected);
385 assert_eq!(
386 minimum_fee(params, height),
387 (expected * GRACE_ACTIONS).unwrap()
388 );
389 }
390
391 #[test]
392 fn ironwood_actions_charged_marginal_fee() {
393 assert_eq!(fee_for(0, 5), (MARGINAL_FEE * 5usize).unwrap());
396 }
397
398 #[test]
399 fn ironwood_actions_combine_with_orchard() {
400 assert_eq!(fee_for(2, 3), (MARGINAL_FEE * 5usize).unwrap());
402 }
403
404 #[test]
405 fn marginal_fee_per_network() {
406 let below = |h: BlockHeight| h - 1;
407
408 assert_eq!(
409 revision_2_height(&MAIN_NETWORK),
410 Some(MAINNET_FEE_REDUCTION_HEIGHT)
411 );
412 assert_fees_at(
413 &MAIN_NETWORK,
414 below(MAINNET_FEE_REDUCTION_HEIGHT),
415 MARGINAL_FEE,
416 );
417 assert_fees_at(
418 &MAIN_NETWORK,
419 MAINNET_FEE_REDUCTION_HEIGHT,
420 REVISION_2_MARGINAL_FEE,
421 );
422
423 assert_eq!(
424 revision_2_height(&TEST_NETWORK),
425 Some(TESTNET_FEE_REDUCTION_HEIGHT)
426 );
427 assert_eq!(
428 TEST_NETWORK.activation_height(NetworkUpgrade::Nu7),
429 Some(TESTNET_FEE_REDUCTION_HEIGHT)
430 );
431 assert_fees_at(
432 &TEST_NETWORK,
433 below(TESTNET_FEE_REDUCTION_HEIGHT),
434 MARGINAL_FEE,
435 );
436 assert_fees_at(
437 &TEST_NETWORK,
438 TESTNET_FEE_REDUCTION_HEIGHT,
439 REVISION_2_MARGINAL_FEE,
440 );
441
442 let with_nu7 = regtest(Some(REGTEST_NU7_HEIGHT));
443 assert_eq!(revision_2_height(&with_nu7), Some(REGTEST_NU7_HEIGHT));
444 assert_fees_at(&with_nu7, below(REGTEST_NU7_HEIGHT), MARGINAL_FEE);
445 assert_fees_at(&with_nu7, REGTEST_NU7_HEIGHT, REVISION_2_MARGINAL_FEE);
446
447 let without_nu7 = regtest(None);
448 assert_eq!(revision_2_height(&without_nu7), None);
449 assert_fees_at(&without_nu7, BlockHeight::from_u32(u32::MAX), MARGINAL_FEE);
450
451 assert_eq!(MARGINAL_FEE, Zatoshis::const_from_u64(5_000));
453 assert_eq!(MINIMUM_FEE, Zatoshis::const_from_u64(10_000));
454 }
455
456 #[test]
457 fn standard_rule_follows_schedule_and_fixed_rule_does_not() {
458 let rule = FeeRule::standard();
459 let before = MAINNET_FEE_REDUCTION_HEIGHT - 1;
460 let from = MAINNET_FEE_REDUCTION_HEIGHT;
461
462 assert_eq!(
464 fee_at(&rule, &MAIN_NETWORK, before, GRACE_ACTIONS),
465 minimum_fee(&MAIN_NETWORK, before)
466 );
467 assert_eq!(
468 fee_at(&rule, &MAIN_NETWORK, from, GRACE_ACTIONS),
469 minimum_fee(&MAIN_NETWORK, from)
470 );
471 assert_eq!(
472 rule.marginal_fee(&MAIN_NETWORK, from),
473 REVISION_2_MARGINAL_FEE
474 );
475
476 #[cfg(feature = "non-standard-fees")]
477 {
478 let fixed = FeeRule::non_standard(
479 MARGINAL_FEE,
480 GRACE_ACTIONS,
481 P2PKH_STANDARD_INPUT_SIZE,
482 P2PKH_STANDARD_OUTPUT_SIZE,
483 )
484 .unwrap();
485 assert_eq!(fixed.marginal_fee(&MAIN_NETWORK, from), MARGINAL_FEE);
486 assert_eq!(
487 fee_at(&fixed, &MAIN_NETWORK, from, GRACE_ACTIONS),
488 (MARGINAL_FEE * GRACE_ACTIONS).unwrap()
489 );
490 }
491 }
492}