Skip to main content

zebra_chain/transaction/
test_signing.rs

1//! Signing transparent-only transactions in tests.
2//!
3//! Regtest tests use this to put real, signed, spendable transactions into block templates and
4//! blocks.
5
6use secp256k1::{PublicKey, SecretKey};
7use zcash_primitives::transaction::{
8    builder::default_tx_expiry_delta,
9    fees::{
10        transparent::InputSize,
11        zip317::{FeeRule, P2PKH_STANDARD_OUTPUT_SIZE},
12        FeeRule as _,
13    },
14    sighash::{PrecomputedSighashData, SignableInput},
15    Authorized, TransactionData, TxVersion, Unauthorized,
16};
17use zcash_protocol::{consensus::BranchId, value::Zatoshis};
18use zcash_transparent::{
19    address::TransparentAddress,
20    builder::{TransparentBuilder, TransparentSigningSet},
21    bundle::OutPoint,
22};
23
24use crate::{
25    amount::{Amount, NonNegative},
26    block::Height,
27    parameters::{Network, NetworkKind},
28    transaction::{compat, Transaction},
29    transparent, BoxError,
30};
31
32/// A secp256k1 key that owns pay-to-public-key-hash outputs.
33#[derive(Clone, Debug)]
34pub struct TransparentSigningKey {
35    secret: SecretKey,
36    public: PublicKey,
37}
38
39impl TransparentSigningKey {
40    /// Generates a random key.
41    pub fn random() -> Self {
42        let secret = loop {
43            if let Ok(secret) = SecretKey::from_secret_bytes(rand::random()) {
44                break secret;
45            }
46        };
47        let public = PublicKey::from_secret_key(&secret);
48
49        Self { secret, public }
50    }
51
52    /// Returns the pay-to-public-key-hash address of this key.
53    pub fn address(&self, network_kind: NetworkKind) -> transparent::Address {
54        match TransparentAddress::from_pubkey(&self.public) {
55            TransparentAddress::PublicKeyHash(hash) => {
56                transparent::Address::from_pub_key_hash(network_kind, hash)
57            }
58            _ => unreachable!("a public key always hashes to a P2PKH address"),
59        }
60    }
61}
62
63impl Transaction {
64    /// Builds and signs a transparent-only transaction that spends `inputs`, which must all be
65    /// P2PKH outputs owned by `key`, to `outputs`.
66    ///
67    /// Pays the ZIP-317 conventional fee and returns the remainder to `key` as a final change
68    /// output, so `inputs` must cover `outputs` plus the fee with a non-dust amount left over.
69    pub fn signed_transparent(
70        network: &Network,
71        target_height: Height,
72        key: &TransparentSigningKey,
73        inputs: &[(transparent::OutPoint, transparent::Output)],
74        outputs: &[(transparent::Address, Amount<NonNegative>)],
75    ) -> Result<Self, BoxError> {
76        let target_height = compat::height_to_block_height(target_height);
77
78        // The change output counts towards the fee, so it is always added below.
79        let fee = FeeRule::standard()
80            .fee_required(
81                network,
82                target_height,
83                inputs.iter().map(|_| InputSize::STANDARD_P2PKH),
84                std::iter::repeat_n(P2PKH_STANDARD_OUTPUT_SIZE, outputs.len() + 1),
85                0,
86                0,
87                0,
88                0,
89            )
90            .map_err(|err| format!("{err:?}"))?;
91
92        let input_total: i64 = inputs
93            .iter()
94            .map(|(_, output)| output.value().zatoshis())
95            .sum();
96        let output_total: i64 = outputs.iter().map(|(_, value)| value.zatoshis()).sum();
97        let change = input_total - output_total - i64::try_from(u64::from(fee))?;
98        if change <= 0 {
99            return Err(format!(
100                "inputs ({input_total}) must exceed outputs ({output_total}) plus fee ({fee:?})"
101            )
102            .into());
103        }
104
105        let mut signing_set = TransparentSigningSet::new();
106        let pubkey = signing_set.add_key(key.secret);
107
108        let mut builder = TransparentBuilder::empty();
109        for (outpoint, output) in inputs {
110            builder.add_p2pkh_input(
111                pubkey,
112                OutPoint::new(outpoint.hash.0, outpoint.index),
113                compat::output_to_txout(output),
114            )?;
115        }
116
117        let change_output = (key.address(network.kind()), Amount::try_from(change)?);
118        // The mempool rejects dust outputs as non-standard.
119        if transparent::Output::new(change_output.1, change_output.0.script()).is_dust() {
120            return Err(format!("change ({change}) would be a dust output").into());
121        }
122        for (address, value) in outputs.iter().chain(std::iter::once(&change_output)) {
123            builder.add_output(
124                &(*address).try_into()?,
125                Zatoshis::from_u64(u64::from(*value))?,
126            )?;
127        }
128        let bundle = builder
129            .build()
130            .ok_or("transaction has no transparent inputs or outputs")?;
131
132        let branch_id = BranchId::for_height(network, target_height);
133        let version = TxVersion::suggested_for_branch(branch_id);
134        let expiry_height = target_height + default_tx_expiry_delta(branch_id);
135
136        let unauthed_tx = TransactionData::<Unauthorized>::from_parts(
137            version,
138            branch_id,
139            0,
140            expiry_height,
141            Some(bundle),
142            None,
143            None,
144            None,
145        );
146        let sighash_data = PrecomputedSighashData::new(unauthed_tx);
147        let signed_bundle = sighash_data
148            .tx()
149            .transparent_bundle()
150            .expect("bundle was just added")
151            .clone()
152            .apply_signatures(
153                |input| {
154                    *sighash_data
155                        .signature_hash(&SignableInput::Transparent(input))
156                        .as_ref()
157                },
158                &signing_set,
159            )?;
160
161        let signed_tx = TransactionData::<Authorized>::from_parts(
162            version,
163            branch_id,
164            0,
165            expiry_height,
166            Some(signed_bundle),
167            None,
168            None,
169            None,
170        )
171        .freeze()?;
172
173        Ok(Self(signed_tx))
174    }
175}