zcash_primitives/transaction/
coinbase.rs1use 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
26pub const MIN_COINBASE_SCRIPT_LEN: usize = 2;
32
33pub const MAX_COINBASE_SCRIPT_LEN: usize = 100;
39
40pub const MAX_COINBASE_HEIGHT_LEN: usize = 6;
47
48#[derive(Clone, Debug)]
50#[non_exhaustive]
51pub enum Error {
52 OversizedScript,
54 OversizedHeight,
56 GenesisInputNotSupported,
58 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#[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
120pub 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 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 (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 if s_len > MAX_COINBASE_SCRIPT_LEN {
193 return Err(Error::OversizedScript);
194 }
195
196 Ok(TxIn::from_parts(OutPoint::NULL, script_sig, u32::MAX))
205}
206
207pub fn is_coinbase<A: Authorization>(tx: &TransactionData<A>) -> bool {
215 tx.transparent_bundle()
216 .is_some_and(transparent_bundle_is_coinbase)
217}
218
219pub(crate) fn transparent_bundle_is_coinbase<A: TransparentAuthorization>(
221 bundle: &Bundle<A, Zatoshis>,
222) -> bool {
223 matches!(&bundle.vin[..], [input] if input.prevout() == &OutPoint::NULL)
226}
227
228#[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 const OP_1: u8 = 0x51;
274
275 const OP_16: u8 = 0x60;
277
278 const OP_0: u8 = 0x00;
280
281 const LAST_SMALL_HEIGHT: u32 = 16;
283
284 const FIRST_PUSHED_HEIGHT: u32 = 17;
287
288 const ONE_BYTE_SIGN_PADDED_HEIGHT: u32 = 0x80;
291
292 const TWO_BYTE_SIGN_PADDED_HEIGHT: u32 = 0x8000;
294
295 const SMALL_HEIGHT_LEN: usize = 1;
297
298 const PUSHDATA1_HEADER_LEN: usize = 2;
301
302 const MAX_MINER_DATA_LEN: usize =
305 MAX_COINBASE_SCRIPT_LEN - SMALL_HEIGHT_LEN - PUSHDATA1_HEADER_LEN;
306
307 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 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 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 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 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 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 const NO_LOCK_TIME: u32 = 0;
417
418 const NO_EXPIRY_HEIGHT: u32 = 0;
420
421 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}