Skip to main content

zcash_primitives/transaction/
coinbase.rs

1//! Types, constants, and functions related to coinbase transactions.
2
3use alloc::vec::Vec;
4use core::fmt;
5
6use ::transparent::{
7    address::Script,
8    bundle::{
9        Authorization as TransparentAuthorization, Authorized, Bundle, MapAuth, OutPoint, TxIn,
10    },
11    sighash::TransparentAuthorizingContext,
12};
13use zcash_protocol::{consensus::BlockHeight, value::Zatoshis};
14use zcash_script::{
15    opcode::{Evaluable as _, PushValue},
16    pattern::push_num,
17    pv,
18    script::{self, Evaluable as _},
19};
20
21use crate::transaction::{Authorization, TransactionData};
22
23#[cfg(feature = "circuits")]
24use ::transparent::builder::TransparentBuilder;
25
26/// The minimum length of the coinbase transaction script.
27///
28/// [§ 7.1.2](https://zips.z.cash/protocol/protocol.pdf#txnconsensus) specifies:
29///
30/// > A coinbase transaction script MUST have length in {2 .. 100} bytes.
31pub const MIN_COINBASE_SCRIPT_LEN: usize = 2;
32
33/// The maximum length of the coinbase transaction script.
34///
35/// [§ 7.1.2](https://zips.z.cash/protocol/protocol.pdf#txnconsensus) specifies:
36///
37/// > A coinbase transaction script MUST have length in {2 .. 100} bytes.
38pub const MAX_COINBASE_SCRIPT_LEN: usize = 100;
39
40/// The maximum length of the encoded height in the coinbase transaction script.
41///
42/// [§ 7.1.2](https://zips.z.cash/protocol/protocol.pdf#txnconsensus) specifies:
43///
44/// > The length of `heightBytes` MUST be in the range {1 .. 5}. Then the encoding is the length of
45/// > `heightBytes` encoded as one byte, followed by `heightBytes` itself.
46pub const MAX_COINBASE_HEIGHT_LEN: usize = 6;
47
48/// Errors related to coinbase transactions.
49#[derive(Clone, Debug)]
50#[non_exhaustive]
51pub enum Error {
52    /// Encoded coinbase script exceeds [`MAX_COINBASE_SCRIPT_LEN`].
53    OversizedScript,
54    /// Encoded block height exceeds [`MAX_COINBASE_HEIGHT_LEN`].
55    OversizedHeight,
56    /// Creating a coinbase input for the genesis block is not supported.
57    GenesisInputNotSupported,
58    /// Coinbase transactions must contain only a dummy input.
59    UnexpectedInputs,
60}
61
62impl fmt::Display for Error {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        match self {
65            Error::OversizedScript => write!(
66                f,
67                "encoded coinbase script exceeds the limit of {MAX_COINBASE_SCRIPT_LEN} bytes",
68            ),
69            Error::OversizedHeight => write!(
70                f,
71                "encoded block height exceeds the limit of {MAX_COINBASE_HEIGHT_LEN} bytes",
72            ),
73            Error::GenesisInputNotSupported => write!(
74                f,
75                "creating a coinbase input for the genesis block is not supported",
76            ),
77            Error::UnexpectedInputs => {
78                write!(f, "coinbase transactions must contain only a dummy input",)
79            }
80        }
81    }
82}
83
84impl core::error::Error for Error {}
85
86/// [`transparent::bundle::Authorization`] marker for the transparent bundle of a
87/// coinbase transaction, which carries no authorizing data.
88///
89/// [`transparent::bundle::Authorization`]: ::transparent::bundle::Authorization
90#[derive(Debug, Clone)]
91pub struct Coinbase;
92
93impl TransparentAuthorization for Coinbase {
94    type ScriptSig = script::Sig;
95}
96
97impl TransparentAuthorizingContext<Zatoshis> for Coinbase {
98    fn input_amounts(&self) -> Vec<Zatoshis> {
99        vec![]
100    }
101
102    fn input_scriptpubkeys(&self) -> Vec<Script> {
103        vec![]
104    }
105}
106
107impl MapAuth<Coinbase, Authorized> for Coinbase {
108    fn map_script_sig(
109        &self,
110        s: <Coinbase as TransparentAuthorization>::ScriptSig,
111    ) -> <Authorized as TransparentAuthorization>::ScriptSig {
112        Script(script::Code(s.to_bytes()))
113    }
114
115    fn map_authorization(&self, _: Coinbase) -> Authorized {
116        Authorized
117    }
118}
119
120/// Creates the input of a coinbase transaction for the block at `height`.
121///
122/// The input's `script_sig` encodes `height`, followed by `miner_data` if it is given.
123/// Without `miner_data`, a height that encodes to a single byte is followed by `OP_0`,
124/// so that the script has the minimum length of [`MIN_COINBASE_SCRIPT_LEN`] bytes.
125///
126/// Returns:
127/// - [`Error::GenesisInputNotSupported`] if `height` is 0;
128/// - [`Error::OversizedHeight`] if the encoded height exceeds
129///   [`MAX_COINBASE_HEIGHT_LEN`] bytes;
130/// - [`Error::OversizedScript`] if the script exceeds [`MAX_COINBASE_SCRIPT_LEN`] bytes.
131pub fn coinbase_input(
132    height: BlockHeight,
133    miner_data: Option<PushValue>,
134) -> Result<TxIn<Coinbase>, Error> {
135    let h = match i64::from(height) {
136        0 => Err(Error::GenesisInputNotSupported),
137        h => Ok(push_num(h)),
138    }?;
139
140    let h_len = h.byte_len();
141    assert!(h_len > 0);
142
143    // # Consensus
144    //
145    // > A coinbase transaction for a block at block height greater than 0 MUST have a script
146    // > that, as its first item, encodes the block height `height` as follows. For `height` in
147    // > the range {1 .. 16}, the encoding is a single byte of value `0x50` + `height`.
148    // > Otherwise, let `heightBytes` be the signed little-endian representation of `height`,
149    // > using the minimum nonzero number of bytes such that the most significant byte is <
150    // > `0x80`. The length of `heightBytes` MUST be in the range {1 .. 5}. Then the encoding is
151    // > the length of `heightBytes` encoded as one byte, followed by `heightBytes` itself. This
152    // > matches the encoding used by Bitcoin in the implementation of [BIP-34] (but the
153    // > description here is to be considered normative).
154    //
155    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
156    //
157    // ## Note
158    //
159    // The height is encoded in `push_num`, which always returns an opcode, and every opcode
160    // serializes to at least one byte, so we assert the lower bound.
161    //
162    // [BIP-34]: <https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki>
163    if h_len > MAX_COINBASE_HEIGHT_LEN {
164        return Err(Error::OversizedHeight);
165    }
166
167    let script_sig = script::Component(
168        [
169            Some(h),
170            // Consensus rule: coinbase script must be at least 2 bytes.
171            (h_len < MIN_COINBASE_SCRIPT_LEN && miner_data.is_none()).then_some(pv::_0),
172            miner_data,
173        ]
174        .into_iter()
175        .flatten()
176        .collect(),
177    );
178
179    let s_len = script_sig.byte_len();
180    assert!(s_len >= MIN_COINBASE_SCRIPT_LEN);
181
182    // # Consensus
183    //
184    // > A coinbase transaction script MUST have length in {2 .. 100} bytes.
185    //
186    // <https://zips.z.cash/protocol/protocol.pdf#txnconsensus>
187    //
188    // ## Note
189    //
190    // The `miner_data` param always contains an opcode, and every opcode serializes to at least
191    // one byte, so we assert the lower bound.
192    if s_len > MAX_COINBASE_SCRIPT_LEN {
193        return Err(Error::OversizedScript);
194    }
195
196    // We set the `prevout` argument to [`OutPoint::NULL`] since [§ 3.11] defines coinbase txs
197    // as those that have a single transparent input with a null `prevout` field.
198    //
199    // We set the `sequence` field to [`u32::MAX`] to disable time-locking, as described in the
200    // [Bitcoin Developer Reference].
201    //
202    // [§ 3.11]: <https://zips.z.cash/protocol/protocol.pdf#coinbasetransactions>
203    // [Bitcoin Developer Reference]: <https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number>
204    Ok(TxIn::from_parts(OutPoint::NULL, script_sig, u32::MAX))
205}
206
207/// Returns `true` if `tx` is a coinbase transaction.
208///
209/// A transaction is a coinbase transaction if it has a transparent bundle with exactly
210/// one input, and that input's `prevout` is [`OutPoint::NULL`]. A transaction with no
211/// transparent bundle is not a coinbase transaction. The consensus rules place further
212/// requirements on the shielded parts of a coinbase transaction; this function does not
213/// check them.
214pub fn is_coinbase<A: Authorization>(tx: &TransactionData<A>) -> bool {
215    tx.transparent_bundle()
216        .is_some_and(transparent_bundle_is_coinbase)
217}
218
219/// Returns `true` if `bundle` is the transparent part of a coinbase transaction.
220pub(crate) fn transparent_bundle_is_coinbase<A: TransparentAuthorization>(
221    bundle: &Bundle<A, Zatoshis>,
222) -> bool {
223    // From `CTransaction::IsCoinBase()` in zcashd:
224    //   return (vin.size() == 1 && vin[0].prevout.IsNull());
225    matches!(&bundle.vin[..], [input] if input.prevout() == &OutPoint::NULL)
226}
227
228/// Builds the transparent bundle of a coinbase transaction from the outputs added to
229/// `builder`.
230///
231/// Returns [`Error::UnexpectedInputs`] if any inputs were added to `builder`, and
232/// otherwise any error of [`coinbase_input`].
233#[cfg(feature = "circuits")]
234pub(crate) fn build_transparent_bundle(
235    builder: TransparentBuilder<Zatoshis>,
236    height: BlockHeight,
237    miner_data: Option<PushValue>,
238) -> Result<Bundle<Coinbase, Zatoshis>, Error> {
239    #[cfg(feature = "transparent-inputs")]
240    if !builder.inputs().is_empty() {
241        return Err(Error::UnexpectedInputs);
242    }
243
244    Ok(Bundle {
245        vin: vec![coinbase_input(height, miner_data)?],
246        vout: builder.outputs().to_vec(),
247        authorization: Coinbase,
248    })
249}
250
251#[cfg(test)]
252mod tests {
253    use alloc::vec::Vec;
254
255    use ::transparent::{
256        address::Script,
257        bundle::{Authorized, Bundle, OutPoint, TxIn},
258    };
259    use assert_matches::assert_matches;
260    use zcash_protocol::{
261        consensus::{BlockHeight, BranchId},
262        value::Zatoshis,
263    };
264    use zcash_script::{pv, script::Evaluable as _};
265
266    use super::{
267        Error, MAX_COINBASE_HEIGHT_LEN, MAX_COINBASE_SCRIPT_LEN, coinbase_input, is_coinbase,
268        transparent_bundle_is_coinbase,
269    };
270    use crate::transaction::{TransactionData, TxVersion};
271
272    /// `OP_1`. Heights 1 to 16 are encoded as the single byte `0x50 + height`.
273    const OP_1: u8 = 0x51;
274
275    /// `OP_16`, the encoding of the largest height that is a single opcode.
276    const OP_16: u8 = 0x60;
277
278    /// `OP_0`, which pads a one-byte height encoding to the two-byte minimum script.
279    const OP_0: u8 = 0x00;
280
281    /// The largest height encoded as a small-integer opcode.
282    const LAST_SMALL_HEIGHT: u32 = 16;
283
284    /// The lowest height encoded as a length-prefixed number rather than a small-integer
285    /// opcode.
286    const FIRST_PUSHED_HEIGHT: u32 = 17;
287
288    /// The lowest height whose one-byte encoding (`0x80`) has its top bit set, so that
289    /// the signed little-endian encoding needs a zero padding byte.
290    const ONE_BYTE_SIGN_PADDED_HEIGHT: u32 = 0x80;
291
292    /// The lowest height whose two-byte encoding (`0x8000`) has its top bit set.
293    const TWO_BYTE_SIGN_PADDED_HEIGHT: u32 = 0x8000;
294
295    /// The encoded length of a height from 1 to 16.
296    const SMALL_HEIGHT_LEN: usize = 1;
297
298    /// The length of an `OP_PUSHDATA1` header: the opcode and one length byte. It
299    /// precedes pushed data of 76 to 255 bytes.
300    const PUSHDATA1_HEADER_LEN: usize = 2;
301
302    /// The longest miner data that fits in a coinbase script beside a height from 1 to
303    /// 16.
304    const MAX_MINER_DATA_LEN: usize =
305        MAX_COINBASE_SCRIPT_LEN - SMALL_HEIGHT_LEN - PUSHDATA1_HEADER_LEN;
306
307    /// An arbitrary byte of miner data that has no single-opcode encoding.
308    const MINER_DATA_BYTE: u8 = 0xab;
309
310    #[test]
311    fn genesis_is_rejected() {
312        assert_matches!(
313            coinbase_input(BlockHeight::from_u32(0), None),
314            Err(Error::GenesisInputNotSupported)
315        );
316    }
317
318    #[test]
319    fn small_height_is_one_opcode_padded_to_two_bytes() {
320        let txin = coinbase_input(BlockHeight::from_u32(1), None).unwrap();
321        assert_eq!(txin.script_sig().to_bytes(), [OP_1, OP_0]);
322        assert_eq!(txin.prevout(), &OutPoint::NULL);
323        assert_eq!(txin.sequence(), u32::MAX);
324    }
325
326    #[test]
327    fn larger_height_is_length_prefixed() {
328        let txin = coinbase_input(BlockHeight::from_u32(FIRST_PUSHED_HEIGHT), None).unwrap();
329        // One length byte, then the height as a single little-endian byte.
330        assert_eq!(
331            txin.script_sig().to_bytes(),
332            [0x01, FIRST_PUSHED_HEIGHT as u8]
333        );
334    }
335
336    #[test]
337    fn largest_small_height_is_one_opcode() {
338        let txin = coinbase_input(BlockHeight::from_u32(LAST_SMALL_HEIGHT), None).unwrap();
339        assert_eq!(txin.script_sig().to_bytes(), [OP_16, OP_0]);
340    }
341
342    #[test]
343    fn height_with_top_bit_set_is_sign_padded() {
344        let txin =
345            coinbase_input(BlockHeight::from_u32(ONE_BYTE_SIGN_PADDED_HEIGHT), None).unwrap();
346        // A length of 2, then `0x80` and the zero byte that keeps it non-negative.
347        assert_eq!(txin.script_sig().to_bytes(), [0x02, 0x80, 0x00]);
348
349        let txin =
350            coinbase_input(BlockHeight::from_u32(TWO_BYTE_SIGN_PADDED_HEIGHT), None).unwrap();
351        // A length of 3, then `0x8000` in little-endian order and the zero byte.
352        assert_eq!(txin.script_sig().to_bytes(), [0x03, 0x00, 0x80, 0x00]);
353    }
354
355    #[test]
356    fn largest_height_is_accepted() {
357        let txin = coinbase_input(BlockHeight::from_u32(u32::MAX), None).unwrap();
358        let script = txin.script_sig().to_bytes();
359        // A length of 5, then four `0xff` bytes and the zero byte.
360        assert_eq!(script, [0x05, 0xff, 0xff, 0xff, 0xff, 0x00]);
361        assert_eq!(script.len(), MAX_COINBASE_HEIGHT_LEN);
362    }
363
364    #[test]
365    fn miner_data_follows_the_height_without_padding() {
366        let data = pv::push_value(&[MINER_DATA_BYTE]).expect("short enough");
367        let txin = coinbase_input(BlockHeight::from_u32(1), Some(data)).unwrap();
368        // The height opcode, then a push of one byte.
369        assert_eq!(txin.script_sig().to_bytes(), [OP_1, 0x01, MINER_DATA_BYTE]);
370    }
371
372    #[test]
373    fn script_of_the_maximum_length_is_accepted() {
374        let data = pv::push_value(&[0u8; MAX_MINER_DATA_LEN]).expect("short enough");
375        let txin = coinbase_input(BlockHeight::from_u32(1), Some(data)).unwrap();
376        assert_eq!(txin.script_sig().to_bytes().len(), MAX_COINBASE_SCRIPT_LEN);
377    }
378
379    #[test]
380    fn script_one_byte_over_the_maximum_length_is_rejected() {
381        let data = pv::push_value(&[0u8; MAX_MINER_DATA_LEN + 1]).expect("short enough");
382        assert_matches!(
383            coinbase_input(BlockHeight::from_u32(1), Some(data)),
384            Err(Error::OversizedScript)
385        );
386    }
387
388    fn bundle(vin: Vec<TxIn<Authorized>>) -> Bundle<Authorized, Zatoshis> {
389        Bundle {
390            vin,
391            vout: vec![],
392            authorization: Authorized,
393        }
394    }
395
396    fn input(prevout: OutPoint) -> TxIn<Authorized> {
397        TxIn::from_parts(prevout, Script::default(), u32::MAX)
398    }
399
400    #[test]
401    fn coinbase_bundle_has_exactly_one_null_prevout() {
402        assert!(transparent_bundle_is_coinbase(&bundle(vec![input(
403            OutPoint::NULL
404        )])));
405        assert!(!transparent_bundle_is_coinbase(&bundle(vec![input(
406            OutPoint::fake()
407        )])));
408        assert!(!transparent_bundle_is_coinbase(&bundle(vec![
409            input(OutPoint::NULL),
410            input(OutPoint::NULL)
411        ])));
412        assert!(!transparent_bundle_is_coinbase(&bundle(vec![])));
413    }
414
415    /// A lock time of zero, which places no restriction on when a transaction is mined.
416    const NO_LOCK_TIME: u32 = 0;
417
418    /// An expiry height of zero, which means that a transaction does not expire.
419    const NO_EXPIRY_HEIGHT: u32 = 0;
420
421    /// Returns a transaction that has only the given transparent bundle.
422    fn transaction(
423        transparent_bundle: Option<Bundle<Authorized, Zatoshis>>,
424    ) -> TransactionData<crate::transaction::Authorized> {
425        TransactionData::from_parts(
426            TxVersion::V5,
427            BranchId::Nu5,
428            NO_LOCK_TIME,
429            BlockHeight::from_u32(NO_EXPIRY_HEIGHT),
430            transparent_bundle,
431            None,
432            None,
433            None,
434        )
435    }
436
437    #[test]
438    fn transaction_is_coinbase_exactly_when_its_transparent_bundle_is() {
439        assert!(is_coinbase(&transaction(Some(bundle(vec![input(
440            OutPoint::NULL
441        )])))));
442        assert!(!is_coinbase(&transaction(Some(bundle(vec![input(
443            OutPoint::fake()
444        )])))));
445        assert!(!is_coinbase(&transaction(None)));
446    }
447}