From 2edd4b6b6bdcb004f6386d5f96a8c929f90ea4c4 Mon Sep 17 00:00:00 2001 From: jolah1 Date: Tue, 3 Nov 2026 12:52:54 +0100 Subject: [PATCH 1/2] fix(channels_sv2)!: reject multi-input coinbases in try_strip_bip141 try_strip_bip141 strips the marker, the flag and the last witness stack, and only checked that this stack is framed like a coinbase's. A two-input transaction whose inputs each carry one 32-byte witness item passed that check: the first input's witness stayed in the "stripped" suffix and the prefix kept the two-input count, so the client built jobs from bytes that are not a transaction. The stripped stack is the whole witness section only when there is a single input, so read the input count after the marker and flag and return the new StripBip141Error::UnexpectedInputCount for anything other than one. https://github.com/stratum-mining/stratum/issues/2397 --- sv2/channels-sv2/src/bip141.rs | 94 +++++++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 7 deletions(-) diff --git a/sv2/channels-sv2/src/bip141.rs b/sv2/channels-sv2/src/bip141.rs index 1847ddd84f..76e009d06b 100644 --- a/sv2/channels-sv2/src/bip141.rs +++ b/sv2/channels-sv2/src/bip141.rs @@ -10,6 +10,7 @@ const FLAG_OFFSET: usize = 5; /// reserved for future layouts that may carry additional serialized sections. const BIP141_FLAG: u8 = 0x01; const MARKER_FLAG_LEN: usize = 2; +const INPUT_COUNT_OFFSET: usize = MARKER_OFFSET + MARKER_FLAG_LEN; const WITNESS_COUNT_LEN: usize = 1; const WITNESS_LEN_LEN: usize = 1; const WITNESS_DATA_LEN: usize = 32; @@ -31,6 +32,10 @@ pub enum StripBip141Error { /// The witness section does not frame exactly one 32-byte item, which a coinbase carrying the /// witness commitment must have. UnexpectedWitnessFraming, + /// The coinbase does not declare exactly one input. Each input has its own witness stack, so + /// with more than one the suffix would hold more witness data than the single stack stripped + /// here. + UnexpectedInputCount, } /// Tries to strip the bip141 marker, flag and witness data from `coinbase_tx_prefix` and @@ -46,13 +51,17 @@ pub enum StripBip141Error { /// # Errors /// /// Returns [`StripBip141Error::FailedToDeserializeCoinbaseInputs`] when -/// `coinbase_tx_prefix` is too short to contain the marker and flag. +/// `coinbase_tx_prefix` is too short to contain the marker and flag, or, when it carries them, +/// the input count that follows. /// /// Returns [`StripBip141Error::UnsupportedBip141Flag`] when `coinbase_tx_prefix` carries the /// bip141 marker with a flag other than the only currently defined value (`0x01`): other nonzero /// flags are reserved for future serialization layouts whose witness section cannot be assumed /// to have the fixed size stripped here. /// +/// Returns [`StripBip141Error::UnexpectedInputCount`] when `coinbase_tx_prefix` carries the +/// bip141 marker and flag but does not declare exactly one input, as a coinbase does. +/// /// Returns [`StripBip141Error::FailedToDeserializeCoinbaseLockTime`] when a transaction with a /// bip141 marker and flag has a suffix too short to contain the lock time (suffix < 4 bytes), or /// [`StripBip141Error::FailedToDeserializeCoinbaseWitness`] when the suffix is too short to @@ -84,6 +93,14 @@ pub fn try_strip_bip141( return Err(StripBip141Error::UnsupportedBip141Flag(flag)); } + // only the last witness stack is stripped below, which is the whole witness section only + // when the transaction has a single input + match coinbase_tx_prefix.get(INPUT_COUNT_OFFSET) { + None => return Err(StripBip141Error::FailedToDeserializeCoinbaseInputs), + Some(&1) => {} + Some(_) => return Err(StripBip141Error::UnexpectedInputCount), + } + // strip bip141 marker and flag bytes from coinbase_tx_prefix let mut coinbase_tx_prefix_stripped_bip141 = coinbase_tx_prefix[0..MARKER_OFFSET].to_vec(); coinbase_tx_prefix_stripped_bip141 @@ -122,6 +139,10 @@ mod tests { use alloc::vec; use super::*; + use bitcoin::{ + absolute::LockTime, consensus::serialize, hashes::Hash, transaction::Version, Amount, + OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Txid, Witness, + }; #[test] fn test_try_strip_bip141_sri_stripped() { @@ -234,11 +255,17 @@ mod tests { Err(StripBip141Error::FailedToDeserializeCoinbaseInputs) )); } + + // with the marker and flag, the input count must follow them + assert!(matches!( + try_strip_bip141(&[0, 0, 0, 0, 0, 1], &coinbase_tx_suffix), + Err(StripBip141Error::FailedToDeserializeCoinbaseInputs) + )); } #[test] fn test_try_strip_bip141_rejects_short_locktime_suffix() { - let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1]; + let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1, 1]; for suffix_len in 0..LOCKTIME_LEN { let coinbase_tx_suffix = vec![0; suffix_len]; @@ -252,7 +279,7 @@ mod tests { #[test] fn test_try_strip_bip141_rejects_short_witness_suffix() { - let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1]; + let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1, 1]; for suffix_len in LOCKTIME_LEN..MIN_COINBASE_TX_SUFFIX_LEN { let coinbase_tx_suffix = vec![0; suffix_len]; @@ -266,7 +293,7 @@ mod tests { #[test] fn test_try_strip_bip141_accepts_minimum_lengths() { - let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1]; + let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1, 1]; let mut coinbase_tx_suffix = [0; MIN_COINBASE_TX_SUFFIX_LEN]; coinbase_tx_suffix[0] = 1; coinbase_tx_suffix[1] = WITNESS_DATA_LEN as u8; @@ -275,7 +302,7 @@ mod tests { .expect("minimum valid bip141 parts should be accepted") .expect("bip141 marker and flag should be stripped"); - assert_eq!(result, (vec![0; 4], vec![0; 4])); + assert_eq!(result, (vec![0, 0, 0, 0, 1], vec![0; 4])); } #[test] @@ -287,7 +314,7 @@ mod tests { coinbase_tx_suffix[1] = WITNESS_DATA_LEN as u8; for flag in 0x02..=0xff { - let coinbase_tx_prefix = [0, 0, 0, 0, 0, flag]; + let coinbase_tx_prefix = [0, 0, 0, 0, 0, flag, 1]; assert!(matches!( try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix), @@ -298,7 +325,7 @@ mod tests { #[test] fn test_try_strip_bip141_rejects_invalid_witness_framing() { - let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1]; + let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1, 1]; let mut coinbase_tx_suffix = [0; MIN_COINBASE_TX_SUFFIX_LEN]; // a committed coinbase witness holds exactly one stack item @@ -317,4 +344,57 @@ mod tests { Err(StripBip141Error::UnexpectedWitnessFraming) )); } + + #[test] + fn test_try_strip_bip141_rejects_input_count_other_than_one() { + let mut coinbase_tx_suffix = [0; MIN_COINBASE_TX_SUFFIX_LEN]; + coinbase_tx_suffix[0] = 1; + coinbase_tx_suffix[1] = WITNESS_DATA_LEN as u8; + + for input_count in (0..=u8::MAX).filter(|input_count| *input_count != 1) { + let coinbase_tx_prefix = [0, 0, 0, 0, 0, 1, input_count]; + + assert!(matches!( + try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix), + Err(StripBip141Error::UnexpectedInputCount) + )); + } + } + + #[test] + fn test_try_strip_bip141_rejects_two_input_transaction() { + // both inputs carry a single 32-byte witness item, so the last witness stack alone is + // framed exactly like a coinbase's + let transaction = Transaction { + version: Version::TWO, + lock_time: LockTime::ZERO, + input: vec![ + TxIn { + previous_output: OutPoint::null(), + script_sig: ScriptBuf::from(vec![0; 8]), + sequence: Sequence::MAX, + witness: Witness::from(vec![vec![0; WITNESS_DATA_LEN]]), + }, + TxIn { + previous_output: OutPoint::new(Txid::from_byte_array([1; 32]), 0), + script_sig: ScriptBuf::new(), + sequence: Sequence::MAX, + witness: Witness::from(vec![vec![1; WITNESS_DATA_LEN]]), + }, + ], + output: vec![TxOut { + value: Amount::ZERO, + script_pubkey: ScriptBuf::new(), + }], + }; + let serialized = serialize(&transaction); + // split in the middle of the first input's scriptSig, where the extranonce would sit + let split = INPUT_COUNT_OFFSET + 1 + 36 + 1 + 4; + let (coinbase_tx_prefix, coinbase_tx_suffix) = serialized.split_at(split); + + assert!(matches!( + try_strip_bip141(coinbase_tx_prefix, coinbase_tx_suffix), + Err(StripBip141Error::UnexpectedInputCount) + )); + } } From 7f20b5659c0b078a0c887d7c34684f6843d70207 Mon Sep 17 00:00:00 2001 From: jolah1 Date: Tue, 3 Nov 2026 12:53:14 +0100 Subject: [PATCH 2/2] fix(channels_sv2)!: only attach the coinbase witness with a commitment The job factory and the client custom job always gave the coinbase input the 32-byte witness reserved value. BIP141 only allows a block to leave out the witness commitment when none of its transactions has witness data, so a template without a commitment output turned into blocks Bitcoin Core rejects as unexpected-witness, from both extended and standard channels. Attach the reserved value only when the outputs carry a commitment. Without a witness the coinbase serializes without the marker and flag, so the prefix/suffix split indexes count them only when there is one, and the strip sites use bytes that have nothing to strip as they are. ExtendedChannelError::FailedToStripBip141 had no other use and goes away. Prebuilt jobs are untouched: their bytes come from the application, which owns their witness. https://github.com/stratum-mining/stratum/issues/2397 --- sv2/channels-sv2/src/bip141.rs | 46 +++++++++- sv2/channels-sv2/src/client/error.rs | 1 - sv2/channels-sv2/src/client/extended.rs | 95 ++++++++++++++++--- sv2/channels-sv2/src/server/extended.rs | 97 +++++++++++++++++++- sv2/channels-sv2/src/server/jobs/extended.rs | 7 +- sv2/channels-sv2/src/server/jobs/factory.rs | 69 ++++++++++---- sv2/channels-sv2/src/server/jobs/standard.rs | 3 +- sv2/channels-sv2/src/server/standard.rs | 94 +++++++++++++++++++ 8 files changed, 373 insertions(+), 39 deletions(-) diff --git a/sv2/channels-sv2/src/bip141.rs b/sv2/channels-sv2/src/bip141.rs index 76e009d06b..04c0ecbfc2 100644 --- a/sv2/channels-sv2/src/bip141.rs +++ b/sv2/channels-sv2/src/bip141.rs @@ -1,8 +1,9 @@ //! Provides functionality to strip coinbase_tx_prefix and coinbase_tx_suffix from bip141 marker, -//! flag and witness data. +//! flag and witness data, and to tell which witness a coinbase must carry. extern crate alloc; -use alloc::vec::Vec; +use alloc::{vec, vec::Vec}; +use bitcoin::{TxOut, Witness}; const MARKER_OFFSET: usize = 4; const FLAG_OFFSET: usize = 5; @@ -16,6 +17,10 @@ const WITNESS_LEN_LEN: usize = 1; const WITNESS_DATA_LEN: usize = 32; const LOCKTIME_LEN: usize = 4; const BIP141_WITNESS_LEN: usize = WITNESS_COUNT_LEN + WITNESS_LEN_LEN + WITNESS_DATA_LEN; +/// Start of a witness commitment output script: `OP_RETURN`, a 36-byte push and the `aa21a9ed` +/// commitment header. +const WITNESS_COMMITMENT_HEADER: [u8; 6] = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed]; +const WITNESS_COMMITMENT_LEN: usize = 32; #[cfg(test)] const MIN_COINBASE_TX_SUFFIX_LEN: usize = BIP141_WITNESS_LEN + LOCKTIME_LEN; @@ -38,15 +43,46 @@ pub enum StripBip141Error { UnexpectedInputCount, } +/// Returns the witness of the input of a coinbase paying to `outputs`. +/// +/// BIP141 only lets a block leave out the witness commitment when none of its transactions +/// carries witness data, and a coinbase witness is witness data. So the coinbase carries the +/// 32-byte witness reserved value when `outputs` include a commitment, and no witness otherwise. +pub(crate) fn coinbase_witness(outputs: &[TxOut]) -> Witness { + let has_witness_commitment = outputs.iter().any(|output| { + let script = output.script_pubkey.as_bytes(); + script.len() >= WITNESS_COMMITMENT_HEADER.len() + WITNESS_COMMITMENT_LEN + && script.starts_with(&WITNESS_COMMITMENT_HEADER) + }); + + if has_witness_commitment { + // 32 bytes of zeros is only safe to assume now, this could change in future soft forks + Witness::from(vec![vec![0; WITNESS_DATA_LEN]]) + } else { + Witness::new() + } +} + +/// Returns the size of the bip141 marker and flag in the serialization of a transaction whose +/// only input carries `witness`: they are serialized only when there is witness data. +pub(crate) fn marker_flag_len(witness: &Witness) -> usize { + if witness.is_empty() { + 0 + } else { + MARKER_FLAG_LEN + } +} + /// Tries to strip the bip141 marker, flag and witness data from `coinbase_tx_prefix` and /// `coinbase_tx_suffix` of a `NewExtendedMiningJob`. /// /// This helps calculate the coinbase `txid` (instead of `wtxid`) for merkle root calculation, and /// it is particularly helpful for translation to Sv1. /// -/// If the coinbase transaction is already stripped of bip141, returns `Ok(None)`. -/// If the coinbase transaction is not stripped, returns `Ok(Some((Vec, Vec)))` with the -/// stripped `coinbase_tx_prefix` and `coinbase_tx_suffix`. +/// Returns `Ok(None)` when the bytes carry no bip141 marker and flag, whether they were already +/// stripped or the coinbase never had a witness (no witness commitment output): they can be used +/// as they are. Otherwise returns `Ok(Some((Vec, Vec)))` with the stripped +/// `coinbase_tx_prefix` and `coinbase_tx_suffix`. /// /// # Errors /// diff --git a/sv2/channels-sv2/src/client/error.rs b/sv2/channels-sv2/src/client/error.rs index 46f324bb64..84d617c018 100644 --- a/sv2/channels-sv2/src/client/error.rs +++ b/sv2/channels-sv2/src/client/error.rs @@ -25,7 +25,6 @@ pub enum ExtendedChannelError { /// The specified job ID was not found in the extended channel. JobIdNotFound, FailedToTryToStripBip141(StripBip141Error), - FailedToStripBip141, FailedToSerializeToB064K, FailedToDeserializeCoinbaseOutputs, ChannelIdMismatch, diff --git a/sv2/channels-sv2/src/client/extended.rs b/sv2/channels-sv2/src/client/extended.rs index d7224a8071..367ca742f3 100644 --- a/sv2/channels-sv2/src/client/extended.rs +++ b/sv2/channels-sv2/src/client/extended.rs @@ -6,7 +6,7 @@ extern crate alloc; use super::{HashMap, MAX_FUTURE_JOBS, MAX_PAST_JOBS}; use crate::{ - bip141::try_strip_bip141, + bip141::{coinbase_witness, marker_flag_len, try_strip_bip141}, chain_tip::ChainTip, client::{ error::ExtendedChannelError, @@ -25,7 +25,7 @@ use bitcoin::{ consensus::{serialize, Decodable}, hashes::sha256d::Hash, transaction::Version, - CompactTarget, OutPoint, Sequence, Target, Transaction, TxIn, TxOut, Witness, + CompactTarget, OutPoint, Sequence, Target, Transaction, TxIn, TxOut, }; use mining_sv2::{ NewExtendedMiningJobOwned, SetCustomMiningJobOwned, SetCustomMiningJobSuccess, @@ -578,9 +578,7 @@ impl ExtendedChannel { previous_output: OutPoint::null(), script_sig: script_sig.into(), sequence: Sequence(set_custom_mining_job.coinbase_tx_input_n_sequence), - witness: Witness::from(vec![vec![0; 32]]), /* note: 32 bytes of zeros is only safe to - * assume now, this could change in future - * soft forks */ + witness: coinbase_witness(&deserialized_outputs), }; let coinbase = Transaction { @@ -593,7 +591,7 @@ impl ExtendedChannel { let serialized_coinbase = serialize(&coinbase); let prefix_index = 4 // tx version - + 2 // segwit + + marker_flag_len(&coinbase.input[0].witness) // segwit marker and flag, if any + 1 // number of inputs + 32 // prev OutPoint + 4 // index @@ -606,11 +604,12 @@ impl ExtendedChannel { let coinbase_tx_suffix = serialized_coinbase[suffix_index..].to_vec(); - // strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix + // strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix; a coinbase without + // a witness commitment carries none, so its bytes are used as they are let (coinbase_tx_prefix_stripped_bip141, coinbase_tx_suffix_stripped_bip141) = try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix) .map_err(ExtendedChannelError::FailedToTryToStripBip141)? - .ok_or(ExtendedChannelError::FailedToStripBip141)?; + .unwrap_or_else(|| (coinbase_tx_prefix.clone(), coinbase_tx_suffix.clone())); let new_extended_mining_job = NewExtendedMiningJobOwned { channel_id: set_custom_mining_job.channel_id, @@ -1053,10 +1052,14 @@ mod tests { }, }; use binary_sv2::Sv2OptionOwned as Sv2Option; - use bitcoin::Target; + use bitcoin::{ + consensus::{deserialize, serialize}, + Amount, ScriptBuf, Target, Transaction, TxOut, + }; use mining_sv2::{ - NewExtendedMiningJobOwned as NewExtendedMiningJob, SetNewPrevHashOwned as SetNewPrevHashMp, - SubmitSharesExtendedOwned as SubmitSharesExtended, + NewExtendedMiningJobOwned as NewExtendedMiningJob, + SetCustomMiningJobOwned as SetCustomMiningJob, SetCustomMiningJobSuccess, + SetNewPrevHashOwned as SetNewPrevHashMp, SubmitSharesExtendedOwned as SubmitSharesExtended, ERROR_CODE_SUBMIT_SHARES_INVALID_NON_ROLLABLE_VERSION_BIT, }; use std::convert::TryInto; @@ -3846,4 +3849,74 @@ mod tests { Err(ShareValidationError::Stale(_)) )); } + + #[test] + fn test_custom_job_success_without_witness_commitment() { + // the outputs carry no witness commitment, so the coinbase is built without a witness + // and serializes without the bip141 marker and flag; the job's prefix and suffix must + // still split it exactly around the extranonce + let mut channel = ExtendedChannel::new( + 1, + "user_identity".to_string(), + ExtranoncePrefix::from_wire(vec![1; 24]).unwrap(), + Target::from_le_bytes([0xff; 32]), + 1.0, + true, + 8, + None, + ) + .unwrap(); + channel + .on_chain_tip_update(ChainTip::new([0u8; 32].into(), 503543726, 1746839905)) + .unwrap(); + + let mut script_bytes = vec![0]; // SegWit version 0 + script_bytes.push(20); // Push 20 bytes (length of pubkey hash) + script_bytes.extend_from_slice(&[ + 235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, + 8, 252, + ]); + let coinbase_outputs = vec![TxOut { + value: Amount::from_sat(5_000_000_000), + script_pubkey: ScriptBuf::from(script_bytes), + }]; + let coinbase_prefix = vec![0xab; 4]; + + let set_custom_mining_job = SetCustomMiningJob { + channel_id: 1, + request_id: 1, + token: vec![0].try_into().unwrap(), + version: 536870912, + prev_hash: [0u8; 32].into(), + ntime_start: 1746839905, + nbits: 503543726, + coinbase_tx_version: 2, + coinbase_prefix: coinbase_prefix.clone().try_into().unwrap(), + coinbase_tx_input_n_sequence: 4294967295, + coinbase_tx_outputs: serialize(&coinbase_outputs).try_into().unwrap(), + coinbase_tx_locktime: 0, + merkle_path: vec![].try_into().unwrap(), + }; + let set_custom_mining_job_success = SetCustomMiningJobSuccess { + channel_id: 1, + request_id: 1, + job_id: 1, + }; + channel + .on_set_custom_mining_job_success(set_custom_mining_job, set_custom_mining_job_success) + .unwrap(); + + let job_message = &channel.get_active_job().unwrap().job_message; + let full_extranonce = vec![0xee; channel.get_full_extranonce_size()]; + let mut serialized_coinbase = job_message.coinbase_tx_prefix.to_owned_bytes(); + serialized_coinbase.extend(&full_extranonce); + serialized_coinbase.extend(job_message.coinbase_tx_suffix.as_bytes()); + let coinbase: Transaction = deserialize(&serialized_coinbase).unwrap(); + + assert_eq!( + coinbase.input[0].script_sig.as_bytes(), + [coinbase_prefix, full_extranonce].concat() + ); + assert_eq!(coinbase.output, coinbase_outputs); + } } diff --git a/sv2/channels-sv2/src/server/extended.rs b/sv2/channels-sv2/src/server/extended.rs index b3ec8080d3..61d88b64b3 100644 --- a/sv2/channels-sv2/src/server/extended.rs +++ b/sv2/channels-sv2/src/server/extended.rs @@ -1268,7 +1268,9 @@ mod tests { MAX_EXTRANONCE_LEN, }; use binary_sv2::{Sv2OptionOwned as Sv2Option, U256Owned as U256}; - use bitcoin::{transaction::TxOut, Amount, ScriptBuf, Target}; + use bitcoin::{ + consensus::deserialize, transaction::TxOut, Amount, ScriptBuf, Target, Transaction, + }; use mining_sv2::{ NewExtendedMiningJobOwned as NewExtendedMiningJob, SetCustomMiningJobOwned as SetCustomMiningJob, @@ -1760,6 +1762,99 @@ mod tests { assert_eq!(channel.get_share_accounting().get_blocks_found(), 1); } + #[test] + fn test_share_validation_block_found_without_witness_commitment() { + // a template without a witness commitment output: BIP141 then forbids witness data in + // the block, so the coinbase of a found block must carry no witness + let channel_id = 1; + let extranonce_prefix = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + ] + .to_vec(); + let mut channel = ExtendedChannel::new( + channel_id, + "user_identity".to_string(), + ExtranoncePrefix::from_wire(extranonce_prefix.clone()).unwrap(), + Target::from_le_bytes([0xff; 32]), + 1.0, + true, + 8, + 100, + 1.0, + None, + None, + None, + ) + .unwrap(); + + let template = NewTemplate { + template_id: 1, + future_template: false, + version: 536870912, + coinbase_tx_version: 2, + coinbase_prefix: vec![82, 0].try_into().unwrap(), + coinbase_tx_input_sequence: 4294967295, + coinbase_tx_value_remaining: SATS_AVAILABLE_IN_TEMPLATE, + coinbase_tx_outputs_count: 0, + coinbase_tx_outputs: Vec::::new().try_into().unwrap(), + coinbase_tx_locktime: 0, + merkle_path: vec![].try_into().unwrap(), + }; + + let pubkey_hash = [ + 235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, + 8, 252, + ]; + let mut script_bytes = vec![0]; // SegWit version 0 + script_bytes.push(20); // Push 20 bytes (length of pubkey hash) + script_bytes.extend_from_slice(&pubkey_hash); + let coinbase_reward_outputs = vec![TxOut { + value: Amount::from_sat(SATS_AVAILABLE_IN_TEMPLATE), + script_pubkey: ScriptBuf::from(script_bytes), + }]; + + // network target: 7fffff0000000000000000000000000000000000000000000000000000000000 + let prev_hash = [ + 251, 175, 106, 40, 35, 87, 122, 90, 58, 51, 78, 32, 202, 236, 228, 36, 154, 174, 206, + 144, 147, 195, 21, 224, 195, 103, 214, 189, 51, 190, 24, 98, + ] + .into(); + let chain_tip = ChainTip::new(prev_hash, 545259519, 1745596910); + channel.set_chain_tip(chain_tip); + channel + .on_new_template(template, coinbase_reward_outputs.clone()) + .unwrap(); + + // this share has hash 1d0d70334da873a6002ef10d4f2c6d17632ba009d1ef234702187018fae5d09d + // which satisfies the network target + let rollable_extranonce = vec![1, 0, 0, 0, 0, 0, 0, 0]; + let share_valid_block = SubmitSharesExtended { + channel_id, + sequence_number: 0, + job_id: 1, + nonce: 1, + ntime: 1745596971, + version: 536870912, + extranonce: rollable_extranonce.clone().try_into().unwrap(), + }; + + let Ok(ShareValidationResult::BlockFound(_, _, serialized_coinbase)) = + channel.validate_share(share_valid_block) + else { + panic!("expected BlockFound"); + }; + + let coinbase: Transaction = deserialize(&serialized_coinbase).unwrap(); + assert!(coinbase.input[0].witness.is_empty()); + assert_eq!(coinbase.output, coinbase_reward_outputs); + let mut full_extranonce = extranonce_prefix; + full_extranonce.extend(rollable_extranonce); + assert!(coinbase.input[0] + .script_sig + .as_bytes() + .ends_with(&full_extranonce)); + } + #[test] fn test_share_validation_block_found_below_job_target_earns_network_difficulty() { // reuses the pre-mined share from test_share_validation_block_found: its hash diff --git a/sv2/channels-sv2/src/server/jobs/extended.rs b/sv2/channels-sv2/src/server/jobs/extended.rs index 46ae4c860e..30386778ee 100644 --- a/sv2/channels-sv2/src/server/jobs/extended.rs +++ b/sv2/channels-sv2/src/server/jobs/extended.rs @@ -14,9 +14,10 @@ use template_distribution_sv2::NewTemplateOwned; /// - all coinbase outputs (spendable + unspendable) associated with the job /// - the `NewExtendedMiningJob` message to be sent across the wire /// -/// Please note that `coinbase_tx_prefix` and `coinbase_tx_suffix` are stored in memory with bip141 -/// data (marker, flag and witness). That makes it easy to reconstruct the segwit coinbase while -/// trying to propagate a block. +/// Please note that `coinbase_tx_prefix` and `coinbase_tx_suffix` are stored in memory with the +/// bip141 data (marker, flag and witness) of the coinbase, which only has them when its outputs +/// include a witness commitment. That makes it easy to reconstruct the coinbase while trying to +/// propagate a block. /// /// However, the `coinbase_tx_prefix` and `coinbase_tx_suffix` contained in the /// `NewExtendedMiningJob` message to be sent across the wire DO NOT contain bip141 data. diff --git a/sv2/channels-sv2/src/server/jobs/factory.rs b/sv2/channels-sv2/src/server/jobs/factory.rs index d341bb9eb2..9e09b36e91 100644 --- a/sv2/channels-sv2/src/server/jobs/factory.rs +++ b/sv2/channels-sv2/src/server/jobs/factory.rs @@ -25,7 +25,7 @@ //! incoming SV2 messages (`NewTemplate`, `SetCustomMiningJob`), ensuring protocol correctness and //! uniqueness of job IDs. use crate::{ - bip141::try_strip_bip141, + bip141::{coinbase_witness, marker_flag_len, try_strip_bip141}, chain_tip::ChainTip, merkle_root::merkle_root_from_path, outputs::deserialize_template_outputs, @@ -34,7 +34,6 @@ use crate::{ use binary_sv2::{B0255Owned, Sv2OptionOwned}; use bitcoin::{ absolute::LockTime, - blockdata::witness::Witness, consensus::{serialize, Decodable}, transaction::{OutPoint, Transaction, TxIn, TxOut, Version}, Amount, Sequence, @@ -331,11 +330,12 @@ impl JobFactory { full_extranonce_size, )?; - // strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix + // strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix; a coinbase without + // a witness commitment carries none, so its bytes are used as they are let (coinbase_tx_prefix_stripped_bip141, coinbase_tx_suffix_stripped_bip141) = try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix) .map_err(|_| JobFactoryError::FailedToStripBip141)? - .ok_or(JobFactoryError::FailedToStripBip141)?; + .unwrap_or_else(|| (coinbase_tx_prefix.clone(), coinbase_tx_suffix.clone())); let merkle_path = template.merkle_path.clone(); @@ -527,11 +527,12 @@ impl JobFactory { let coinbase_tx_suffix = self.custom_coinbase_tx_suffix(set_custom_mining_job.clone(), full_extranonce_size)?; - // strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix + // strip bip141 bytes from coinbase_tx_prefix and coinbase_tx_suffix; a coinbase without + // a witness commitment carries none, so its bytes are used as they are let (coinbase_tx_prefix_stripped_bip141, coinbase_tx_suffix_stripped_bip141) = try_strip_bip141(&coinbase_tx_prefix, &coinbase_tx_suffix) .map_err(|_| JobFactoryError::FailedToStripBip141)? - .ok_or(JobFactoryError::FailedToStripBip141)?; + .unwrap_or_else(|| (coinbase_tx_prefix.clone(), coinbase_tx_suffix.clone())); let merkle_path = set_custom_mining_job.merkle_path.clone(); @@ -649,9 +650,7 @@ impl JobFactory { previous_output: OutPoint::null(), script_sig: script_sig.into(), sequence: Sequence(m.coinbase_tx_input_n_sequence), - witness: Witness::from(vec![vec![0; 32]]), /* note: 32 bytes of zeros is only safe to - * assume now, this could change in future - * soft forks */ + witness: coinbase_witness(&deserialized_outputs), }; Ok(Transaction { @@ -674,7 +673,7 @@ impl JobFactory { // always below the 253 byte threshold where CompactSize switches from a 1-byte to a // 3-byte encoding, so the script length prefix is unconditionally 1 byte let index = 4 // tx version - + 2 // segwit + + marker_flag_len(&coinbase.input[0].witness) // segwit marker and flag, if any + 1 // number of inputs + 32 // prev OutPoint + 4 // index @@ -698,7 +697,7 @@ impl JobFactory { // always below the 253 byte threshold where CompactSize switches from a 1-byte to a // 3-byte encoding, so the script length prefix is unconditionally 1 byte let index = 4 // tx version - + 2 // segwit + + marker_flag_len(&coinbase.input[0].witness) // segwit marker and flag, if any + 1 // number of inputs + 32 // prev OutPoint + 4 // index @@ -766,9 +765,7 @@ impl JobFactory { previous_output: OutPoint::null(), script_sig: script_sig.into(), sequence: Sequence(template.coinbase_tx_input_sequence), - witness: Witness::from(vec![vec![0; 32]]), /* note: 32 bytes of zeros is only safe to - * assume now, this could change in future - * soft forks */ + witness: coinbase_witness(&outputs), }; Ok(Transaction { @@ -799,7 +796,7 @@ impl JobFactory { // always below the 253 byte threshold where CompactSize switches from a 1-byte to a // 3-byte encoding, so the script length prefix is unconditionally 1 byte let index = 4 // tx version - + 2 // segwit bytes + + marker_flag_len(&coinbase.input[0].witness) // segwit marker and flag, if any + 1 // number of inputs + 32 // prev OutPoint + 4 // index @@ -833,7 +830,7 @@ impl JobFactory { // always below the 253 byte threshold where CompactSize switches from a 1-byte to a // 3-byte encoding, so the script length prefix is unconditionally 1 byte let coinbase_tx_suffix = serialized_coinbase[4 // tx version - + 2 // segwit bytes + + marker_flag_len(&coinbase.input[0].witness) // segwit marker and flag, if any + 1 // number of inputs + 32 // prev OutPoint + 4 // index @@ -851,7 +848,7 @@ impl JobFactory { #[cfg(test)] mod tests { use super::*; - use bitcoin::ScriptBuf; + use bitcoin::{consensus::deserialize, ScriptBuf}; use mining_sv2::NewExtendedMiningJobOwned as NewExtendedMiningJob; use template_distribution_sv2::NewTemplateOwned as NewTemplate; @@ -1248,6 +1245,44 @@ mod tests { )); } + #[test] + fn test_custom_job_without_witness_commitment() { + // coinbase_reward_outputs() carries no witness commitment, so BIP141 forbids a coinbase + // witness: the bytes a found block is assembled from have none to strip + let mut job_factory = JobFactory::new(true, None, None); + let coinbase_prefix = vec![0xab; 4]; + let full_extranonce = vec![0xee; 32]; + + let job = job_factory + .new_extended_job_from_custom_job( + custom_job_with_coinbase_prefix(coinbase_prefix.clone()), + vec![0; 32], + full_extranonce.len(), + ) + .unwrap(); + + assert_eq!( + job.get_coinbase_tx_prefix_with_bip141(), + job.get_coinbase_tx_prefix_without_bip141() + ); + assert_eq!( + job.get_coinbase_tx_suffix_with_bip141(), + job.get_coinbase_tx_suffix_without_bip141() + ); + + let mut serialized_coinbase = job.get_coinbase_tx_prefix_with_bip141(); + serialized_coinbase.extend(&full_extranonce); + serialized_coinbase.extend(job.get_coinbase_tx_suffix_with_bip141()); + let coinbase: Transaction = deserialize(&serialized_coinbase).unwrap(); + + assert!(coinbase.input[0].witness.is_empty()); + assert_eq!( + coinbase.input[0].script_sig.as_bytes(), + [coinbase_prefix, full_extranonce].concat() + ); + assert_eq!(coinbase.output, coinbase_reward_outputs()); + } + #[test] fn test_new_extended_job_from_prebuilt_job() { let mut job_factory = JobFactory::new(false, Some("pool".to_string()), None); diff --git a/sv2/channels-sv2/src/server/jobs/standard.rs b/sv2/channels-sv2/src/server/jobs/standard.rs index 8974ffe8d1..90138d43a6 100644 --- a/sv2/channels-sv2/src/server/jobs/standard.rs +++ b/sv2/channels-sv2/src/server/jobs/standard.rs @@ -41,7 +41,8 @@ use template_distribution_sv2::NewTemplateOwned; /// /// For a job built from a template, the coinbase bytes are the serialized coinbase the job /// factory assembled, split at the extranonce, so they carry the BIP141 data (marker, flag and -/// witness) a found block needs. For a [`PrebuiltJob`](super::PrebuiltJob), they are the bytes +/// witness) a found block needs, if any: the factory only adds it when the outputs include a +/// witness commitment. For a [`PrebuiltJob`](super::PrebuiltJob), they are the bytes /// handed over, as given. #[derive(Debug, Clone)] pub struct StandardJob { diff --git a/sv2/channels-sv2/src/server/standard.rs b/sv2/channels-sv2/src/server/standard.rs index 7b626f79dc..eadc95a8d0 100644 --- a/sv2/channels-sv2/src/server/standard.rs +++ b/sv2/channels-sv2/src/server/standard.rs @@ -1476,6 +1476,100 @@ mod tests { ); } + #[test] + fn test_share_validation_block_found_without_witness_commitment() { + // a template without a witness commitment output: BIP141 then forbids witness data in + // the block, so the coinbase of a found block must carry no witness + let standard_channel_id = 1; + let extranonce_prefix = [ + 83, 116, 114, 97, 116, 117, 109, 32, 86, 50, 32, 83, 82, 73, 32, 80, 111, 111, 108, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, + ] + .to_vec(); + let mut standard_channel = StandardChannel::new( + standard_channel_id, + "user_identity".to_string(), + ExtranoncePrefix::from_wire(extranonce_prefix.clone()).unwrap(), + Target::from_le_bytes([0xff; 32]), + 1.0, + 100, + 1.0, + None, + None, + None, + ) + .unwrap(); + + let template = NewTemplate { + template_id: 1, + future_template: false, + version: 536870912, + coinbase_tx_version: 2, + coinbase_prefix: vec![82, 0].try_into().unwrap(), + coinbase_tx_input_sequence: 4294967295, + coinbase_tx_value_remaining: SATS_AVAILABLE_IN_TEMPLATE, + coinbase_tx_outputs_count: 0, + coinbase_tx_outputs: Vec::::new().try_into().unwrap(), + coinbase_tx_locktime: 0, + merkle_path: vec![].try_into().unwrap(), + }; + + let pubkey_hash = [ + 235, 225, 183, 220, 194, 147, 204, 170, 14, 231, 67, 168, 111, 137, 223, 130, 88, 194, + 8, 252, + ]; + let mut script_bytes = vec![0]; // SegWit version 0 + script_bytes.push(20); // Push 20 bytes (length of pubkey hash) + script_bytes.extend_from_slice(&pubkey_hash); + let coinbase_reward_outputs = vec![TxOut { + value: Amount::from_sat(SATS_AVAILABLE_IN_TEMPLATE), + script_pubkey: ScriptBuf::from(script_bytes), + }]; + + // network target: 7fffff0000000000000000000000000000000000000000000000000000000000 + let prev_hash = [ + 251, 175, 106, 40, 35, 87, 122, 90, 58, 51, 78, 32, 202, 236, 228, 36, 154, 174, 206, + 144, 147, 195, 21, 224, 195, 103, 214, 189, 51, 190, 24, 98, + ] + .into(); + let chain_tip = ChainTip::new(prev_hash, 545259519, 1745596910); + standard_channel.set_chain_tip(chain_tip); + standard_channel + .on_new_template(template, coinbase_reward_outputs.clone()) + .unwrap(); + let active_standard_job = standard_channel.get_active_job().unwrap(); + let job_id = active_standard_job.get_job_id(); + let job_merkle_root = active_standard_job.get_merkle_root().to_array(); + + // this share has hash 41795802f79ee046f7b5920c9efbf791a8e492c0850c40943319d4c3522c51a3 + // which satisfies the network target + let share_valid_block = SubmitSharesStandardOwned { + channel_id: standard_channel_id, + sequence_number: 0, + job_id, + nonce: 2, + ntime: 1745596932, + version: 536870912, + }; + + let Ok(ShareValidationResult::BlockFound(_, _, serialized_coinbase)) = + standard_channel.validate_share(share_valid_block) + else { + panic!("expected BlockFound"); + }; + + let coinbase: Transaction = deserialize(&serialized_coinbase).unwrap(); + assert!(coinbase.input[0].witness.is_empty()); + assert_eq!(coinbase.output, coinbase_reward_outputs); + // merkle_path is empty in this template, so the merkle root IS the coinbase txid + let coinbase_txid: [u8; 32] = *coinbase.compute_txid().as_ref(); + assert_eq!(coinbase_txid, job_merkle_root); + assert!(coinbase.input[0] + .script_sig + .as_bytes() + .ends_with(&extranonce_prefix)); + } + #[test] fn test_share_validation_block_found_below_job_target_earns_network_difficulty() { // reuses the pre-mined share from test_share_validation_block_found: its hash