Skip to main content

zcash_primitives/transaction/fees/
transparent.rs

1//! Types related to computation of fees and change related to the transparent components
2//! of a transaction.
3
4use core::convert::Infallible;
5
6use crate::transaction::{
7    components::transparent::script_serialized_size, fees::zip317::P2PKH_STANDARD_INPUT_SIZE,
8};
9use transparent::{
10    address::Script,
11    bundle::{OutPoint, TxOut},
12};
13use zcash_protocol::value::Zatoshis;
14use zcash_script::{script, solver};
15
16#[cfg(feature = "transparent-inputs")]
17use {
18    core::iter,
19    transparent::builder::{SpendInfo, TransparentInputInfo},
20    zcash_encoding::CompactSize,
21    zcash_script::{pattern::push_script, pv, script::Evaluable as _},
22};
23
24/// The size of a transparent input, or the outpoint corresponding to the input
25/// if the size of the script required to spend that input is unknown.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub enum InputSize {
28    /// The txin size is known.
29    Known(usize),
30    /// The size of the script required to spend this input (and therefore the txin size)
31    /// is unknown.
32    Unknown(OutPoint),
33}
34
35impl InputSize {
36    /// An `InputSize` corresponding to the upper bound on the size of a P2PKH input used by ZIP 317.
37    pub const STANDARD_P2PKH: InputSize = InputSize::Known(P2PKH_STANDARD_INPUT_SIZE);
38}
39
40/// Maximum size of a DER-encoded ECDSA signature (72 bytes) plus one SIGHASH type byte.
41#[cfg(feature = "transparent-inputs")]
42const MAX_SIG_SIZE: usize = 72 + 1;
43
44/// Size of a serialized outpoint: transaction hash (32 bytes) + output index (4 bytes).
45#[cfg(feature = "transparent-inputs")]
46const PREVOUT_SIZE: usize = 32 + 4;
47
48/// Size of a serialized sequence number (u32).
49#[cfg(feature = "transparent-inputs")]
50const SEQUENCE_SIZE: usize = 4;
51
52/// Returns an upper bound, in bytes, on the serialized size of a P2SH input that spends
53/// via `redeem_script`, assuming signatures of the maximum length.
54///
55/// Returns `None` if the redeem script is not a recognized P2SH script kind (currently
56/// only P2MS-in-P2SH is supported).
57#[cfg(feature = "transparent-inputs")]
58pub fn p2sh_input_serialized_len(redeem_script: &script::FromChain) -> Option<usize> {
59    let fake_sig = pv::push_value(&[0; MAX_SIG_SIZE]).expect("short enough");
60
61    let script_len = redeem_script
62        .refine()
63        .ok()
64        .as_ref()
65        .and_then(solver::standard)
66        .and_then(|spend_info| match spend_info {
67            solver::ScriptKind::MultiSig { required, .. } => Some(
68                script::Component(
69                    iter::empty()
70                        .chain(Some(pv::_0))
71                        .chain(iter::repeat_n(fake_sig, usize::from(required)))
72                        .chain(push_script(redeem_script))
73                        .collect(),
74                )
75                .byte_len(),
76            ),
77            _ => None,
78        })?;
79
80    let script_sig_len = CompactSize::serialized_size(script_len) + script_len;
81    Some(PREVOUT_SIZE + script_sig_len + SEQUENCE_SIZE)
82}
83
84/// This trait provides a minimized view of a transparent input suitable for use in
85/// fee and change computation.
86pub trait InputView: core::fmt::Debug {
87    /// The outpoint to which the input refers.
88    fn outpoint(&self) -> &OutPoint;
89
90    /// The previous output being spent.
91    fn coin(&self) -> &TxOut<Zatoshis>;
92
93    /// The size of this transparent input in a transaction, as used in [ZIP 317].
94    ///
95    /// [ZIP 317]: https://zips.z.cash/zip-0317#rationale-for-the-chosen-parameters
96    fn serialized_size(&self) -> InputSize {
97        match script::PubKey::parse(&self.coin().script_pubkey().0)
98            .ok()
99            .as_ref()
100            .and_then(solver::standard)
101        {
102            Some(solver::ScriptKind::PubKeyHash { .. }) => InputSize::STANDARD_P2PKH,
103            _ => InputSize::Unknown(self.outpoint().clone()),
104        }
105    }
106}
107
108#[cfg(feature = "transparent-inputs")]
109impl InputView for TransparentInputInfo<Zatoshis> {
110    fn outpoint(&self) -> &OutPoint {
111        self.outpoint()
112    }
113
114    fn coin(&self) -> &TxOut<Zatoshis> {
115        self.coin()
116    }
117
118    fn serialized_size(&self) -> InputSize {
119        // For P2PKH inputs, return the ZIP 317 standard size (150 bytes) rather than the
120        // exact serialized size (which is one byte smaller). The proposal layer accounts
121        // for fees using the standard size; the builder must agree, otherwise a
122        // shielding transaction with enough P2PKH inputs to cross a
123        // `ceildiv(t_in_total_size, 150)` boundary will fail with `ChangeRequired`.
124        match self.spend_info() {
125            SpendInfo::P2pkh { .. } => InputSize::STANDARD_P2PKH,
126            SpendInfo::P2sh { redeem_script } => p2sh_input_serialized_len(redeem_script).map_or(
127                InputSize::Unknown(self.outpoint().clone()),
128                InputSize::Known,
129            ),
130        }
131    }
132}
133
134impl InputView for Infallible {
135    fn outpoint(&self) -> &OutPoint {
136        unreachable!()
137    }
138    fn coin(&self) -> &TxOut<Zatoshis> {
139        unreachable!()
140    }
141}
142
143/// This trait provides a minimized view of a transparent output suitable for use in
144/// fee and change computation.
145pub trait OutputView: core::fmt::Debug {
146    /// Returns the value of the output being created.
147    fn value(&self) -> Zatoshis;
148
149    /// Returns the script corresponding to the newly created output.
150    fn script_pubkey(&self) -> &Script;
151
152    /// Returns the serialized size of the txout.
153    fn serialized_size(&self) -> usize {
154        // The serialized size of a transparent `TxOut` is the serialized size of an amount
155        // plus the serialized size of the script pubkey.
156        8 + script_serialized_size(self.script_pubkey())
157    }
158}
159
160impl OutputView for TxOut<Zatoshis> {
161    fn value(&self) -> Zatoshis {
162        self.value()
163    }
164
165    fn script_pubkey(&self) -> &Script {
166        self.script_pubkey()
167    }
168}
169
170#[cfg(all(test, feature = "transparent-inputs"))]
171mod tests {
172    use secp256k1::{
173        PublicKey, SecretKey,
174        constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE},
175    };
176    use transparent::address::TransparentAddress;
177    use zcash_script::{
178        pattern::check_multisig,
179        script::{Component, FromChain},
180    };
181
182    use super::{MAX_SIG_SIZE, PREVOUT_SIZE, SEQUENCE_SIZE, p2sh_input_serialized_len};
183
184    /// The parts of a serialized input whose size does not depend on the script: the
185    /// outpoint and the sequence number.
186    const FIXED_INPUT_LEN: usize = PREVOUT_SIZE + SEQUENCE_SIZE;
187
188    /// `OP_0`, the dummy element that `OP_CHECKMULTISIG` consumes.
189    const DUMMY_LEN: usize = 1;
190
191    /// The cost of pushing at most 75 bytes of data: one opcode byte that gives the length.
192    const DIRECT_PUSH_OVERHEAD: usize = 1;
193
194    /// The cost of pushing 76 to 255 bytes of data: `OP_PUSHDATA1` and one length byte.
195    const PUSHDATA1_OVERHEAD: usize = 2;
196
197    /// The length of the CompactSize encoding of a value of at most 252.
198    const COMPACT_SIZE_ONE_BYTE_LEN: usize = 1;
199
200    /// The length of the CompactSize encoding of a value from 253 to 65535.
201    const COMPACT_SIZE_THREE_BYTE_LEN: usize = 3;
202
203    /// A direct push of a signature placeholder of the maximum length.
204    const SIG_PUSH_LEN: usize = DIRECT_PUSH_OVERHEAD + MAX_SIG_SIZE;
205
206    /// A direct push of a compressed public key.
207    const PUBKEY_PUSH_LEN: usize = DIRECT_PUSH_OVERHEAD + PUBLIC_KEY_SIZE;
208
209    /// The threshold opcode, the key-count opcode, and `OP_CHECKMULTISIG`.
210    const MULTISIG_OPCODES_LEN: usize = 3;
211
212    fn pubkey(seed: u8) -> [u8; PUBLIC_KEY_SIZE] {
213        let sk = SecretKey::from_secret_bytes([seed; SECRET_KEY_SIZE]).unwrap();
214        PublicKey::from_secret_key(&sk).serialize()
215    }
216
217    #[test]
218    fn p2sh_2_of_2_input_len() {
219        let (k1, k2) = (pubkey(1), pubkey(2));
220        let redeem_script: FromChain =
221            Component(check_multisig(2, &[&k1, &k2], false).unwrap()).weaken();
222        // The 71-byte redeem script fits a direct push (at most 75 bytes), and the
223        // 221-byte scriptSig fits a 1-byte CompactSize (at most 252).
224        let redeem_len = MULTISIG_OPCODES_LEN + 2 * PUBKEY_PUSH_LEN;
225        let script_sig_len = DUMMY_LEN + 2 * SIG_PUSH_LEN + (DIRECT_PUSH_OVERHEAD + redeem_len);
226        assert_eq!(
227            p2sh_input_serialized_len(&redeem_script),
228            Some(FIXED_INPUT_LEN + COMPACT_SIZE_ONE_BYTE_LEN + script_sig_len)
229        );
230    }
231
232    #[test]
233    fn p2sh_2_of_3_input_len() {
234        let (k1, k2, k3) = (pubkey(1), pubkey(2), pubkey(3));
235        let redeem_script: FromChain =
236            Component(check_multisig(2, &[&k1, &k2, &k3], false).unwrap()).weaken();
237        // The 105-byte redeem script needs OP_PUSHDATA1 (opcode plus length byte), and
238        // the 256-byte scriptSig needs a 3-byte CompactSize.
239        let redeem_len = MULTISIG_OPCODES_LEN + 3 * PUBKEY_PUSH_LEN;
240        let script_sig_len = DUMMY_LEN + 2 * SIG_PUSH_LEN + (PUSHDATA1_OVERHEAD + redeem_len);
241        assert_eq!(
242            p2sh_input_serialized_len(&redeem_script),
243            Some(FIXED_INPUT_LEN + COMPACT_SIZE_THREE_BYTE_LEN + script_sig_len)
244        );
245    }
246
247    #[test]
248    fn non_multisig_redeem_script_has_unknown_len() {
249        let p2pkh = TransparentAddress::PublicKeyHash([0; 20]).script().weaken();
250        assert_eq!(p2sh_input_serialized_len(&p2pkh), None);
251    }
252}