Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 128 additions & 12 deletions sv2/channels-sv2/src/bip141.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
//! 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;
/// The only witness serialization flag BIP141 currently defines. Other nonzero values are
/// 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;
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;

Expand All @@ -31,6 +37,40 @@ 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,
}

/// 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
Expand All @@ -39,20 +79,25 @@ pub enum StripBip141Error {
/// 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<u8>, Vec<u8>)))` 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<u8>, Vec<u8>)))` with the stripped
/// `coinbase_tx_prefix` and `coinbase_tx_suffix`.
///
/// # 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 &lt; 4 bytes), or
/// [`StripBip141Error::FailedToDeserializeCoinbaseWitness`] when the suffix is too short to
Expand Down Expand Up @@ -84,6 +129,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
Expand Down Expand Up @@ -122,6 +175,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() {
Expand Down Expand Up @@ -234,11 +291,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];
Expand All @@ -252,7 +315,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];
Expand All @@ -266,7 +329,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;
Expand All @@ -275,7 +338,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]
Expand All @@ -287,7 +350,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),
Expand All @@ -298,7 +361,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
Expand All @@ -317,4 +380,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)
));
}
}
1 change: 0 additions & 1 deletion sv2/channels-sv2/src/client/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading