Skip to content

Commit 0edabd4

Browse files
committed
Add coinbase validation to Block::validate() with new error variants
Add validation checks to Block::validate() to ensure blocks have a valid coinbase: - Check for empty transaction list (NoTransactions error) - Verify first transaction is coinbase (InvalidCoinbase error) The validation now happens during Block::validate() rather than requiring every caller to check coinbase presence separately.
1 parent ca4d87d commit 0edabd4

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

bitcoin/src/blockdata/block.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,14 @@ impl BlockUncheckedExt for Block<Unchecked> {
118118
fn validate(self) -> Result<Block<Checked>, InvalidBlockError> {
119119
let (header, transactions) = self.into_parts();
120120

121+
if transactions.is_empty() {
122+
return Err(InvalidBlockError::NoTransactions);
123+
}
124+
125+
if !transactions[0].is_coinbase() {
126+
return Err(InvalidBlockError::InvalidCoinbase);
127+
}
128+
121129
if !check_merkle_root(&header, &transactions) {
122130
return Err(InvalidBlockError::InvalidMerkleRoot);
123131
}
@@ -405,6 +413,10 @@ pub enum InvalidBlockError {
405413
InvalidMerkleRoot,
406414
/// The witness commitment in coinbase transaction does not match the calculated witness_root.
407415
InvalidWitnessCommitment,
416+
/// Block has no transactions (missing coinbase).
417+
NoTransactions,
418+
/// The first transaction is not a valid coinbase transaction.
419+
InvalidCoinbase,
408420
}
409421

410422
impl From<Infallible> for InvalidBlockError {
@@ -418,6 +430,8 @@ impl fmt::Display for InvalidBlockError {
418430
match *self {
419431
InvalidMerkleRoot => write!(f, "header Merkle root does not match the calculated Merkle root"),
420432
InvalidWitnessCommitment => write!(f, "the witness commitment in coinbase transaction does not match the calculated witness_root"),
433+
NoTransactions => write!(f, "block has no transactions (missing coinbase)"),
434+
InvalidCoinbase => write!(f, "the first transaction is not a valid coinbase transaction"),
421435
}
422436
}
423437
}

0 commit comments

Comments
 (0)