zebra_chain/transaction/unmined/zip317.rs
1//! An implementation of the [ZIP-317] fee calculations for [UnminedTx]s:
2//! - [conventional fee](https://zips.z.cash/zip-0317#fee-calculation)
3//! - [block production transaction weight](https://zips.z.cash/zip-0317#block-production)
4
5use std::cmp::max;
6
7use thiserror::Error;
8
9use crate::{
10 amount::{Amount, NonNegative},
11 block::MAX_BLOCK_BYTES,
12 serialization::ZcashSerialize,
13 transaction::{Transaction, UnminedTx},
14};
15
16#[cfg(test)]
17mod tests;
18
19/// The marginal fee for the ZIP-317 fee calculation, in zatoshis per logical action.
20//
21// TODO: allow Amount<NonNegative> in constants
22pub const MARGINAL_FEE: u64 = 1_000;
23
24/// The number of grace logical actions allowed by the ZIP-317 fee calculation.
25const GRACE_ACTIONS: u32 = 2;
26
27/// The standard size of p2pkh inputs for the ZIP-317 fee calculation, in bytes.
28const P2PKH_STANDARD_INPUT_SIZE: usize = 150;
29
30/// The standard size of p2pkh outputs for the ZIP-317 fee calculation, in bytes.
31const P2PKH_STANDARD_OUTPUT_SIZE: usize = 34;
32
33/// The weight ratio cap for ZIP-317 block production.
34/// `weight_ratio_cap` in ZIP-317.
35const BLOCK_PRODUCTION_WEIGHT_RATIO_CAP: f32 = 10.0;
36
37/// The minimum fee for the block production weight ratio calculation, in zatoshis.
38/// If a transaction has a lower fee, this value is used instead.
39///
40/// This avoids special handling for transactions with zero weight.
41const MIN_BLOCK_PRODUCTION_SUBSTITUTE_FEE: i64 = 1;
42
43/// If a tx has more than `BLOCK_UNPAID_ACTION_LIMIT` "unpaid actions", it will never be mined by
44/// the [_Recommended algorithm for block template construction_][alg-def], implemented in Zebra
45/// [here][alg-impl].
46///
47/// [alg-def]: https://zips.z.cash/zip-0317#recommended-algorithm-for-block-template-construction
48/// [alg-impl]: https://github.com/zcashfoundation/zebra/blob/95e4d0973caac075b47589f6a05f9d744acd3db3/zebra-rpc/src/methods/get_block_template_rpcs/zip317.rs#L39
49pub const BLOCK_UNPAID_ACTION_LIMIT: u32 = 0;
50
51/// The minimum fee per kilobyte for Zebra mempool transactions.
52/// Also used as the minimum fee for a mempool transaction.
53///
54/// Based on `DEFAULT_MIN_RELAY_TX_FEE` in `zcashd`:
55/// <https://github.com/zcash/zcash/blob/f512291ff20098291442e83713de89bcddc07546/src/main.h#L71-L72>
56///
57/// This is a `usize` to simplify transaction size-based calculation code.
58pub const MIN_MEMPOOL_TX_FEE_RATE: usize = 100;
59
60/// The fee cap for [`MIN_MEMPOOL_TX_FEE_RATE`] minimum required mempool fees.
61///
62/// Based on `LEGACY_DEFAULT_FEE` in `zcashd`:
63/// <https://github.com/zcash/zcash/blob/9e856cfc5b81aa2607a16a23ff5584ea10014de6/src/amount.h#L35-L36>
64///
65/// This is a `usize` to simplify transaction size-based calculation code.
66pub const MEMPOOL_TX_FEE_REQUIREMENT_CAP: usize = 1000;
67
68/// Returns the conventional fee for `transaction`, as defined by [ZIP-317].
69///
70/// [ZIP-317]: https://zips.z.cash/zip-0317#fee-calculation
71pub fn conventional_fee(transaction: &Transaction) -> Amount<NonNegative> {
72 // zcash_primitives checks for non-p2pkh inputs, but Zebra doesn't.
73 // Conventional fees are only used in the standard rules for mempool eviction
74 // and block production, so these implementations are compatible.
75 //
76 // <https://github.com/zcash/librustzcash/blob/main/zcash_primitives/src/transaction/fees/zip317.rs#L135>
77
78 let marginal_fee: Amount<NonNegative> = MARGINAL_FEE.try_into().expect("fits in amount");
79
80 // marginal_fee * max(logical_actions, GRACE_ACTIONS)
81 let conventional_fee = marginal_fee * conventional_actions(transaction).into();
82
83 conventional_fee.expect("conventional fee is positive and limited by serialized size limit")
84}
85
86/// Returns the number of unpaid actions for `transaction`, as defined by [ZIP-317].
87///
88/// [ZIP-317]: https://zips.z.cash/zip-0317#block-production
89pub fn unpaid_actions(transaction: &UnminedTx, miner_fee: Amount<NonNegative>) -> u32 {
90 // max(logical_actions, GRACE_ACTIONS)
91 let conventional_actions = conventional_actions(&transaction.transaction);
92
93 // floor(tx.fee / marginal_fee)
94 let marginal_fee_weight_ratio = miner_fee / MARGINAL_FEE;
95 let marginal_fee_weight_ratio: i64 = marginal_fee_weight_ratio
96 .expect("marginal fee is not zero")
97 .into();
98
99 // max(0, conventional_actions - marginal_fee_weight_ratio)
100 //
101 // Subtracting MAX_MONEY/1000 from a u32 can't go above i64::MAX.
102 let unpaid_actions = i64::from(conventional_actions) - marginal_fee_weight_ratio;
103
104 unpaid_actions.try_into().unwrap_or_default()
105}
106
107/// Returns the block production fee weight ratio for `transaction`, as defined by [ZIP-317].
108///
109/// This calculation will always return a positive, non-zero value.
110///
111/// [ZIP-317]: https://zips.z.cash/zip-0317#block-production
112pub fn conventional_fee_weight_ratio(
113 transaction: &UnminedTx,
114 miner_fee: Amount<NonNegative>,
115) -> f32 {
116 // Check that this function will always return a positive, non-zero value.
117 //
118 // The maximum number of logical actions in a block is actually
119 // MAX_BLOCK_BYTES / MIN_ACTION_BYTES. MIN_ACTION_BYTES is currently
120 // the minimum transparent output size, but future transaction versions could change this.
121 assert!(
122 MIN_BLOCK_PRODUCTION_SUBSTITUTE_FEE as f32 / MAX_BLOCK_BYTES as f32 > 0.0,
123 "invalid block production constants: the minimum fee ratio must not be zero"
124 );
125
126 let miner_fee = max(miner_fee.into(), MIN_BLOCK_PRODUCTION_SUBSTITUTE_FEE) as f32;
127
128 let conventional_fee = i64::from(transaction.conventional_fee) as f32;
129
130 let uncapped_weight = miner_fee / conventional_fee;
131
132 uncapped_weight.min(BLOCK_PRODUCTION_WEIGHT_RATIO_CAP)
133}
134
135/// Returns the conventional actions for `transaction`, `max(logical_actions, GRACE_ACTIONS)`,
136/// as defined by [ZIP-317].
137///
138/// [ZIP-317]: https://zips.z.cash/zip-0317#fee-calculation
139pub fn conventional_actions(transaction: &Transaction) -> u32 {
140 let tx_in_total_size: usize = transaction
141 .inputs()
142 .iter()
143 .map(|input| input.zcash_serialized_size())
144 .sum();
145
146 let tx_out_total_size: usize = transaction
147 .outputs()
148 .iter()
149 .map(|output| output.zcash_serialized_size())
150 .sum();
151
152 let n_join_split = transaction.joinsplit_count();
153 let n_spends_sapling = transaction.sapling_spends_count();
154 let n_outputs_sapling = transaction.sapling_outputs().count();
155 let n_actions_orchard = transaction.orchard_actions().count();
156 // Ironwood actions have the same structure and cost as Orchard actions, so they are counted
157 // the same way. This is zero for pre-v6 transactions.
158 let n_actions_ironwood = transaction.ironwood_actions().count();
159
160 let tx_in_logical_actions = tx_in_total_size.div_ceil(P2PKH_STANDARD_INPUT_SIZE);
161 let tx_out_logical_actions = tx_out_total_size.div_ceil(P2PKH_STANDARD_OUTPUT_SIZE);
162
163 let logical_actions = max(tx_in_logical_actions, tx_out_logical_actions)
164 + 2 * n_join_split
165 + max(n_spends_sapling, n_outputs_sapling)
166 + n_actions_orchard
167 + n_actions_ironwood;
168 let logical_actions: u32 = logical_actions
169 .try_into()
170 .expect("transaction items are limited by serialized size limit");
171
172 max(GRACE_ACTIONS, logical_actions)
173}
174
175/// Make ZIP-317 checks before inserting a transaction into the mempool.
176pub fn mempool_checks(
177 unpaid_actions: u32,
178 miner_fee: Amount<NonNegative>,
179 transaction_size: usize,
180) -> Result<(), Error> {
181 // # Standard Rule
182 //
183 // > If a transaction has more than `block_unpaid_action_limit` "unpaid actions" as defined by the
184 // > Recommended algorithm for block template construction, it will never be mined by that algorithm.
185 // > Nodes MAY drop these transactions.
186 //
187 // <https://zips.z.cash/zip-0317#transaction-relaying>
188 if unpaid_actions > BLOCK_UNPAID_ACTION_LIMIT {
189 return Err(Error::UnpaidActions);
190 }
191
192 // # Standard Rule
193 //
194 // > Nodes that normally relay transactions are expected to do so for transactions that pay at least the
195 // > conventional fee as specified in this ZIP.
196 //
197 // <https://zips.z.cash/zip-0317#transaction-relaying>
198 //
199 // In Zebra, we use a similar minimum fee rate to `zcashd` v5.5.0 and later.
200 // Transactions must pay a fee of at least 100 zatoshis per 1000 bytes of serialized size,
201 // with a maximum fee of 1000 zatoshis.
202 //
203 // <https://github.com/zcash/zcash/blob/9e856cfc5b81aa2607a16a23ff5584ea10014de6/src/amount.cpp#L24-L37>
204 //
205 // In zcashd this is `DEFAULT_MIN_RELAY_TX_FEE` and `LEGACY_DEFAULT_FEE`:
206 // <https://github.com/zcash/zcash/blob/f512291ff20098291442e83713de89bcddc07546/src/main.h#L71-L72>
207 // <https://github.com/zcash/zcash/blob/9e856cfc5b81aa2607a16a23ff5584ea10014de6/src/amount.h#L35-L36>
208 //
209 // ## Note
210 //
211 // If the check above for the maximum number of unpaid actions passes with
212 // [`BLOCK_UNPAID_ACTION_LIMIT`] set to zero, then there is no way for the legacy check below to
213 // fail. This renders the legacy check redundant in that case.
214
215 const KILOBYTE: usize = 1000;
216
217 let max_block_size = usize::try_from(MAX_BLOCK_BYTES).map_err(|_| Error::InvalidMinFee)?;
218
219 // Blocks, and therefore, txs are limited to 2 MB and usize is at least 4 GB, implying that we
220 // can multiply MIN_MEMPOOL_TX_FEE_RATE by transaction_size without overflow.
221 assert!(MIN_MEMPOOL_TX_FEE_RATE < usize::MAX / max_block_size);
222
223 let min_fee: u64 = (MIN_MEMPOOL_TX_FEE_RATE * transaction_size / KILOBYTE)
224 .clamp(MIN_MEMPOOL_TX_FEE_RATE, MEMPOOL_TX_FEE_REQUIREMENT_CAP)
225 .try_into()
226 .map_err(|_| Error::InvalidMinFee)?;
227
228 let min_fee = Amount::<NonNegative>::try_from(min_fee).map_err(|_| Error::InvalidMinFee)?;
229
230 if miner_fee < min_fee {
231 return Err(Error::FeeBelowMinimumRate);
232 }
233
234 Ok(())
235}
236
237/// Errors related to ZIP-317.
238#[derive(Error, Clone, Debug, PartialEq, Eq)]
239#[allow(missing_docs)]
240pub enum Error {
241 #[error("Unpaid actions is higher than the limit")]
242 UnpaidActions,
243
244 #[error("Transaction fee is below the minimum fee rate")]
245 FeeBelowMinimumRate,
246
247 #[error("Minimum fee could not be calculated")]
248 InvalidMinFee,
249}